diff --git a/README.md b/README.md index e86de979..9b04e3e7 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the **Modes (November 2026): Duos, Trios, Creative, Box Fights and Zone Wars.** Five more ways to play with friends, made of Driftfall's own island, land shader, build pieces, editing, weapons, props and bots; Classic is the battle royale above, unchanged. **Picking one:** the menu has a Mode picker (Classic, Duos, Trios, Creative, Box Fights, Zone Wars, with the mode's options under it: Box Fights' team size 1v1 to 4v4, rounds to win 3, 5 or 7, bots fill in or off; Duos and Trios have only Bots, set in the lobby); in a party launch (party.js's room `p` + 6 characters, `partyRoom`) a mode's Bots is shown Off and locked with "No bots in party games", the host stores `bo: 0` and `modeRoster`/`sqRoster` add no bots whatever `bo` says, so Box Fights, Duos and Trios need people for two teams and wait as they do with Bots off (Creative's targets and sparring bots, which players add themselves, are unchanged); Practice (offline) plays the picked mode against practice bots, and a room you make starts in it. In a room the host (the usual host: the longest-present live player) picks the mode and its options in the lobby, and everyone sees the pick; the host presses Start (modes have no countdown, and can start with one person when bots fill in; Creative always can). Quick match rooms (`dz-pub-…`) are always Classic. The pause panel gives the host End for everyone (back to the lobby). Saved in the browser: `driftfall:mode` (the menu's pick) and `driftfall:opts:`, and Creative's loadout `driftfall:crload` and rarity `driftfall:crrar`. **Arenas:** a mode is played on its own arena, which takes the island's place while it is on (`setArena`): its own height grid in `TH` (so `terrainH`, walking, shots, builds, the land rules, bots' paths and both maps follow it unchanged), its own ground and sea meshes on the island's ground shader with its own control map (`arenaCtl`: paving with the shader's joints on the 4 m build grid, dirt tracks, darker marks), the island's trees, rocks, bushes and grass tufts (one mesh each, solid but unbreakable, in the arena's hash only), and an empty spatial hash, so none of the island's buildings, chests or pieces are there. The island's hash, ramps, heights, ground, sea, bots' grid and map picture are kept aside and put back exactly when the mode ends (`ISL`); an arena is made the first time it is needed and kept (`ARC`). Creative: a 128 m paved square at 4 m, a grassy rim with two hills, a beach. Box Fights: a flat paved circle with a fixed edge 24 m out (drawn as a low bank of the storm's cloud; nobody walks or builds past it), the two teams' boxes 8 m apart. Zone Wars: a round island about 140 m across with rolling ground and five hills (all under 15 m), rocks, pines and dirt tracks. **Creative:** unlimited scrap and ammo (∞ on the HUD), no storm, fly (the Fly key, Y, or Jump twice; Jump goes up and Fly down, Shift, goes down; on a phone FLY and DOWN buttons above the stick), Back to spawn (U), a knockout puts you back where you fell after 3 s, health and shield come back after 4 s out of a fight. Creative tools (I, or Creative tools in the pause panel): your four slots from every weapon and heal at any rarity, practice targets (stand-still bots, up to 12, put 6 m in front of you; knocked out, one stands again 2 s later), sparring bots (up to 4, put 14 m in front of you, with Box Fights' loadout and a mode bot's mind, so they come for whoever is near; knocked out, one comes back where it was put 3 s later; `pracArm`), Clear them all, Clear my builds and, for the host, Clear every build. Anyone may edit any build, and everyone in the room is in it whenever they join. **Box Fights:** two teams, Blue and Orange (colours always with the name), each starting in its own one-cell box of real build pieces (four walls, a floor and a roof, owned by the team, `T0`/`T1`: the team's to edit, anyone's to break), with a fixed loadout every round (Epic Pump Shotgun, SMG and Rifle, 3 Shield Fizz, 200 scrap, full shield); a 4 s countdown (3, 2, 1, FIGHT) with everyone frozen; no damage from team-mates (shots pass through them); last team standing takes the round, or after 2:30 the team with more health and shield left (a tie is nobody's); first to N. Team-mates are on the map and name tags are in the team's colour; a knocked-out player watches a team-mate. **Zone Wars:** everyone for themselves on random spots (`zwSpawns`) with a fixed loadout (Rare Pump Shotgun, Rifle and Drum SMG, 2 Shield Fizz, 300 scrap, 50 shield) and a fast storm (`ZW_PH`: six phases, closed in under two minutes) whose next circle jumps from a third of the way to nearly the edge of the last one, so part of it is often outside the old circle; last one standing takes the round (if the storm takes the last two together, nobody does); first to N. **Bots:** Box Fights fills each team, Zone Wars fills up to 8 (on by default, off in the options; Practice always fills). They use `botThinkM`: no loot, go for the nearest enemy (never a team-mate or a target), shoot through and break builds in the way, stay out of the storm. **Sync:** the host decides everything and puts it in its node. A mode's match state goes in a new key, `mx` (`md` the mode, `op` its options, and per round `rn` the round, `sc` the score as a string, `blue-orange` or `id:wins,…`, `tm` each roster place's team, `zs` Zone Wars' circles as `x,z,r;…`, `sid` the series, `rw` the round's winner, `fin`/`wn` at the end), while `ms` then just says lobby: pages from before the modes only read `ms`, so they sit a mode out in the lobby instead of playing it on the island, and Classic's `ms` is exactly what it was. Every page writes `gm: 1`, and only pages with it are put in a mode's roster (the lobby says how many people have an older copy). Each round is a match of its own (a new id), so `setupMatch` puts the arena, builds and everyone back between rounds and events from an old round are dropped; the boxes are built the same way on every page at a round's start, and someone arriving mid-round gets the builds as they stand from the host's build list (`bd`, whose owner field now also says 61/62 for a team's box). The host runs the bots and targets and lists them in its node (`bt`: `{id: [x, y, z, heading, pitch, health, shield, state, in hand, knockouts, 1 target / 2 sparring bot / 0, 1 down]}`), which the others draw with `netsmooth.js` like players; a bot's shots, builds and knockouts are the host's events marked `f` (the bot's id), which pages from before ignore; hits on a bot are sent to the host, as hits on a player go to that player. If the host leaves, the next one runs the bots from where they are (`takeBots`) and carries on the round and the score from the last `mx` it saw. Creative's commands (clear my builds, clear every build, add a target or a sparring bot, `fi: 1`, clear them) are events `k: 'cm'`; the host adds everyone who arrives to Creative's roster (only ever added to, so builds keep their owners in the build list). No Firebase paths or rules changed. **Stats:** the modes (Duos and Trios too) record nothing in the Leaderboards (no matches, wins, knockouts, placings or Elo; `recordStats` returns at once), so Driftfall's battle-royale boards and the miles worked from them only ever count Classic (solo). Play time is still counted by stats.js, as for any game, because it is time spent playing Driftfall. A separate set of keys would show nowhere (leaderboard.js lists only Driftfall's Classic stats) and only make every player's stats node bigger. **Cost:** an arena is one ground and one sea mesh in place of the island's, one props mesh and one tufts mesh (Creative measured 12 draw calls on the plain look); making one the first time takes a moment (its ground, sea, map and bots' grid). Nothing new is made every frame except the HUD's strings a few times a second. **Duos and Trios (`du`, `tr`):** the battle royale in teams of 2 or 3, on the island with the Drifter, loot and storm exactly as in Classic: in the code `GM` stays `'br'` and `SQ` is the team size, so everything Classic does is shared (see "Squads" in the script). Teams (`tm`, one base-36 digit per roster place) are the people in the order they joined the room (a Party that launches together joins together), filled with bots when Bots is on, plus bot teams up to 12 players (`sqRoster`); Practice is you and your bot team-mates against bot teams (6 teams of 2, 4 of 3). Online, as in Box Fights, the host runs the bots (`bt`, now also with the Drifter, falling and gliding states) and sends their shots, loot and knockouts as events marked `f`; a team's bots jump just after their person and land near them, and catch up with them when they fall 24 m behind. **No friendly fire:** shots pass through team-mates and a team-mate's hit is never applied. **Name tags:** team-mates' tags are blue and show through anything from anywhere; team-mates are blue dots on both maps; a dead player watches a team-mate. **Down, not out:** when your health runs out while someone on your team is still up, you go down instead (`dn: 1` in your node; event `k: 'dn'`): 100 health that bleeds away at 3.4 a second, crawling at a third of the speed, lying face down (lower hit boxes, a lower camera), no shooting, building, editing, opening or healing (on a phone Fire, Aim, Reload and Edit hide). A team-mate holding Use (G, or the touch button, which reads REVIVE) within 2.4 m for 4 s picks you up with 30 health (event `k: 'rv'`); bots go to a downed team-mate within 45 m and do the same, and a downed bot crawls to its nearest team-mate. Anyone else's shots, the storm or bleeding out finish you, and once nobody on the team is up everyone down on it is out. As with every hit, each browser decides this for its own player (and the host for its bots). **Winning:** the last team with anyone left (`wt` in the match state); the HUD counts teams left, the end panel shows the team's place out of the teams. The match state is in `mx`, like the other modes, so a page from before sits a Duos or Trios match out. **Tests** (`window.__dz`, webdriver only) add `GM`, `SQ`, `arenaOn`, `setArena`, `modeStart`, `botNet`, `syncBots`, `sqRoster`, `goDown`, `sqUp` and the rest of the mode functions. **Checked** in Practice for every mode (rounds, scores, boxes put back, the storm, flying, tools, targets and sparring bots, downs, revives by you and by bots, team wipes, a team win) and online with two browsers in one room for Creative (shared builds, a sparring bot, clearing), Box Fights 1v1 (a round won, the next one set up), Zone Wars (the same circles on both) and Duos (both on one team with 10 host-run bots, no friendly fire, a down seen by the team-mate and a revive by them, a host bot downed by the other player), at 1280 × 800, 375 × 812 and 812 × 375 with no console errors. Weak or not checked: Trios online, 3v3 and 4v4 Box Fights online, a host leaving mid-match in a mode (the bots carry on with the next host from where they are, with a basic loadout in Duos and Trios), a full room of 30, and a real phone; you can't pick your team (it's join order); downed players' lying pose is the falling pose on the ground. Collision rules (keep them if you touch movement): you and the Entity are boxes 0.72 m wide and 1.95 m tall; map walls, posts, pillars (0.9 m and 1.5 m), office partitions (1.25 m tall, 12 cm thick: jump onto or over them) and built walls and floors are solid boxes. A ramp is solid too (`inRamp`): a sloping sheet 0.33 m thick whose top you walk on. With the middle of a body over a ramp, the body is clear of it only on top (feet no more than a 0.6 m step below the surface, which is how you step onto the low end or land on it from a jump) or underneath with its head under the ramp's underside; anything between counts as inside the ramp, and movement never goes there: walking or jumping into a ramp from the side or from behind stops you (`rampBlocks`), under one you can only stand where there is head room (the 1.5 m under the high end) and a jump there stops at the underside, and nothing gets up through a ramp from below. (Until November 2026 ramps were walkable surfaces only and could be walked and jumped through.) Movement goes one axis at a time so you slide along walls; a move that would enter a solid is dropped unless it is a step of up to 0.6 m onto something with head room; and a frame that would move you more than 0.25 m (below about 25 fps; frames are capped at 50 ms) is split into shorter steps, so nothing as thin as a wall can be skipped over. You stand on anything your box overlaps and fall only once you are clear of it, and walking up a ramp into a floor stops you under it (if a floor dropped on you pushed you down below a ramp's surface, you can still walk back down the ramp, just not further up). The only way into a solid is a build landing on you (your own, the Entity's or another player's), and the game then shoves you out the shortest way (sideways out of a wall, up onto or down from under a floor) that ends inside the map without passing through any other wall or build on the way, rather than trapping you or letting you walk through it; the same push-out runs at spawn and on every step. A ramp that lands on you (`rampOut`) lifts you onto it if that is no more than 2 m up, so a ramp placed in the cell you are standing in puts you on it ready to climb; otherwise you are moved the shortest free way: along the slope to where there is head room underneath or to where it is low enough to step onto, out of a side, or up or down. Other players' drawn positions are clamped to the map and pushed out of solid boxes too (not ramps: each player's own page keeps them out of those), so a corner cut between two updates, or a late update carried on, never draws (or lets you shoot) someone inside a wall. Shots are rays tested against every solid, ramp surface, the floor and the ceiling before players, so they can't pass through walls or builds. - `e63334287a3deaa3/ironwing/`: Ironwing (**preview, admin page only**; Back Room folder; the display name lives in ONE constant, `IW.GAME_NAME` in `js/core.js`), the air entry in the Midnight Ops war series: a single-player campaign of carrier-fighter missions over the sea and the islands, flown from a third-person chase camera (three.js r187 with the r128 compatibility layer from `/lib/three/`, plus `../autores.js`; Web Audio; no Firebase, nothing online). **Preview gate:** like Midnight Ops, `window.IW_PREVIEW = true` at the top of `index.html` lets the game run only in a browser holding `ironwing:preview` = `1` (set by the "Ironwing (preview)" button on the admin page); without it the page says "Not available yet" and loads none of the game. While the preview is on, every mission is open for testing (`IW.unlocked`); set `IW_PREVIEW` to false to open the game, which also turns on the normal unlock order and play-time counting (`stats.js`), and then give it its card, phone row and What's new entry. **Missions** (`js/missions/`, registered as data with `IW.missions.register({id, num, title, kind, line, mood, briefing, loadout: {bombs, rockets}, build(M, data), setup(M, cp, data), medals})`, the same shape as Midnight Ops'): 0 **Flight School** (training: catapult launch from the carrier Resolute, five ring gates, four target drones, a practice raft to bomb, land back aboard), 1 **Dawn Strike** (carrier strike: sink two destroyers of a flotilla steaming west, a cruiser for the bonus, fighters overhead), 2 **Hold the Atoll** (base defence: scramble from Kestrel Field and break up three raids of level and dive bombers with escorts; the base is lost under 35% integrity), 3 **Fleet Shield** (fleet defence: torpedo bombers low from the west, dive bombers from the clouds, then both; keep the Resolute afloat), 4 **Fire on Kalder Reef** (base attack at sunset: fuel tanks, radar mast and heavy flak, fighters scrambling from the runway, then home to land). The script API is `M.obj/done/lose/when/after/say/checkpoint/fail/complete`; `M.ship()` and `M.structure()` spawn things that stay destroyed when a checkpoint is restored (each has a `uid`, and the checkpoint keeps the list of uids destroyed so far); three medal goals give gold, silver or bronze. To add a mission, copy one in `js/missions/`, give it the next `num`, and add its ` + + +Black Tie + + + + + + + + + + +
+ + + + +

Black Tie

Loading

+ + + + + + + + + + + + + + + + + + diff --git a/e63334287a3deaa3/blacktie/js/ai.js b/e63334287a3deaa3/blacktie/js/ai.js new file mode 100644 index 00000000..ca25acf5 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/ai.js @@ -0,0 +1,561 @@ +/* + * The villain's guards, the alert level, and the civilians (RP.AI, RP.Alert). + * + * Guards: unaware -> suspicious -> alerted. Awareness builds from what they see (distance, light, the player's stance + * and cover, field of view, smoke) and hear (shots, fights, footsteps, explosions), times the difficulty. Alerted + * guards call it in on the radio, pick cover that protects them from the player (enforcers and elites also flank), + * peek and fire in bursts, reload behind cover, push in or retreat by health and aggression, swing a rifle butt up + * close, and (elites) throw grenades at a player who stays in cover. Only a few may shoot at once ("attack tokens"), + * and hits are rolled from distance, the player's speed and cover, so fights are fair. Types differ in accuracy, + * reaction time, aggression, health and coordination: sentry < enforcer < elite; marksmen hold long sight lines. + * + * Alert level (replaces a police "wanted" level): 0..5 tiers. Seen fighting -> 1; kills and time in combat raise it; + * each tier brings more and tougher guards in from out of sight, with radio chatter. Break line of sight and stay + * out of the search circle long enough and it drops a tier at a time. + * + * Civilians can't be hurt: gunfire or explosions near them, or a gun pointed at them, make them run and cower. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W, TU = RP.TUNING, WP = RP.Weapons; + var AI = RP.AI = { _uid: 0 }; + var D2R = Math.PI / 180; + var TYPES = { + sentry: { kind: 'sentry', hp: 100, armour: 0, acc: 0.42, react: 0.9, aggr: 0.35, coord: 0.2, weapon: 'vespa', sight: 34, fov: 110, name: 'Sentry' }, + enforcer: { kind: 'enforcer', hp: 120, armour: 40, acc: 0.55, react: 0.65, aggr: 0.7, coord: 0.6, weapon: 'tern', sight: 40, fov: 120, name: 'Enforcer' }, + shotgunner: { kind: 'enforcer', hp: 130, armour: 40, acc: 0.6, react: 0.6, aggr: 0.9, coord: 0.5, weapon: 'breaker', sight: 30, fov: 120, name: 'Enforcer' }, + elite: { kind: 'elite', hp: 150, armour: 70, acc: 0.68, react: 0.45, aggr: 0.8, coord: 0.9, weapon: 'gale', sight: 46, fov: 130, name: 'Elite', grenades: 2 }, + gunner: { kind: 'elite', hp: 170, armour: 80, acc: 0.5, react: 0.55, aggr: 0.6, coord: 0.7, weapon: 'mauler', sight: 46, fov: 120, name: 'Elite' }, + marksman: { kind: 'marksman', hp: 90, armour: 0, acc: 0.8, react: 0.8, aggr: 0.2, coord: 0.4, weapon: 'longreach', sight: 90, fov: 80, name: 'Marksman', stay: true } + }; + AI.TYPES = TYPES; + var LINES = { + spot: ['Intruder! By the {p}!', 'Contact, contact!', 'I see someone, weapon out!', 'Hey! Stop right there!'], + hear: ['Did you hear that?', 'Something by the {p}...', 'Going to take a look.'], + lost: ['Lost visual.', 'Where did they go?', 'Spread out, find them.'], + calm: ['Must have been nothing.', 'All quiet. Back to it.'], + down: ['Man down!', 'We lost one!'], + reload: ['Reloading!', 'Changing mag!'], + nade: ['Grenade out!', 'Flush them!'], + flank: ['Moving round the side.', 'Flanking left!', 'I will go wide.'], + cover: ['Get to cover!', 'They are behind the {c}!'] + }; + var RADIO = ['Control to all teams: intruder on the grounds.', 'All units, the {p}. Converge.', 'Bringing in the response team. Hold them there.', 'Send the elite squad. Now.', 'Every team we have, move. Do not let them reach the harbour.']; + var RADIO_DOWN = ['Control: stand down to search pattern.', 'Control: sweep the area, stay sharp.', 'Control: all clear, back to posts.']; + AI.line = function (key, g) { + var l = LINES[key]; if (!l) return ''; + var s = l[Math.floor(Math.random() * l.length)]; + return s.replace('{p}', placeName(g ? g.pos : RP.G.player.pos)).replace('{c}', 'wall'); + }; + function placeName(p) { + var S = RP.map && RP.map.spots, best = 'town', bd = 1e9; + var names = { piazza: 'piazza', steps: 'cathedral steps', marina: 'waterfront', harbour: 'harbour', villaTerrace: 'villa terrace', villaGate: 'villa gate', lemons: 'lemon terraces', mainStreet: 'main street', tower: 'watchtower', villaStudy: 'villa', + tunnel1: 'first tunnel', belvedere: 'belvedere', terraces: 'lemon farm', coveBridge: 'viaduct', cove: 'cove', busStop: 'bus stop', tunnel2: 'second tunnel', bowlTop: 'top road', piazzetta: 'piazzetta', churchSquare: 'church square', bowlBeach: 'beach' }; + for (var k in names) { var s = S[k]; if (!s) continue; var d = Math.hypot(p.x - s.x, p.z - s.z); if (d < bd) { bd = d; best = names[k]; } } + return best; + } + AI.place = placeName; + + // ------------------------------------------------------------------ spawn + AI.spawnGuard = function (type, spot, opts) { + opts = opts || {}; + var ty = TYPES[type] || TYPES.sentry, df = RP.diff(); + var a = RP.Chars.spawn(ty.kind); + RP.R.scene.add(a.root); + var y = spot.y != null ? spot.y : W.ground(spot.x, spot.z, W.terrainH(spot.x, spot.z) + 1.4).y /* street level, not a roof above it */; + var g = { + actor: a, team: 'guard', type: type, ty: ty, alive: true, radius: TU.radius, pos: new T.Vector3(spot.x, y, spot.z), yaw: spot.yaw || 0, + hp: ty.hp * df.hp, maxHp: ty.hp * df.hp, armour: ty.armour, weapon: opts.weapon || ty.weapon, mag: 0, aware: 0, state: opts.patrol ? 'patrol' : 'idle', + post: { x: spot.x, z: spot.z, yaw: spot.yaw || 0 }, patrol: opts.patrol || null, pi: 0, wait: Math.random() * 3, + path: null, pathI: 0, repath: 0, speed: 0, moveYaw: 0, think: Math.random() * 0.3, lastSeen: null, lastSeenT: -99, seeT: 0, + cover: null, coverT: 0, peek: 0, burst: 0, fireCd: 0, reloadT: 0, meleeCd: 0, grenades: ty.grenades || 0, nadeT: 10 + Math.random() * 6, + stagger: 0, down: false, ko: false, investigate: null, searchT: 0, flank: Math.random() < ty.coord * 0.6, sees: false, token: false, react: 0, barkT: 0, strafeT: 0 + }; + var d = WP.DEFS[g.weapon]; g.mag = d.mag; g.def = d; g.uid = ++AI._uid; + var m = WP.model(g.weapon); a.hold(m); g.model = m; + g.takeDamage = function (amt, info) { damage(g, amt, info); }; + a.root.position.copy(g.pos); a.root.rotation.y = g.yaw; + RP.G.guards.push(g); RP.G.ents.push(g); + return g; + }; + AI.spawnCiv = function (spot, opts) { + opts = opts || {}; + var a = opts.actor || RP.Chars.spawn('guest', opts); // (a traffic driver getting out keeps their own actor) + if (!a.root.parent) RP.R.scene.add(a.root); + var y = spot.y != null ? spot.y : W.ground(spot.x, spot.z, W.terrainH(spot.x, spot.z) + 1.4).y /* street level, not a roof above it */; + var c = { actor: a, team: 'civ', alive: true, radius: TU.radius, pos: new T.Vector3(spot.x, y, spot.z), yaw: spot.yaw == null ? Math.random() * 6.28 : spot.yaw, state: 'idle', + home: { x: spot.x, z: spot.z }, wander: opts.wander == null ? 6 : opts.wander, wait: Math.random() * 6, path: null, pathI: 0, speed: 0, fear: 0, think: Math.random(), talk: opts.talk }; + c.takeDamage = function (amt, info) { c.scare(info && info.point || c.pos, 4); }; + c.scare = function (from, k) { if (c.fear < 3 || k > c.fear) { c.fear = Math.max(c.fear, k); c.from = from.clone ? from.clone() : new T.Vector3(from.x, from.y, from.z); c.state = 'flee'; c.path = null; } }; + a.root.position.copy(c.pos); a.root.rotation.y = c.yaw; + if (c.talk) a.playFull('alert', { loop: true, fade: 0, speed: 0.6 + Math.random() * 0.3 }); + RP.G.civilians.push(c); RP.G.ents.push(c); + return c; + }; + + // ------------------------------------------------------------------ damage and reactions + function damage(g, amt, info) { + if (!g.alive) { if (g.actor.rag && info && info.dir) RP.Rag.push(g.actor, info.dir.clone().multiplyScalar(info.force || 1), info.point); return; } + if (g.ko) return; + // armour soaks torso hits + if (g.armour > 0 && info && info.region === 'torso') { var ab = Math.min(g.armour, amt * 0.5); g.armour -= ab; amt -= ab; } + // elites sometimes slip a melee attack + if (info && info.melee && g.type === 'elite' && Math.random() < 0.25 && !g.stagger && RP.G.player.counterT <= 0) { g.dodgeT = 0.4; g.actor.move('dodge'); return; } + g.hp -= amt; + var from = info && info.from; + if (from && from.team === 'player') { alertGuard(g, from.pos, true); if (g.aware < 1) g.aware = 1; } + if (info && info.dir) g.actor.flinch(-info.dir.x, -info.dir.z, Math.min(1.2, amt / 30)); + if (g.hp <= 0) { kill(g, info); return; } + if (info && (info.explosion || (info.melee && info.force > 2) || info.car)) { + g.actor._vel = new T.Vector3(); + RP.Rag.start(g.actor, info.dir.clone().multiplyScalar(info.force || 3).setY(info.explosion ? 3.5 : 1.2), info.point); + g.down = true; g.downT = 2.2 + Math.random(); g.cover = null; g.path = null; + } else if (amt > 28 || (info && info.melee && info.force > 1) || (info && info.region === 'leg' && amt > 18)) { + g.stagger = info && info.melee ? 0.7 : 0.55; g.actor.playFull(info && info.melee ? 'stagger' : 'hit', { fade: 0.05, speed: info && info.melee ? 1.5 : 1 }); + g.burst = 0; + } + if (g.hp < g.maxHp * 0.3 && g.ty.aggr < 0.5 && Math.random() < 0.6) { g.retreat = true; g.cover = null; } + } + function kill(g, info) { + g.alive = false; g.state = 'dead'; g.cover && (g.cover.taken = null); g.cover = null; + var imp = info && info.dir ? info.dir.clone().multiplyScalar(info.force || 1.5) : new T.Vector3(); + if (info && info.region === 'head') imp.multiplyScalar(1.3); + if (!g.actor.rag) { g.actor._vel = new T.Vector3(Math.sin(g.yaw), 0, Math.cos(g.yaw)).multiplyScalar(g.speed); RP.Rag.start(g.actor, imp.setY(Math.max(imp.y, 0.5)), info && info.point, { dead: true }); } + else g.actor.rag.alive = false; + // drop the weapon as an ammo pickup + if (g.model) { + var hp = g.actor.bones.hand_r ? g.actor.bones.hand_r.getWorldPosition(new T.Vector3()) : g.pos.clone().setY(g.pos.y + 1); + g.actor.hold(null); g.model = null; + var dv = imp.clone().multiplyScalar(0.6).add(new T.Vector3((Math.random() - 0.5) * 1.5, 1.5, (Math.random() - 0.5) * 1.5)); + RP.Items.dropWeapon(g.weapon, hp, dv, { mag: g.mag || 0, reserve: Math.ceil(g.def.mag * (0.5 + Math.random())) }, g.yaw); + } + RP.emit('guardDown', g, info); + if (info && info.from && info.from.team === 'player') { RP.G.player.kills++; RP.Alert.event('kill', g); } + // nearby guards react + RP.G.guards.forEach(function (o) { if (o !== g && o.alive && o.pos.distanceTo(g.pos) < 22) { alertGuard(o, RP.G.player.pos, false); if (Math.random() < 0.3) say(o, 'down'); } }); + } + AI.takenDown = function (g, p) { + g.ko = true; g.alive = false; g.state = 'ko'; g.cover = null; g.path = null; + g.yaw = p.yaw; g.actor.root.rotation.y = g.yaw; + g.actor.setUpper(null, 0.1); + g.actor.playFull('takedownVictim', { fade: 0.1, hold: true }); + if (g.model) g.actor.hold(null); + RP.emit('guardDown', g, { takedown: true }); + setTimeout(function () { if (!g.actor.rag) { RP.Rag.start(g.actor, new T.Vector3(), null, { dead: true }); } }, 2500); + }; + + // ------------------------------------------------------------------ speaking (subtitle + sound) + function say(g, key) { + if (RP.G.time - (g.barkT || -9) < 3) return; + g.barkT = RP.G.time; + RP.Audio.bark(g.pos, key === 'spot' || key === 'nade'); + if (g.pos.distanceTo(RP.G.player.pos) < 35) RP.emit('sub', g.ty.name + ': ' + AI.line(key, g), 2.2); + } + AI.say = say; + + // ------------------------------------------------------------------ perception + var _e = new T.Vector3(), _t = new T.Vector3(); + function canSee(g, p) { + if (!p.alive) return 0; + var eye = _e.set(g.pos.x, g.pos.y + 1.65, g.pos.z), d = eye.distanceTo(_t.set(p.pos.x, p.pos.y + 1.2, p.pos.z)); + var range = g.ty.sight * (RP.G.night ? 0.7 : 1) * (g.state === 'combat' ? 1.4 : 1); + if (d > range) return 0; + var to = _t.clone().sub(eye); to.y = 0; to.normalize(); + var ang = Math.acos(M.clamp(to.dot(new T.Vector3(Math.sin(g.yaw), 0, Math.cos(g.yaw))), -1, 1)) / D2R; + var fov = g.ty.fov * (g.state === 'combat' || g.state === 'search' ? 1.6 : 1); + if (ang > fov / 2 && d > 2.2) return 0; + if (RP.FX.inSmoke(eye) || RP.FX.inSmoke(p.pos) ) return 0; + // two points on the body: head and chest + var head = W.los(eye.x, eye.y, eye.z, p.pos.x, p.pos.y + 1.6, p.pos.z), chest = head || W.los(eye.x, eye.y, eye.z, p.pos.x, p.pos.y + (p.stealth ? 0.8 : 1.15), p.pos.z); + if (!head && !chest) return 0; + var k = (1 - d / range) * (head && chest ? 1 : 0.6) * p.vis * (ang < 35 ? 1.3 : 0.8) * RP.diff().aware; + if (p.aiming || p.fireHeld) k *= 1.5; + if (d < 4) k *= 2.2; + return k; + } + function alertGuard(g, pos, direct) { + if (!g.alive) return; + g.lastSeen = pos.clone(); g.lastSeenT = RP.G.time; + if (g.state !== 'combat') { g.react = g.ty.react * RP.diff().react * (direct ? 0.5 : 1) + Math.random() * 0.3; g.state = 'combat'; g.cover = null; g.path = null; } + g.aware = 1; + } + AI.alertGuard = alertGuard; + + // ------------------------------------------------------------------ movement along a path + function goTo(g, x, z, dt) { + if (!g.path || g.repath <= 0 || !g.goal || Math.hypot(g.goal.x - x, g.goal.z - z) > 1.5) { + g.goal = { x: x, z: z }; g.path = W.path(g.pos.x, g.pos.z, x, z, 6000); g.pathI = 1; g.repath = 2 + Math.random(); + if (!g.path) { g.path = [{ x: g.pos.x, z: g.pos.z }, { x: x, z: z }]; } + } + g.repath -= dt; + var tgt = g.path[Math.min(g.pathI, g.path.length - 1)]; + var dx = tgt.x - g.pos.x, dz = tgt.z - g.pos.z, d = Math.hypot(dx, dz); + if (d < 0.6 && g.pathI < g.path.length - 1) { g.pathI++; return goTo(g, x, z, 0); } + return { dx: d > 1e-3 ? dx / d : 0, dz: d > 1e-3 ? dz / d : 0, d: Math.hypot(x - g.pos.x, z - g.pos.z) }; + } + function moveBody(e, dx, dz, speed, dt, faceMove) { + e.speed = M.approach(e.speed, speed, speed > e.speed ? 7 : 10, dt); + // separation from others nearby + var sx = 0, sz = 0; + RP.G.ents.forEach(function (o) { if (o === e || !o.alive || o.team === 'player' && e.team !== 'civ') return; var ox = e.pos.x - o.pos.x, oz = e.pos.z - o.pos.z, d2 = ox * ox + oz * oz; if (d2 < 0.9 && d2 > 1e-4) { var d = Math.sqrt(d2); sx += ox / d * (0.95 - d); sz += oz / d * (0.95 - d); } }); + var mx = dx * e.speed + sx * 2, mz = dz * e.speed + sz * 2; + W.move(e.pos, mx * dt, mz * dt, e.radius, 1.7); + var gr = W.ground(e.pos.x, e.pos.z, e.pos.y + 0.5, 0.5); + e.pos.y = M.damp(e.pos.y, gr.y, 18, dt); + if (faceMove && e.speed > 0.2) e.yaw = M.approachAngle(e.yaw, Math.atan2(dx, dz), 7, dt); + e.moveYaw = Math.atan2(dx, dz); + } + + // ------------------------------------------------------------------ cover choice + var _cl = []; + function pickCover(g, p) { + var pts = W.coverNear(g.pos.x, g.pos.z, 22, _cl), best = null, bs = -1e9; + var toP = p.pos.clone().sub(g.pos); var dP = toP.length(); + var range = g.def.range ? g.def.range[1] * 0.7 : 30; + for (var i = 0; i < pts.length; i++) { + var c = pts[i]; if (c.taken && c.taken !== g) continue; + if (Math.abs(c.y - g.pos.y) > 6) continue; + var pc = new T.Vector3(p.pos.x - c.x, 0, p.pos.z - c.z), dpc = pc.length(); pc.divideScalar(dpc || 1); + var protect = pc.x * c.dx + pc.z * c.dz; // 1: the cover faces the player + if (protect < 0.45) continue; + var dSelf = Math.hypot(c.x - g.pos.x, c.z - g.pos.z); + var s = protect * 4 - dSelf * 0.18; + if (dpc > range) s -= (dpc - range) * 0.3; + if (dpc < 6) s -= (6 - dpc) * 1.2; + if (g.retreat) s += dpc * 0.15; + else s -= Math.abs(dpc - range * 0.6) * 0.05 * g.ty.aggr; + if (g.flank) { var side = new T.Vector3(c.x - p.pos.x, 0, c.z - p.pos.z).normalize(), pf = new T.Vector3(Math.sin(p.yaw), 0, Math.cos(p.yaw)); s += (1 - Math.abs(side.dot(pf))) * 2.5 * g.ty.coord; } + if (c.edge) s += 0.6; if (c.low) s += 0.3; + if (s > bs) { bs = s; best = c; } + } + return best; + } + + // ------------------------------------------------------------------ the guard brain (fixed step) + var tokens = 0; + AI.step = function (dt) { + var p = RP.G.player, df = RP.diff(); + tokens = 0; + RP.G.guards.forEach(function (g) { if (g.alive && g.token) tokens++; }); + var maxTok = RP.settings.difficulty === 'hard' ? 4 : RP.settings.difficulty === 'easy' ? 2 : 3; + for (var i = 0; i < RP.G.guards.length; i++) { + var g = RP.G.guards[i]; + if (!g.alive) continue; + if (g.down) { g.downT -= dt; if (g.downT <= 0 && RP.Rag.settled(g.actor)) { var r = RP.Rag.release(g.actor); g.pos.set(r.x, W.ground(r.x, r.z, g.pos.y + 1).y, r.z); g.yaw = r.yaw; g.actor.move('getUp'); g.down = false; g.stagger = 1.0; } else { if (g.actor.rag) g.pos.set(g.actor.rag.p.pelvis.x, g.pos.y, g.actor.rag.p.pelvis.z); continue; } } + var dP = g.pos.distanceTo(p.pos); + // far and calm: think rarely + g.think -= dt; + var thinkNow = g.think <= 0; + if (thinkNow) g.think = g.state === 'combat' ? 0.12 : dP > 80 ? 0.6 : 0.22; + g.fireCd -= dt; g.meleeCd -= dt; g.nadeT -= dt; g.stagger = Math.max(0, g.stagger - dt); g.dodgeT = Math.max(0, (g.dodgeT || 0) - dt); + // ---- perception + if (thinkNow) { + var k = canSee(g, p), period = g.state === 'combat' ? 0.12 : dP > 80 ? 0.6 : 0.22; + g.sees = k > 0; + if (k > 0) { + g.aware = Math.min(1.2, g.aware + k * period * (g.state === 'suspicious' ? 2.6 : 1.6) / Math.max(0.3, df.react)); + if (g.aware >= 1 || g.state === 'combat') { + if (g.state !== 'combat') { say(g, 'spot'); RP.Alert.spotted(g); } + alertGuard(g, p.pos, false); + RP.Alert.seen(p.pos); + } else if (g.aware > 0.35 && g.state !== 'suspicious') { g.state = 'suspicious'; g.investigate = p.pos.clone(); g.searchT = 6; say(g, 'hear'); RP.emit('suspicious', g); } + else if (g.state === 'suspicious') g.investigate = p.pos.clone(); + } else if (g.state !== 'combat') g.aware = Math.max(0, g.aware - period * 0.12); + // hearing + for (var n = 0; n < RP.Combat.noises.length; n++) { + var no = RP.Combat.noises[n]; if (no.src === g || (no.heard && no.heard[g.uid])) continue; + no.heard = no.heard || {}; no.heard[g.uid] = 1; + var dn = no.p.distanceTo(g.pos); + if (dn < no.r * df.aware) { + if (no.kind === 'shot' || no.kind === 'explosion') { if (g.state !== 'combat') { alertGuard(g, no.src && no.src.team === 'player' ? no.p : g.pos, false); say(g, 'spot'); RP.Alert.spotted(g); } } + else if (g.state === 'idle' || g.state === 'patrol' || g.state === 'suspicious') { + g.aware = Math.min(0.95, g.aware + 0.3); g.state = 'suspicious'; g.investigate = no.p.clone(); g.searchT = 7; + if (Math.random() < 0.5) say(g, 'hear'); + } + } + } + } + if (g.stagger > 0 || g.dodgeT > 0) { g.speed = M.approach(g.speed, 0, 10, dt); continue; } + // ---- behaviour + if (g.state === 'idle' || g.state === 'patrol') calm(g, dt); + else if (g.state === 'suspicious') suspicious(g, dt); + else if (g.state === 'combat') combat(g, p, dt, dP, maxTok); + else if (g.state === 'search') search(g, dt); + } + }; + function calm(g, dt) { + g.actor._up = 'holdRifle'; + if (g.patrol) { + var wp = g.patrol[g.pi]; + if (g.wait > 0) { g.wait -= dt; g.speed = M.approach(g.speed, 0, 6, dt); if (wp.yaw != null) g.yaw = M.approachAngle(g.yaw, wp.yaw, 2, dt); return; } + var mv = goTo(g, wp.x, wp.z, dt); + if (mv.d < 0.8) { g.pi = (g.pi + 1) % g.patrol.length; g.wait = wp.wait == null ? 2 + Math.random() * 3 : wp.wait; g.path = null; return; } + moveBody(g, mv.dx, mv.dz, TU.walk * 0.9, dt, true); + } else { + var d = Math.hypot(g.post.x - g.pos.x, g.post.z - g.pos.z); + if (d > 1) { var m2 = goTo(g, g.post.x, g.post.z, dt); moveBody(g, m2.dx, m2.dz, TU.walk, dt, true); } + else { g.speed = M.approach(g.speed, 0, 6, dt); g.wait -= dt; if (g.wait < 0) { g.wait = 4 + Math.random() * 5; g.lookYaw = g.post.yaw + (Math.random() - 0.5) * 1.6; } g.yaw = M.approachAngle(g.yaw, g.lookYaw == null ? g.post.yaw : g.lookYaw, 1.2, dt); } + } + } + function suspicious(g, dt) { + g.actor._up = 'aimIdle'; + var t = g.investigate; + var mv = goTo(g, t.x, t.z, dt); + if (mv.d > 1.5) moveBody(g, mv.dx, mv.dz, TU.walk, dt, true); + else { g.speed = M.approach(g.speed, 0, 6, dt); g.searchT -= dt; g.yaw += Math.sin(RP.G.time * 0.9 + g.post.x) * dt * 1.2; } + if (g.searchT <= 0 || (mv.d < 1.5 && g.searchT < 3 && g.aware < 0.2)) { g.state = g.patrol ? 'patrol' : 'idle'; g.aware = 0; g.path = null; if (Math.random() < 0.5) say(g, 'calm'); } + g.searchT -= dt * 0.3; + } + function search(g, dt) { + g.actor._up = 'aimIdle'; + if (!g.searchPt || g.searchPtT <= 0) { + var c = RP.Alert.searchCentre || g.lastSeen || g.pos, r = RP.Alert.searchR || 15; + g.searchPt = { x: c.x + (Math.random() - 0.5) * r * 1.4, z: c.z + (Math.random() - 0.5) * r * 1.4 }; g.searchPtT = 6 + Math.random() * 5; + } + g.searchPtT -= dt; + var mv = goTo(g, g.searchPt.x, g.searchPt.z, dt); + if (mv.d > 1.2) moveBody(g, mv.dx, mv.dz, TU.walk * 1.3, dt, true); else { g.speed = 0; g.searchPtT -= dt * 2; g.yaw += dt * 0.8; } + if (RP.Alert.level === 0) { g.state = g.patrol ? 'patrol' : 'idle'; g.aware = 0; g.path = null; } + } + function combat(g, p, dt, dP, maxTok) { + var d = g.def; + if (g.react > 0) { g.react -= dt; g.speed = M.approach(g.speed, 0, 8, dt); faceTo(g, g.lastSeen || p.pos, dt, 6); g.actor._up = 'aimIdle'; return; } + var seen = g.sees, lastT = RP.G.time - g.lastSeenT; + if (seen) { g.lastSeen = p.pos.clone(); g.lastSeenT = RP.G.time; } + if (!p.alive) { g.state = 'search'; return; } + // lost them for a while: search + if (!seen && lastT > 9) { g.state = 'search'; g.cover = null; if (Math.random() < 0.5) say(g, 'lost'); return; } + // reload + if (g.mag <= 0) { + if (g.reloadT <= 0) { g.reloadT = d.reload * 1.3; g.reloadT0 = g.reloadT; if (Math.random() < 0.4) say(g, 'reload'); RP.Audio.mech('magOut', g.pos); } + g.reloadT -= dt; g.actor.reloadU = g.reloadT > 0 && g.reloadT0 ? 1 - g.reloadT / g.reloadT0 : -1; + if (g.reloadT <= 0) { g.mag = d.mag; RP.Audio.mech('magIn', g.pos); } + } + // melee up close + if (dP < 1.7 && g.meleeCd <= 0 && p.alive) { + g.meleeCd = 1.6; g.windup = 0.38; g.actor.move('gunWhip', { speed: 0.9 }); + } + if (g.windup > 0) { + g.windup -= dt; faceTo(g, p.pos, dt, 10); + if (g.windup <= 0) { + if (g.pos.distanceTo(p.pos) < 1.8) { g.yaw = Math.atan2(p.pos.x - g.pos.x, p.pos.z - g.pos.z); RP.Combat.melee(g, 1.8, 90, 16 * RP.diff().aggr, { knock: 1.4 }); } + } + g.speed = M.approach(g.speed, 0, 8, dt); return; + } + // grenade at a player who has been in cover a while + if (g.grenades > 0 && g.nadeT <= 0 && seen && dP > 8 && dP < 26 && p.state === 'cover' && p.st > 4) { + g.grenades--; g.nadeT = 14; say(g, 'nade'); + var tgt = p.pos.clone(), from = g.pos.clone(); from.y += 1.6; + var dx = tgt.x - from.x, dz = tgt.z - from.z, L = Math.hypot(dx, dz), tf = L / 13; + var v = new T.Vector3(dx / tf, (tgt.y - from.y + 0.5 * 9.8 * tf * tf) / tf, dz / tf); + g.actor.playUpper('throw', { speed: 1.5 }); + setTimeout(function () { if (g.alive) RP.Combat.throwProj('frag', g, from, v, WP.DEFS.frag); }, 400); + } + // cover: choose (or re-choose when flanked / every few seconds) + g.coverT -= dt; + if (!g.cover || g.coverT <= 0 || coverBroken(g, p)) { + if (g.cover) g.cover.taken = null; + g.cover = g.ty.stay && g.post ? null : pickCover(g, p); + if (g.cover) { g.cover.taken = g; if (g.flank && Math.random() < 0.3) say(g, 'flank'); } + g.coverT = 6 + Math.random() * 6; g.atCover = false; g.path = null; + } + var shooting = false; + if (g.cover && !g.atCover) { + var mv = goTo(g, g.cover.x, g.cover.z, dt); + // run there, shooting on the move at a lower rate if they can see the player + moveBody(g, mv.dx, mv.dz, 3.7 * (g.retreat ? 1.2 : 1), dt, !seen); + if (seen) faceTo(g, p.pos, dt, 8); + if (mv.d < 0.5) { g.atCover = true; g.peekT = 0.6 + Math.random(); g.peek = 0; } + shooting = seen && Math.random() < 0.5; + } else if (g.cover && g.atCover) { + g.speed = M.approach(g.speed, 0, 10, dt); + // hide <-> peek cycle + g.peekT -= dt; + if (g.peekT <= 0) { g.peek = g.peek ? 0 : 1; g.peekT = g.peek ? 1.2 + Math.random() * 1.4 * g.ty.aggr : 0.8 + Math.random() * 1.6 * (1 - g.ty.aggr); if (g.peek) g.burst = 0; } + if (g.mag <= 0) g.peek = 0; + faceTo(g, g.lastSeen || p.pos, dt, 8); + shooting = g.peek && seen; + // push in sometimes + if (g.ty.aggr > 0.6 && Math.random() < dt * 0.05 * g.ty.aggr) { g.coverT = 0; } + } else { + // no cover: strafe and shoot, or close in + g.strafeT -= dt; + if (g.strafeT <= 0) { g.strafeDir = Math.random() < 0.5 ? 1 : -1; g.strafeT = 1 + Math.random() * 2; } + var to = p.pos.clone().sub(g.pos); to.y = 0; var dd = to.length(); to.normalize(); + var side = new T.Vector3(-to.z, 0, to.x).multiplyScalar(g.strafeDir), want = dd > (d.range ? d.range[1] * 0.5 : 20) ? to : side; + if (!g.ty.stay) moveBody(g, want.x, want.z, dd > 12 ? 3.5 : 1.6, dt, false); else g.speed = 0; + faceTo(g, p.pos, dt, 8); + shooting = seen; + } + // attack tokens: only a few shoot at once + if (shooting && !g.token && tokens < maxTok) { g.token = true; tokens++; } + if (!shooting && g.token && Math.random() < dt * 0.8) { g.token = false; tokens--; } + g.actor._up = g.cover && g.atCover && !g.peek ? (g.cover.low ? 'crouchAim' : 'holdRifle') : 'aimIdle'; + g.crouch = g.cover && g.atCover && g.cover.low && !g.peek ? 1 : 0; + if (shooting && g.token && g.mag > 0 && g.reloadT <= 0 && g.fireCd <= 0) guardFire(g, p, dP); + } + function coverBroken(g, p) { + if (!g.cover || !g.atCover) return false; + var c = g.cover, pc = new T.Vector3(p.pos.x - c.x, 0, p.pos.z - c.z).normalize(); + return pc.x * c.dx + pc.z * c.dz < 0.2; // the player got round it + } + function faceTo(g, pt, dt, rate) { g.yaw = M.approachAngle(g.yaw, Math.atan2(pt.x - g.pos.x, pt.z - g.pos.z), rate, dt); } + var _m = new T.Vector3(); + function guardFire(g, p, dP) { + var d = g.def, df = RP.diff(); + g.mag--; g.burst++; + var rate = 60 / d.rpm; + // bursts: auto weapons fire 3-6 rounds then pause + if (d.auto && g.burst >= 3 + Math.floor(Math.random() * 4)) { g.burst = 0; g.fireCd = 0.5 + Math.random() * 0.9; } + else g.fireCd = Math.max(rate, d.auto ? rate : 0.45 + Math.random() * 0.5); + var mz = g.model ? g.model.userData.muzzle.getWorldPosition(_m) : g.actor.chest(_m); + // hit chance: accuracy x distance x player speed x cover x warm-up + var range = d.range ? d.range[1] : 40; + var pk = 0.75 * g.ty.acc * df.acc * M.clamp(1.15 - dP / (range * 1.2), 0.15, 1) * (p.speed > 4 ? 0.55 : p.speed > 1.8 ? 0.75 : 1) * (p.state === 'cover' ? 0.55 : 1) * (p.state === 'roll' ? 0.3 : 1) * Math.min(1, (RP.G.time - g.lastSeenT < 0.1 ? 0.5 : 0.5) + g.burst * 0.12); + var tgt = p.actor.chest(new T.Vector3()); + if (Math.random() > pk) { + // a near miss: somewhere round the player + var off = new T.Vector3((Math.random() - 0.5) * 2, (Math.random() - 0.3) * 1.4, (Math.random() - 0.5) * 2).normalize().multiplyScalar(0.5 + Math.random() * 1.2); + tgt.add(off); + } + var dir = tgt.sub(mz).normalize(); + RP.Combat.fire(g, mz.clone(), dir, d, { spread: 0.4, dmgMul: 0.5 }); + RP.FX.muzzle(mz, dir, d.dmg > 50 || d.pellets); + RP.Audio.shot(d.snd, mz.clone(), { gain: 0.9 }); + g.actor.playUpper(d.oneHand ? 'firePistol' : 'fire', { fade: 0.03, speed: 1.3 }); + if (Math.random() < 0.15) RP.FX.shell(mz, dir, new T.Vector3(-dir.z, 0, dir.x)); + } + + // ------------------------------------------------------------------ civilians + AI.stepCivs = function (dt) { + var p = RP.G.player; + RP.G.civilians.forEach(function (c) { + c.think -= dt; + if (c.think <= 0) { + c.think = 0.3; + // a gun pointed at them, or shots / explosions close by + if (p.alive && (p.aiming || p.fireHeld) && !RP.Weapons.DEFS[p.cur].melee && c.pos.distanceTo(p.pos) < 14) { + var aim = RP.Cam.aimRay(), to = c.pos.clone().add(new T.Vector3(0, 1.2, 0)).sub(aim.o).normalize(); + if (to.dot(aim.dir) > 0.96) c.scare(p.pos, 3); + } + RP.Combat.noises.forEach(function (n) { if ((n.kind === 'shot' || n.kind === 'explosion') && n.p.distanceTo(c.pos) < n.r * 0.7) c.scare(n.p, n.kind === 'explosion' ? 5 : 3); }); + } + if (c.state === 'flee') { + if (c.talk) { c.actor.stopFull(0.2); c.talk = false; } + if (!c.path) { + var away = c.pos.clone().sub(c.from); away.y = 0; away.normalize(); + var dest = c.pos.clone().addScaledVector(away, 25 + Math.random() * 15); + c.path = W.path(c.pos.x, c.pos.z, dest.x, dest.z, 4000) || [{ x: c.pos.x, z: c.pos.z }, { x: dest.x, z: dest.z }]; c.pathI = 1; c.fleeT = 10; + } + c.fleeT -= dt; + var wp = c.path[Math.min(c.pathI, c.path.length - 1)], dx = wp.x - c.pos.x, dz = wp.z - c.pos.z, dd = Math.hypot(dx, dz); + if (dd < 0.7 && c.pathI < c.path.length - 1) c.pathI++; + if ((dd < 0.7 && c.pathI >= c.path.length - 1) || c.fleeT <= 0) { c.state = 'cower'; c.cowerT = 8 + Math.random() * 6; c.speed = 0; } + else moveBody(c, dd ? dx / dd : 0, dd ? dz / dd : 0, 4.6, dt, true); + } else if (c.state === 'cower') { + c.speed = M.approach(c.speed, 0, 8, dt); c.cowerT -= dt; + if (c.cowerT <= 0 && RP.Alert.level === 0) { c.state = 'idle'; c.fear = 0; c.path = null; } + } else { + // idle: stand and chat, now and then stroll a few metres + if (c.talk) { c.speed = 0; return; } + c.wait -= dt; + if (c.wait <= 0 && !c.path && c.wander > 0) { + var a = Math.random() * 6.28, r = Math.random() * c.wander; + var tx = c.home.x + Math.cos(a) * r, tz = c.home.z + Math.sin(a) * r; + if (W.navOk(tx, tz)) { c.path = W.path(c.pos.x, c.pos.z, tx, tz, 1500); c.pathI = 1; } + c.wait = 5 + Math.random() * 8; + } + if (c.path) { + var w2 = c.path[Math.min(c.pathI, c.path.length - 1)], ex = w2.x - c.pos.x, ez = w2.z - c.pos.z, ed = Math.hypot(ex, ez); + if (ed < 0.5) { if (c.pathI < c.path.length - 1) c.pathI++; else c.path = null; } + moveBody(c, ed ? ex / ed : 0, ed ? ez / ed : 0, TU.walk * 0.85, dt, true); + } else c.speed = M.approach(c.speed, 0, 6, dt); + } + }); + }; + + // ------------------------------------------------------------------ animation (per rendered frame) + AI.frame = function (dt) { + RP.G.guards.forEach(function (g) { + var a = g.actor; + a.root.position.copy(g.pos); a.root.rotation.y = g.yaw; + if (!g.alive || g.down) { if (a.rag || g.ko) a.update(dt); return; } + var rel = M.wrap(g.moveYaw - g.yaw); + var up = g.actor._up || 'holdRifle'; if (g.def.oneHand) up = /aim/i.test(up) ? 'aimPistol' : 'holdPistol'; + a.setUpper(up, 0.25); + a.drive({ speed: g.speed, dir: rel, strafe: g.state === 'combat' ? 1 : 0, stealth: g.crouch || 0, sprint: 0, turnRate: 0 }); + if (g.state === 'combat' && g.lastSeen) { + var e = g.actor.chest(new T.Vector3()), t = RP.G.player.actor.chest(new T.Vector3()), dy = t.y - e.y, dh = Math.hypot(t.x - e.x, t.z - e.z); + a.setAim(Math.atan2(dy, dh), 0); a.weaponAim = g.actor._up === 'aimIdle' || g.actor._up === 'aimPistol' ? 1 : 0; a.weaponPitch = Math.atan2(dy, dh); + } else { a.setAim(0, 0); a.weaponAim = 0; a.weaponPitch = 0; } + a.update(dt); + }); + RP.G.civilians.forEach(function (c) { + var a = c.actor; a.root.position.copy(c.pos); a.root.rotation.y = c.yaw; + a.drive({ speed: c.speed, dir: 0, strafe: 0, stealth: c.state === 'cower' ? 1 : 0, sprint: c.speed > 4 ? 1 : 0 }); + a.setUpper(c.state === 'cower' ? null : null); + a.update(dt); + }); + }; + + // ==================================================================================== alert level + var AL = RP.Alert = { level: 0, prog: 0, seenT: -99, searchCentre: null, searchR: 0, coolT: 0, reinf: [], spawned: 0, enabled: true }; + AL.reset = function (enabled) { AL.level = 0; AL.prog = 0; AL.seenT = -99; AL.searchCentre = null; AL.searchR = 0; AL.spawned = 0; AL.enabled = enabled !== false; AL.reinfT = 0; RP.Audio.alarm(false); RP.emit('alert', 0); }; + AL.spotted = function (g) { if (!AL.enabled) return; if (AL.level === 0) set(1, g); AL.seen(RP.G.player.pos); }; + AL.seen = function (pos) { AL.seenT = RP.G.time; AL.searchCentre = pos.clone(); }; + AL.event = function (kind) { if (!AL.enabled) return; AL.prog += kind === 'kill' ? 1 : 0.25; check(); }; + function set(l, g) { + l = M.clamp(l, 0, 5); if (l === AL.level) return; + var up = l > AL.level; AL.level = l; + if (up) { + RP.Audio.radio(); RP.emit('sub', 'Radio: ' + RADIO[Math.min(RADIO.length - 1, l - 1)].replace('{p}', placeName(RP.G.player.pos)), 3); + RP.Audio.ui('alert'); + if (l >= 3) RP.Audio.alarm(true); + AL.reinfT = 3 + Math.random() * 3; + } else { + RP.Audio.radio(); RP.emit('sub', 'Radio: ' + RADIO_DOWN[Math.min(RADIO_DOWN.length - 1, Math.max(0, 2 - l))], 3); + if (l < 3) RP.Audio.alarm(false); + } + RP.emit('alert', l); + } + AL.set = set; + var NEED = [0, 2, 5, 9, 14]; // progress (kills, plus a little per few seconds of fighting) to reach tiers 2..5 + function check() { for (var l = 4; l >= 1; l--) if (AL.prog >= NEED[l] && AL.level < l + 1) { set(l + 1); break; } } + AL.step = function (dt) { + if (!AL.enabled || AL.level === 0) return; + var p = RP.G.player, since = RP.G.time - AL.seenT; + if (since < 1) AL.prog += dt * 0.06; + check(); + AL.searchR = 18 + AL.level * 10; + // cool down: out of sight, and out of the search circle + var outside = !AL.searchCentre || p.pos.distanceTo(AL.searchCentre) > AL.searchR; + var anySees = RP.G.guards.some(function (g) { return g.alive && g.sees; }); + if (anySees) AL.coolT = 0; + else AL.coolT += dt * (outside ? 1.6 : 0.6); + RP.G.guards.forEach(function (g) { if (g.alive && g.state === 'combat' && RP.G.time - g.lastSeenT > 9) g.state = 'search'; }); + if (AL.coolT > TU.alertCool[AL.level]) { AL.coolT = 0; AL.prog = Math.min(AL.prog, NEED[Math.max(0, AL.level - 2)] || 0); set(AL.level - 1); } + // reinforcements by tier + AL.reinfT -= dt; + if (AL.reinfT <= 0 && RP.G.mission && RP.G.mission.reinforce !== false) { + AL.reinfT = 14 - AL.level; + var alive = RP.G.guards.filter(function (g) { return g.alive; }).length; + var cap = [0, 6, 8, 11, 13, 15][AL.level]; + if (alive < cap) reinforce(AL.level); + } + }; + function reinforce(level) { + var p = RP.G.player, spots = (RP.G.mission && RP.G.mission.spawns) || RP.map.spawns || []; + // a spawn point out of the player's sight, 35-80 m away + var cands = spots.filter(function (s) { var d = Math.hypot(s.x - p.pos.x, s.z - p.pos.z); return d > 30 && d < 90 && !W.los(p.pos.x, p.pos.y + 1.6, p.pos.z, s.x, (s.y || W.terrainH(s.x, s.z)) + 1.6, s.z); }); + if (!cands.length) return; + var s = cands[Math.floor(Math.random() * cands.length)]; + var team = level <= 1 ? ['sentry', 'sentry'] : level === 2 ? ['sentry', 'enforcer'] : level === 3 ? ['enforcer', 'shotgunner', 'enforcer'] : level === 4 ? ['elite', 'enforcer', 'elite'] : ['elite', 'gunner', 'elite', 'elite']; + team.forEach(function (t, i) { + var g = AI.spawnGuard(t, { x: s.x + (i % 2) * 1.5, z: s.z + Math.floor(i / 2) * 1.5, y: s.y, yaw: Math.atan2(p.pos.x - s.x, p.pos.z - s.z) }); + alertGuard(g, AL.searchCentre || p.pos, false); g.react = 0.5; + if (RP.Warm) RP.Warm(g); + }); + AL.spawned += team.length; + RP.emit('sub', 'Radio: ' + ['Team in position.', 'Response team arriving.', 'Second squad on site.', 'Elite squad deployed.'][Math.min(3, level - 1)], 2.5); + } +})(); diff --git a/e63334287a3deaa3/blacktie/js/audio.js b/e63334287a3deaa3/blacktie/js/audio.js new file mode 100644 index 00000000..40febe8a --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/audio.js @@ -0,0 +1,221 @@ +/* + * Sound (RP.Audio): everything is synthesised with Web Audio, nothing is downloaded. Positional sounds go through a + * PannerNode relative to the camera; a convolver with a generated impulse gives each shot a tail (short slap outside, + * a longer, darker room inside: RP.Audio.indoor is set each frame from the map's indoor zones). Distant gunfire is + * low-passed and delayed by the speed of sound. + */ +(function () { + 'use strict'; + var A = RP.Audio = { ok: false, indoor: 0 }; + var ctx, master, sfx, revOut, revIn, revSendOut, revSendIn, noiseBuf, listenerPos = new THREE.Vector3(); + + A.init = function () { + if (A.ok) { if (ctx.state === 'suspended') ctx.resume(); return; } + try { ctx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { return; } + A.ctx = ctx; + master = ctx.createGain(); master.gain.value = RP.settings.volume; + var comp = ctx.createDynamicsCompressor(); comp.threshold.value = -14; comp.ratio.value = 4; comp.attack.value = 0.003; comp.release.value = 0.2; + master.connect(comp); comp.connect(ctx.destination); + sfx = ctx.createGain(); sfx.connect(master); + revOut = ctx.createConvolver(); revOut.buffer = impulse(0.9, 3.2, 0.15); revSendOut = ctx.createGain(); revSendOut.gain.value = 0.35; revSendOut.connect(revOut); revOut.connect(master); + revIn = ctx.createConvolver(); revIn.buffer = impulse(1.6, 2.2, 0.01); revSendIn = ctx.createGain(); revSendIn.gain.value = 0; revSendIn.connect(revIn); revIn.connect(master); + noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate); + var d = noiseBuf.getChannelData(0); for (var i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + A.ok = true; + ambience(); + }; + A.setVolume = function (v) { if (master) master.gain.value = v; }; + function impulse(len, decay, predelay) { + var n = Math.floor(ctx.sampleRate * len), b = ctx.createBuffer(2, n, ctx.sampleRate); + for (var c = 0; c < 2; c++) { + var d = b.getChannelData(c), pd = Math.floor(predelay * ctx.sampleRate); + for (var i = pd; i < n; i++) d[i] = (Math.random() * 2 - 1) * Math.pow(1 - (i - pd) / (n - pd), decay); + } + return b; + } + // listener follows the camera + A.listen = function (cam) { + if (!A.ok) return; + var L = ctx.listener, p = cam.position, f = new THREE.Vector3(0, 0, -1).applyQuaternion(cam.quaternion), u = new THREE.Vector3(0, 1, 0).applyQuaternion(cam.quaternion); + listenerPos.copy(p); + if (L.positionX) { L.positionX.value = p.x; L.positionY.value = p.y; L.positionZ.value = p.z; L.forwardX.value = f.x; L.forwardY.value = f.y; L.forwardZ.value = f.z; L.upX.value = u.x; L.upY.value = u.y; L.upZ.value = u.z; } + else { L.setPosition(p.x, p.y, p.z); L.setOrientation(f.x, f.y, f.z, u.x, u.y, u.z); } + var tIn = A.indoor ? 0.55 : 0, tOut = A.indoor ? 0.08 : 0.35; + revSendIn.gain.setTargetAtTime(tIn, ctx.currentTime, 0.2); revSendOut.gain.setTargetAtTime(tOut, ctx.currentTime, 0.2); + }; + // a positional output chain: returns the node to connect sources into + function out(pos, gain, rev) { + var g = ctx.createGain(); g.gain.value = gain == null ? 1 : gain; + if (pos) { + var p = ctx.createPanner(); p.panningModel = 'equalpower'; p.distanceModel = 'inverse'; p.refDistance = 4; p.rolloffFactor = 1.1; p.maxDistance = 600; + if (p.positionX) { p.positionX.value = pos.x; p.positionY.value = pos.y; p.positionZ.value = pos.z; } else p.setPosition(pos.x, pos.y, pos.z); + g.connect(p); p.connect(sfx); + if (rev) { var s = ctx.createGain(); s.gain.value = rev; p.connect(s); s.connect(revSendOut); s.connect(revSendIn); } + } else { g.connect(sfx); if (rev) { var s2 = ctx.createGain(); s2.gain.value = rev; g.connect(s2); s2.connect(revSendOut); s2.connect(revSendIn); } } + return g; + } + function noise(dest, t0, dur, type, freq, q, gain, attack) { + var s = ctx.createBufferSource(); s.buffer = noiseBuf; s.loopStart = Math.random(); s.loop = true; + var f = ctx.createBiquadFilter(); f.type = type || 'bandpass'; f.frequency.value = freq || 1000; f.Q.value = q || 0.7; + var g = ctx.createGain(); g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(gain, t0 + (attack || 0.002)); g.gain.exponentialRampToValueAtTime(0.0008, t0 + dur); + s.connect(f); f.connect(g); g.connect(dest); s.start(t0, Math.random() * 1.5); s.stop(t0 + dur + 0.05); + return f; + } + function tone(dest, t0, dur, f0, f1, type, gain) { + var o = ctx.createOscillator(); o.type = type || 'sine'; o.frequency.setValueAtTime(f0, t0); if (f1) o.frequency.exponentialRampToValueAtTime(Math.max(1, f1), t0 + dur); + var g = ctx.createGain(); g.gain.setValueAtTime(gain, t0); g.gain.exponentialRampToValueAtTime(0.0008, t0 + dur); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + dur + 0.02); + } + + // a car horn at pos: two detuned square notes through a low-pass (a small Italian car's double beep when `twice`) + A.horn = function (pos, len, twice) { + if (!A.ok) return; + var t0 = ctx.currentTime, dest = out(pos, 0.32, 0.4), lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 1900; lp.connect(dest); + (twice ? [0, 0.22] : [0]).forEach(function (dt) { + [415, 523].forEach(function (f) { + var o = ctx.createOscillator(), g = ctx.createGain(); o.type = 'square'; o.frequency.value = f; + g.gain.setValueAtTime(0, t0 + dt); g.gain.linearRampToValueAtTime(0.5, t0 + dt + 0.015); g.gain.setValueAtTime(0.5, t0 + dt + (len || 0.3)); g.gain.linearRampToValueAtTime(0, t0 + dt + (len || 0.3) + 0.04); + o.connect(g); g.connect(lp); o.start(t0 + dt); o.stop(t0 + dt + (len || 0.3) + 0.06); + }); + }); + }; + + // ------------------------------------------------------------------ weapons + var GUN = { // crack (noise band Hz, gain), body (thump Hz), tail length, loudness + pistol: [2600, 0.9, 150, 0.18, 1], revolver: [1800, 1.1, 110, 0.3, 1.3], smg: [3000, 0.8, 170, 0.14, 0.9], rifle: [2200, 1.0, 120, 0.22, 1.2], rifle2: [1900, 1.1, 105, 0.26, 1.3], + shotgun: [1400, 1.2, 85, 0.32, 1.4], shotgun2: [1200, 1.3, 80, 0.36, 1.5], sniper: [1500, 1.3, 90, 0.5, 1.6], mg: [2000, 1.05, 100, 0.25, 1.25], gl: [600, 0.6, 70, 0.15, 0.8], rl: [500, 0.9, 60, 0.6, 1.2] + }; + A.shot = function (profile, pos, o) { + if (!A.ok) return; + o = o || {}; + var P = GUN[profile] || GUN.pistol, d = pos ? pos.distanceTo(listenerPos) : 0, t0 = ctx.currentTime + d / 343; + var far = M_clamp((d - 40) / 260, 0, 1), sup = o.suppressed ? 0.25 : 1; + var dest = out(pos, P[4] * (o.gain || 1) * sup * (1 - far * 0.5), 0.9 * (1 - far * 0.3)); + var lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 9000 - far * 7800; lp.connect(dest); + noise(lp, t0, 0.05 + P[3] * 0.25, 'bandpass', P[0] * (0.9 + Math.random() * 0.2), 0.6, P[1] * 0.9); + noise(lp, t0, 0.012, 'highpass', 4000, 0.5, P[1] * 0.6 * (1 - far)); + tone(lp, t0, 0.09 + P[3] * 0.2, P[2] * 1.6, P[2] * 0.5, 'sine', 1.1); + noise(lp, t0 + 0.01, P[3], 'lowpass', 500, 0.5, 0.5); + // the tail: the report rolling off the cliffs and house fronts. One tail per burst (at most every 0.28 s), so + // automatic fire is a run of dry cracks followed by a single long echo rather than a wash of overlapping ones. + if (!o.suppressed && t0 - (A._tailT || -9) > 0.28) { + A._tailT = t0; + var tg = out(pos, P[4] * 0.55 * (1 - far * 0.3), 1.0), L = 0.7 + P[3] * 2.2; + noise(tg, t0 + 0.03, L, 'lowpass', 900 - far * 400, 0.4, 0.32, 0.03); + noise(tg, t0 + 0.19 + Math.random() * 0.04, L * 0.7, 'lowpass', 1300, 0.6, 0.2, 0.02); // first slap back + noise(tg, t0 + 0.43 + Math.random() * 0.08, L * 0.6, 'lowpass', 700, 0.5, 0.12, 0.04); // far wall + if (P[2] < 100) tone(tg, t0, 0.35, P[2] * 0.9, 34, 'sine', 0.5); // big guns thump + } + }; + A.dry = function (pos) { if (!A.ok) return; var t = ctx.currentTime, d = out(pos, 0.5); noise(d, t, 0.03, 'highpass', 3000, 1, 0.6); }; + A.mech = function (kind, pos) { // reload and handling noises: magOut, magIn, slide, bolt, shell, pump, open, close, pin, swing + if (!A.ok) return; + var t = ctx.currentTime, d = out(pos, 0.45, 0.1); + switch (kind) { + case 'magOut': noise(d, t, 0.05, 'bandpass', 1800, 2, 0.6); tone(d, t, 0.04, 900, 600, 'square', 0.05); break; + case 'magIn': noise(d, t, 0.04, 'bandpass', 2500, 3, 0.9); noise(d, t + 0.03, 0.05, 'bandpass', 1200, 2, 0.6); break; + case 'slide': noise(d, t, 0.08, 'bandpass', 3200, 1.5, 0.7); noise(d, t + 0.09, 0.05, 'bandpass', 2200, 2, 0.9); break; + case 'bolt': noise(d, t, 0.06, 'bandpass', 2000, 2, 0.7); noise(d, t + 0.18, 0.06, 'bandpass', 2600, 2, 0.8); break; + case 'shell': noise(d, t, 0.05, 'bandpass', 1400, 1.5, 0.7); break; + case 'pump': noise(d, t, 0.07, 'bandpass', 1500, 1.4, 0.9); noise(d, t + 0.16, 0.07, 'bandpass', 1900, 1.4, 1); break; + case 'open': noise(d, t, 0.08, 'bandpass', 1100, 2, 0.8); break; + case 'close': noise(d, t, 0.05, 'bandpass', 1600, 3, 1); break; + case 'pin': tone(d, t, 0.08, 2600, 2400, 'triangle', 0.15); break; + case 'swing': noise(d, t, 0.2, 'bandpass', 700, 0.8, 0.5, 0.06); break; + case 'brass': tone(d, t + 0.25, 0.08, 4200, 3800, 'triangle', 0.05); tone(d, t + 0.35, 0.06, 3900, 3500, 'triangle', 0.03); break; + case 'holster': noise(d, t, 0.1, 'bandpass', 800, 1, 0.3, 0.02); break; + } + }; + // ------------------------------------------------------------------ impacts, melee, bodies + A.impact = function (mat, pos, k) { + if (!A.ok || !pos || pos.distanceTo(listenerPos) > 120) return; + var t = ctx.currentTime, d = out(pos, 0.5 * (k || 1), 0.15); + if (mat === 'metal' || mat === 'car') { tone(d, t, 0.18, 2400 + Math.random() * 1500, 1800, 'triangle', 0.18); noise(d, t, 0.04, 'highpass', 3000, 1, 0.5); } + else if (mat === 'glass') { for (var i = 0; i < 5; i++) tone(d, t + i * 0.012, 0.12, 3000 + Math.random() * 4000, 2500, 'sine', 0.08); noise(d, t, 0.15, 'highpass', 5000, 1, 0.5); } + else if (mat === 'wood') { noise(d, t, 0.06, 'bandpass', 900, 2, 0.9); tone(d, t, 0.05, 320, 200, 'sine', 0.3); } + else if (mat === 'water') { noise(d, t, 0.25, 'lowpass', 1200, 0.7, 0.7, 0.01); } + else if (mat === 'flesh') { noise(d, t, 0.05, 'lowpass', 600, 1, 1); tone(d, t, 0.06, 160, 80, 'sine', 0.5); } + else if (mat === 'dirt' || mat === 'sand') { noise(d, t, 0.07, 'lowpass', 900, 0.7, 0.8); } + else { noise(d, t, 0.06, 'bandpass', 1800, 1.2, 0.8); noise(d, t, 0.1, 'lowpass', 500, 0.7, 0.4); } + }; + A.whiz = function (pos) { if (!A.ok) return; var t = ctx.currentTime, d = out(pos, 0.35); noise(d, t, 0.12, 'bandpass', 2600, 4, 0.8, 0.03); }; + A.punch = function (pos, k) { if (!A.ok) return; var t = ctx.currentTime, d = out(pos, 0.9 * (k || 1), 0.1); noise(d, t, 0.06, 'lowpass', 900, 1, 1.2); tone(d, t, 0.09, 140, 60, 'sine', 0.9); noise(d, t, 0.02, 'highpass', 2500, 1, 0.4); }; + A.thud = function (pos, k) { if (!A.ok) return; var t = ctx.currentTime, d = out(pos, 0.7 * (k || 1), 0.1); tone(d, t, 0.15, 90, 40, 'sine', 1); noise(d, t, 0.12, 'lowpass', 400, 0.7, 0.8); }; + A.step = function (mat, pos, loud) { + if (!A.ok || !pos || pos.distanceTo(listenerPos) > 40) return; + var t = ctx.currentTime, d = out(pos, 0.12 * (loud || 1)); + if (mat === 'sand' || mat === 'dirt') noise(d, t, 0.09, 'lowpass', 700, 0.7, 0.9, 0.01); + else if (mat === 'wood') { noise(d, t, 0.05, 'bandpass', 600, 1.5, 1); tone(d, t, 0.04, 180, 120, 'sine', 0.3); } + else if (mat === 'metal' || mat === 'car') { noise(d, t, 0.05, 'bandpass', 2200, 2, 0.7); } + else if (mat === 'water') noise(d, t, 0.14, 'lowpass', 1500, 0.8, 0.8, 0.02); + else { noise(d, t, 0.045, 'bandpass', 1600, 1.3, 0.9); noise(d, t, 0.03, 'lowpass', 300, 0.7, 0.6); } + }; + A.explosion = function (pos, k) { + if (!A.ok) return; + k = k || 1; + var dd = pos.distanceTo(listenerPos), t = ctx.currentTime + dd / 343, d = out(pos, 2.2 * k, 1.2); + noise(d, t, 1.6, 'lowpass', 600, 0.6, 1.6, 0.005); + tone(d, t, 0.8, 70, 25, 'sine', 1.6); + noise(d, t, 0.15, 'highpass', 2000, 0.5, 0.8 * Math.max(0, 1 - dd / 150)); + noise(d, t + 0.2, 1.8, 'lowpass', 220, 0.5, 0.7, 0.2); + }; + A.glass = function (pos) { A.impact('glass', pos, 1.5); }; + // ------------------------------------------------------------------ voices: a radio squelch and a mumbled bark + A.radio = function () { + if (!A.ok) return; + var t = ctx.currentTime, d = out(null, 0.25); + noise(d, t, 0.08, 'bandpass', 2400, 2, 0.8); tone(d, t, 0.05, 1200, 1200, 'square', 0.04); + var bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 1300; bp.Q.value = 1.5; bp.connect(d); + for (var i = 0; i < 6; i++) tone(bp, t + 0.1 + i * 0.09, 0.08, 180 + Math.random() * 120, 140, 'sawtooth', 0.08); + noise(d, t + 0.7, 0.06, 'bandpass', 2400, 2, 0.6); + }; + A.bark = function (pos, urgent) { + if (!A.ok || !pos) return; + var t = ctx.currentTime, d = out(pos, urgent ? 0.6 : 0.35, 0.2); + var bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 900; bp.Q.value = 0.8; bp.connect(d); + var n = 3 + Math.floor(Math.random() * 4); + for (var i = 0; i < n; i++) tone(bp, t + i * 0.11, 0.1, (urgent ? 210 : 150) + Math.random() * 60, 120, 'sawtooth', 0.12); + }; + var alarmNode = null; + A.alarm = function (on) { + if (!A.ok) return; + if (on && !alarmNode) { + var o = ctx.createOscillator(), lfo = ctx.createOscillator(), lg = ctx.createGain(), g = ctx.createGain(); + o.type = 'triangle'; o.frequency.value = 700; lfo.frequency.value = 0.8; lg.gain.value = 220; lfo.connect(lg); lg.connect(o.frequency); + g.gain.value = 0.035; o.connect(g); g.connect(sfx); o.start(); lfo.start(); alarmNode = { o: o, l: lfo, g: g }; + } else if (!on && alarmNode) { alarmNode.g.gain.setTargetAtTime(0, ctx.currentTime, 0.3); var a = alarmNode; setTimeout(function () { a.o.stop(); a.l.stop(); }, 1500); alarmNode = null; } + }; + A.ui = function (kind) { + if (!A.ok) return; + var t = ctx.currentTime, d = out(null, 0.25); + if (kind === 'tick') tone(d, t, 0.03, 1800, 1500, 'triangle', 0.2); + else if (kind === 'ok') { tone(d, t, 0.08, 880, 880, 'triangle', 0.25); tone(d, t + 0.08, 0.12, 1320, 1320, 'triangle', 0.25); } + else if (kind === 'hit') tone(d, t, 0.05, 2400, 2000, 'square', 0.06); + else if (kind === 'kill') { tone(d, t, 0.06, 1500, 1500, 'square', 0.06); tone(d, t + 0.05, 0.08, 2000, 2000, 'square', 0.05); } + else if (kind === 'alert') { tone(d, t, 0.12, 600, 900, 'sawtooth', 0.12); } + else if (kind === 'objective') { tone(d, t, 0.15, 523, 523, 'sine', 0.3); tone(d, t + 0.12, 0.15, 659, 659, 'sine', 0.3); tone(d, t + 0.24, 0.3, 784, 784, 'sine', 0.3); } + }; + A.heart = function (k) { if (!A.ok || k < 0.05) return; var t = ctx.currentTime, d = out(null, 0.5 * k); tone(d, t, 0.12, 60, 40, 'sine', 1); tone(d, t + 0.2, 0.12, 55, 38, 'sine', 0.8); }; + // ------------------------------------------------------------------ ambience: the sea, wind, cicadas by day + var amb = {}; + function ambience() { + var sea = ctx.createBufferSource(); sea.buffer = noiseBuf; sea.loop = true; + var f = ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.value = 500; + var g = ctx.createGain(); g.gain.value = 0.0; + var lfo = ctx.createOscillator(); lfo.frequency.value = 0.09; var lg = ctx.createGain(); lg.gain.value = 0.03; lfo.connect(lg); lg.connect(g.gain); + sea.connect(f); f.connect(g); g.connect(master); sea.start(); lfo.start(); + amb.sea = g; + var cic = ctx.createBufferSource(); cic.buffer = noiseBuf; cic.loop = true; + var cf = ctx.createBiquadFilter(); cf.type = 'bandpass'; cf.frequency.value = 5200; cf.Q.value = 8; + var cg = ctx.createGain(); cg.gain.value = 0; + var cl = ctx.createOscillator(); cl.frequency.value = 18; var clg = ctx.createGain(); clg.gain.value = 0.01; cl.connect(clg); clg.connect(cg.gain); + cic.connect(cf); cf.connect(cg); cg.connect(master); cic.start(); cl.start(); + amb.cic = cg; + } + A.ambient = function (seaNear, day, combat) { + if (!A.ok) return; + amb.sea.gain.setTargetAtTime(0.02 + 0.06 * seaNear, ctx.currentTime, 0.5); + amb.cic.gain.setTargetAtTime(day ? 0.012 * (1 - combat) : 0, ctx.currentTime, 1); + }; + function M_clamp(v, a, b) { return v < a ? a : v > b ? b : v; } +})(); diff --git a/e63334287a3deaa3/blacktie/js/build.js b/e63334287a3deaa3/blacktie/js/build.js new file mode 100644 index 00000000..f9b2f4da --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/build.js @@ -0,0 +1,570 @@ +/* + * Static scenery builder and chunk streaming (RP.B). Maps call these helpers (mostly through RP.Kit in mapkit.js); each + * one writes triangles into a bucket per 128 m chunk and per detail class, and (where it says so) a collision box + * into RP.W. B.finish() turns every bucket into one mesh that shares one material (RP.mat.town, a texture array, see + * maptex.js), so a chunk of town is three draw calls however many surfaces it has: + * + * 'shell' walls, roofs, paving, roads: drawn out to the preset's draw distance, casts shadows + * 'detail' balconies, props, street clutter: drawn near the camera only, casts shadows + * 'flat' windows, shutters, signs, lamps: drawn near the camera only, no shadows + * 'far' one plain box per building, all chunks in one mesh: drawn for the chunks beyond the draw distance + * + * The terrain is cut into the same chunks at three resolutions (2 m, 4 m, and 8 m merged into one mesh for the far + * coast, 16 m on Low). The middle and far meshes list only the chunks that are in view, so each is one draw call. B.stream(camera), called every frame from RP.Sea.update, shows what is near, hides the rest, and builds a + * chunk's terrain meshes the first time they are needed. Leaf cards are one InstancedMesh per chunk. + * + * UVs are in metres (the code-made textures tile per metre or per few metres). Every vertex carries a colour that + * tints the texture and holds a little baked ambient occlusion (darker at the foot of walls and under eaves); the + * colour's alpha byte is the material id (RP.MT), which the shader turns into a texture layer and roughness. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W; + var B = RP.B = {}; + var CH = B.CH = 128; + // how far each class is drawn, per quality preset (metres from the camera to the chunk's edge) + B.RANGE = { + // near: detail and flat classes; fol: leaf cards; tnear: finest terrain; far: shells and mid terrain (beyond it a + // chunk is in the far meshes); civ: how far bystanders are drawn; steps: terrain cell size (m) near, mid, far + low: { near: 72, fol: 100, tnear: 28, far: 250, civ: 110, steps: [2, 4, 16] }, + medium: { near: 150, fol: 200, tnear: 80, far: 480, civ: 240, steps: [2, 4, 8] }, + high: { near: 250, fol: 360, tnear: 190, far: 720, civ: 500, steps: [2, 4, 8] } + }; + + // ------------------------------------------------------------------ buckets (growable typed arrays) + function Bucket(cls, cx, cz) { + this.cls = cls; this.cx = cx; this.cz = cz; this.n = 0; this.ni = 0; this.cap = 512; this.icap = 1024; + this.pos = new Float32Array(this.cap * 3); this.nrm = new Int8Array(this.cap * 3); this.uv = new Float32Array(this.cap * 2); + this.col = new Uint8Array(this.cap * 4); this.idx = new Uint32Array(this.icap); + } + Bucket.prototype.need = function (nv, ni) { + if (this.n + nv > this.cap) { + var c = this.cap; while (this.n + nv > c) c *= 2; + var p = new Float32Array(c * 3); p.set(this.pos.subarray(0, this.n * 3)); this.pos = p; + var nn = new Int8Array(c * 3); nn.set(this.nrm.subarray(0, this.n * 3)); this.nrm = nn; + var u = new Float32Array(c * 2); u.set(this.uv.subarray(0, this.n * 2)); this.uv = u; + var cl = new Uint8Array(c * 4); cl.set(this.col.subarray(0, this.n * 4)); this.col = cl; + this.cap = c; + } + if (this.ni + ni > this.icap) { + var ic = this.icap; while (this.ni + ni > ic) ic *= 2; + var ix = new Uint32Array(ic); ix.set(this.idx.subarray(0, this.ni)); this.idx = ix; this.icap = ic; + } + }; + function enc(v) { return v <= 0 ? 0 : v >= 1 ? 255 : Math.sqrt(v) * 255 + 0.5 | 0; } // linear -> gamma 2 byte (squared in the shader) + Bucket.prototype.vert = function (x, y, z, nx, ny, nz, u, v, r, g, b, mt) { + var i = this.n++, a = i * 3; + this.pos[a] = x; this.pos[a + 1] = y; this.pos[a + 2] = z; + this.nrm[a] = nx * 127; this.nrm[a + 1] = ny * 127; this.nrm[a + 2] = nz * 127; + this.uv[i * 2] = u; this.uv[i * 2 + 1] = v; + a = i * 4; this.col[a] = enc(r); this.col[a + 1] = enc(g); this.col[a + 2] = enc(b); this.col[a + 3] = mt; + return i; + }; + + var WHITE = new T.Color(1, 1, 1); + B.reset = function () { + B.buckets = {}; B.handles = {}; B.chunks = {}; B.chunkList = []; B.meshes = []; B.instanced = []; B.tris = 0; B.cls = 'shell'; + B.leaves = {}; B.land = null; B.farTown = null; B.farLand = null; B.midLand = null; + }; + function chunkOf(cx, cz) { + var k = cx + '|' + cz, c = B.chunks[k]; + if (!c) { + c = B.chunks[k] = { cx: cx, cz: cz, x0: cx * CH, z0: cz * CH, x1: (cx + 1) * CH, z1: (cz + 1) * CH, d: 1e9, + shell: null, detail: null, flat: null, leaf: null, tn: null, far: false, mid: false, farTown: null, farLand: null, midLand: null }; + B.chunkList.push(c); + } + return c; + } + B.chunkAt = function (x, z) { return chunkOf(Math.floor(x / CH), Math.floor(z / CH)); }; + // a handle to write one material into the bucket of the chunk that holds (x, z). cls: 'shell' | 'detail' | 'flat' | 'far' + function bucket(mat, x, z, cls) { + if (cls && cls.indexOf('noshadow') >= 0) cls = 'flat'; + var def = RP.MTDEF[mat] || RP.MTDEF.stucco; + cls = cls || def.cls || B.cls; + var cx = Math.floor(x / CH), cz = Math.floor(z / CH), k = cls + '|' + cx + '|' + cz, hk = k + '|' + mat; + var h = B.handles[hk]; + if (h) return h; + var b = B.buckets[k]; + if (!b) { b = B.buckets[k] = new Bucket(cls, cx, cz); chunkOf(cx, cz); } + return (B.handles[hk] = { b: b, mt: def.id, tint: def.tint || null, dbl: !!def.dbl }); + } + B.bucket = bucket; + // run fn with a different default detail class + B.as = function (cls, fn) { var o = B.cls; B.cls = cls; try { return fn(); } finally { B.cls = o; } }; + + // a quad from 4 corners (counter-clockwise seen from the front), UVs given per corner, colour per corner + var _a = new T.Vector3(), _b = new T.Vector3(), _n = new T.Vector3(); + B.quad = function (h, p0, p1, p2, p3, uv, c0, c1, c2, c3) { + var bk = h.b, t = h.tint; + _a.subVectors(p1, p0); _b.subVectors(p3, p0); _n.crossVectors(_a, _b); + if (_n.lengthSq() < 1e-10) { _a.subVectors(p2, p1); _b.subVectors(p3, p1); _n.crossVectors(_a, _b); if (_n.lengthSq() < 1e-10) return; } // no area: nothing to draw + _n.normalize(); + c0 = c0 || WHITE; c1 = c1 || c0; c2 = c2 || c0; c3 = c3 || c0; + var tr = t ? t.r : 1, tg = t ? t.g : 1, tb = t ? t.b : 1; + bk.need(h.dbl ? 8 : 4, h.dbl ? 12 : 6); + var i0 = bk.vert(p0.x, p0.y, p0.z, _n.x, _n.y, _n.z, uv[0], uv[1], c0.r * tr, c0.g * tg, c0.b * tb, h.mt); + bk.vert(p1.x, p1.y, p1.z, _n.x, _n.y, _n.z, uv[2], uv[3], c1.r * tr, c1.g * tg, c1.b * tb, h.mt); + bk.vert(p2.x, p2.y, p2.z, _n.x, _n.y, _n.z, uv[4], uv[5], c2.r * tr, c2.g * tg, c2.b * tb, h.mt); + bk.vert(p3.x, p3.y, p3.z, _n.x, _n.y, _n.z, uv[6], uv[7], c3.r * tr, c3.g * tg, c3.b * tb, h.mt); + var ix = bk.idx, k = bk.ni; + ix[k] = i0; ix[k + 1] = i0 + 1; ix[k + 2] = i0 + 2; ix[k + 3] = i0; ix[k + 4] = i0 + 2; ix[k + 5] = i0 + 3; bk.ni += 6; + if (h.dbl) { // cloth is seen from both sides + var j0 = bk.vert(p0.x, p0.y, p0.z, -_n.x, -_n.y, -_n.z, uv[0], uv[1], c0.r * tr, c0.g * tg, c0.b * tb, h.mt); + bk.vert(p1.x, p1.y, p1.z, -_n.x, -_n.y, -_n.z, uv[2], uv[3], c1.r * tr, c1.g * tg, c1.b * tb, h.mt); + bk.vert(p2.x, p2.y, p2.z, -_n.x, -_n.y, -_n.z, uv[4], uv[5], c2.r * tr, c2.g * tg, c2.b * tb, h.mt); + bk.vert(p3.x, p3.y, p3.z, -_n.x, -_n.y, -_n.z, uv[6], uv[7], c3.r * tr, c3.g * tg, c3.b * tb, h.mt); + k = bk.ni; ix = bk.idx; + ix[k] = j0; ix[k + 1] = j0 + 2; ix[k + 2] = j0 + 1; ix[k + 3] = j0; ix[k + 4] = j0 + 3; ix[k + 5] = j0 + 2; bk.ni += 6; + } + }; + // a triangle (for gables and fans) + B.tri = function (h, p0, p1, p2, uv, c) { + var bk = h.b, t = h.tint; c = c || WHITE; + _a.subVectors(p1, p0); _b.subVectors(p2, p0); _n.crossVectors(_a, _b); if (_n.lengthSq() < 1e-10) return; _n.normalize(); + var r = c.r * (t ? t.r : 1), g = c.g * (t ? t.g : 1), b = c.b * (t ? t.b : 1); + bk.need(3, 3); + var i0 = bk.vert(p0.x, p0.y, p0.z, _n.x, _n.y, _n.z, uv[0], uv[1], r, g, b, h.mt); + bk.vert(p1.x, p1.y, p1.z, _n.x, _n.y, _n.z, uv[2], uv[3], r, g, b, h.mt); + bk.vert(p2.x, p2.y, p2.z, _n.x, _n.y, _n.z, uv[4], uv[5], r, g, b, h.mt); + bk.idx[bk.ni++] = i0; bk.idx[bk.ni++] = i0 + 1; bk.idx[bk.ni++] = i0 + 2; + }; + + // oriented box: centre (x, z), bottom y0, size w (local x) h d (local z), yaw. opts: + // col (THREE.Color linear), uvs (metres per texture repeat, default 1), ao (darken bottom, 0..1), noTop, noSides, + // bottom, collide (adds a W box with mat/cover/kind from opts), topCol, cls (detail class), topMat (another + // material for the top face), fitUV ([nu, nv]: the side faces show exactly nu x nv texture tiles) + var _p = []; + for (var _i = 0; _i < 8; _i++) _p.push(new T.Vector3()); + B.box = function (mat, x, y0, z, w, h, d, yaw, opts) { + opts = opts || {}; + var c = Math.cos(yaw || 0), s = Math.sin(yaw || 0), hx = w / 2, hz = d / 2, y1 = y0 + h; + var col = opts.col || WHITE, ao = opts.ao == null ? 0.25 : opts.ao, us = opts.uvs || 1; + var cb = ao ? col.clone().multiplyScalar(1 - ao) : col, ct = opts.topCol || col; + function P(i, lx, y, lz) { return _p[i].set(x + lx * c + lz * s, y, z - lx * s + lz * c); } + var bk = bucket(mat, x, z, opts.cls || opts.flags); + // corners: 0..3 bottom (-x-z, +x-z, +x+z, -x+z), 4..7 top + P(0, -hx, y0, -hz); P(1, hx, y0, -hz); P(2, hx, y0, hz); P(3, -hx, y0, hz); + P(4, -hx, y1, -hz); P(5, hx, y1, -hz); P(6, hx, y1, hz); P(7, -hx, y1, hz); + var p = _p; + // UVs: u along the face, v up the face (metres / us), world-anchored v so stacked boxes line up + var v0 = y0 / us, v1 = y1 / us, uw = w / us, ud = d / us; + if (opts.fitUV) { v0 = 0; v1 = opts.fitUV[1]; uw = ud = opts.fitUV[0]; } + if (!opts.noSides) { + B.quad(bk, p[3], p[2], p[6], p[7], [0, v0, uw, v0, uw, v1, 0, v1], cb, cb, col, col); // +z (front) + B.quad(bk, p[1], p[0], p[4], p[5], [0, v0, uw, v0, uw, v1, 0, v1], cb, cb, col, col); // -z + B.quad(bk, p[2], p[1], p[5], p[6], [0, v0, ud, v0, ud, v1, 0, v1], cb, cb, col, col); // +x + B.quad(bk, p[0], p[3], p[7], p[4], [0, v0, ud, v0, ud, v1, 0, v1], cb, cb, col, col); // -x + } + if (!opts.noTop) { + var tk = opts.topMat ? bucket(opts.topMat, x, z, opts.cls || opts.flags) : bk, ts = opts.topUvs || us; + B.quad(tk, p[7], p[6], p[5], p[4], [x / ts - hx / ts, z / ts + hz / ts, x / ts + hx / ts, z / ts + hz / ts, x / ts + hx / ts, z / ts - hz / ts, x / ts - hx / ts, z / ts - hz / ts], ct); + } + if (opts.bottom) B.quad(bk, p[0], p[1], p[2], p[3], [0, 0, w / us, 0, w / us, d / us, 0, d / us], cb); + if (opts.collide) { + return W.addBox({ x: x, z: z, y0: y0, y1: y1, hx: hx, hz: hz, yaw: yaw || 0, mat: opts.collide, cover: !!opts.cover, kind: opts.kind || '', see: !!opts.see, deck: !!opts.deck }); + } + return null; + }; + + // geometry from a THREE.BufferGeometry, transformed, into a bucket (columns, domes, boat hulls...). opts: uvs, uScale, + // vScale, uOff, vOff, pitch, roll, cls, aoY + ao, inside (draw the inner faces: the underside of a vault) + var _m4 = new T.Matrix4(), _q = new T.Quaternion(), _e = new T.Euler(), _v = new T.Vector3(), _s = new T.Vector3(), _nm = new T.Matrix3(), _gv = new T.Vector3(), _gn = new T.Vector3(); + B.geo = function (mat, g, x, y, z, yaw, sx, sy, sz, col, opts) { + opts = opts || {}; + _e.set(opts.pitch || 0, yaw || 0, opts.roll || 0, 'YXZ'); _q.setFromEuler(_e); + _m4.compose(_v.set(x, y, z), _q, _s.set(sx, sy == null ? sx : sy, sz == null ? sx : sz)); + _nm.getNormalMatrix(_m4); + var h = bucket(mat, x, z, opts.cls || opts.flags), bk = h.b, t = h.tint; + var P = g.attributes.position, N = g.attributes.normal, U = g.attributes.uv, C = g.attributes.color, I = g.index; + col = col || WHITE; + var tr = col.r * (t ? t.r : 1), tg = col.g * (t ? t.g : 1), tb = col.b * (t ? t.b : 1); + var uvs = opts.uvs || 1, v = _gv, n = _gn, nI = I ? I.count : P.count, flip = (sx * (sy == null ? sx : sy) * (sz == null ? sx : sz)) < 0; + bk.need(P.count * (h.dbl ? 2 : 1), nI * (h.dbl ? 2 : 1)); + var base = bk.n, uS = (opts.uScale || 1) / uvs, vS = (opts.vScale || 1) / uvs, uO = opts.uOff || 0, vO = opts.vOff || 0; + for (var pass = 0; pass < (h.dbl ? 2 : 1); pass++) { + for (var i = 0; i < P.count; i++) { + v.fromBufferAttribute(P, i).applyMatrix4(_m4); + if (N) n.fromBufferAttribute(N, i).applyMatrix3(_nm).normalize(); else n.set(0, 1, 0); + if (pass || opts.inside) n.multiplyScalar(pass && opts.inside ? 1 : -1); + var k = 1; + if (opts.aoY != null) k = 1 - opts.ao * M.clamp(1 - (v.y - opts.aoY) / 1.2, 0, 1); + var cr = tr * k, cg = tg * k, cb = tb * k; + if (C) { cr *= C.getX(i); cg *= C.getY(i); cb *= C.getZ(i); } + bk.vert(v.x, v.y, v.z, n.x, n.y, n.z, U ? U.getX(i) * uS + uO : v.x / uvs, U ? U.getY(i) * vS + vO : v.z / uvs, cr, cg, cb, h.mt); + } + var b0 = base + pass * P.count, rev = (flip !== !!pass) !== !!opts.inside; + for (i = 0; i < nI; i += 3) { + var a = I ? I.getX(i) : i, b = I ? I.getX(i + 1) : i + 1, c = I ? I.getX(i + 2) : i + 2; + bk.idx[bk.ni++] = b0 + a; bk.idx[bk.ni++] = b0 + (rev ? c : b); bk.idx[bk.ni++] = b0 + (rev ? b : c); + } + } + }; + + // a strip that follows the terrain along a polyline: lanes, the coast road, paths. pts [{x,z,y?}], y from terrain + // unless given; lift above it in metres. Collision is the terrain itself (the map flattens the ground under roads). + // opts: col, lift, uvs, edgeDark, cls, uAcross (texture tiles across the width, default width / uvs) + B.ribbon = function (mat, pts, width, opts) { + opts = opts || {}; + var col = opts.col || WHITE, lift = opts.lift == null ? 0.04 : opts.lift, us = opts.uvs || 2, edge = opts.edgeDark == null ? 1 : opts.edgeDark; + var dist = 0, prevL = null, prevR = null, prevD = 0, half = width / 2, ua = opts.uAcross || width / us; + var ce = edge === 1 ? col : col.clone().multiplyScalar(edge); + // resample at ~2 m so the strip hugs the ground + var rs = []; + for (var i = 0; i < pts.length - 1; i++) { + var a = pts[i], b = pts[i + 1], L = Math.hypot(b.x - a.x, b.z - a.z), n = Math.max(1, Math.ceil(L / 2)); + for (var k = 0; k < n; k++) { var t = k / n; rs.push({ x: a.x + (b.x - a.x) * t, z: a.z + (b.z - a.z) * t, y: a.y != null && b.y != null ? a.y + (b.y - a.y) * t : null }); } + } + rs.push(pts[pts.length - 1]); + for (i = 0; i < rs.length; i++) { + var p = rs[i], q = rs[Math.min(rs.length - 1, i + 1)], o = rs[Math.max(0, i - 1)]; + var dx = q.x - o.x, dz = q.z - o.z, l = Math.hypot(dx, dz) || 1, nx = -dz / l, nz = dx / l; + if (i > 0) dist += Math.hypot(p.x - rs[i - 1].x, p.z - rs[i - 1].z); + var Lx = p.x + nx * half, Lz = p.z + nz * half, Rx = p.x - nx * half, Rz = p.z - nz * half; + var yL = (p.y != null ? p.y : W.terrainH(Lx, Lz)) + lift, yR = (p.y != null ? p.y : W.terrainH(Rx, Rz)) + lift; + if (p.y == null) { var yc = W.terrainH(p.x, p.z) + lift; yL = Math.max(yL, yc - 0.05); yR = Math.max(yR, yc - 0.05); } + var Lp = new T.Vector3(Lx, yL, Lz), Rp = new T.Vector3(Rx, yR, Rz); + if (prevL) { + var bk = bucket(mat, p.x, p.z, opts.cls || opts.flags); + B.quad(bk, prevL, Lp, Rp, prevR, [0, prevD / us, 0, dist / us, ua, dist / us, ua, prevD / us], ce, ce, ce, ce); + } + prevL = Lp; prevR = Rp; prevD = dist; + } + }; + + // ------------------------------------------------------------------ leaf cards (one InstancedMesh per chunk) + var _lm = new T.Matrix4(), _lq = new T.Quaternion(), _le = new T.Euler(), _lp = new T.Vector3(), _ls = new T.Vector3(); + B.leaf = function (x, y, z, sx, sy, sz, color, rot) { + var k = Math.floor(x / CH) + '|' + Math.floor(z / CH), l = B.leaves[k]; + if (!l) { l = B.leaves[k] = { m: [], c: [], cx: Math.floor(x / CH), cz: Math.floor(z / CH) }; } + _le.set(0, rot == null ? Math.random() * 6.28 : rot, 0); _lq.setFromEuler(_le); + _lm.compose(_lp.set(x, y, z), _lq, _ls.set(sx, sy, sz)); + for (var i = 0; i < 16; i++) l.m.push(_lm.elements[i]); + l.c.push(color.r, color.g, color.b); + }; + // other instanced props (kept for maps that want their own): B.inst(geometry, material, matrices[]) + B.inst = function (geo, mat, mats, opts) { + if (!mats.length) return null; + var im = new T.InstancedMesh(geo, mat, mats.length); + for (var i = 0; i < mats.length; i++) im.setMatrixAt(i, mats[i]); + im.castShadow = !(opts && opts.noShadow); im.receiveShadow = true; + im.computeBoundingSphere(); + B.instanced.push(im); RP.R.scene.add(im); + B.tris += (geo.index ? geo.index.count : geo.attributes.position.count) / 3 * mats.length; + return im; + }; + + // ------------------------------------------------------------------ finish: buckets -> meshes, per chunk + function geoFrom(b) { + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.BufferAttribute(b.pos.slice(0, b.n * 3), 3)); + g.setAttribute('normal', new T.BufferAttribute(b.nrm.slice(0, b.n * 3), 3, true)); + g.setAttribute('uv', new T.BufferAttribute(b.uv.slice(0, b.n * 2), 2)); + g.setAttribute('aCol', new T.BufferAttribute(b.col.slice(0, b.n * 4), 4, true)); + g.setIndex(new T.BufferAttribute(b.n > 65535 ? b.idx.slice(0, b.ni) : new Uint16Array(b.idx.subarray(0, b.ni)), 1)); + g.computeBoundingSphere(); + return g; + } + B.finish = function () { + var R = RP.R, low = R.qname === 'low'; + B.range = B.RANGE[R.qname] || B.RANGE.medium; + var farParts = []; + Object.keys(B.buckets).forEach(function (k) { + var b = B.buckets[k]; if (!b.ni) return; + var c = chunkOf(b.cx, b.cz); + if (b.cls === 'far') { farParts.push(b); return; } + var mesh = new T.Mesh(geoFrom(b), RP.mat.town); + mesh.castShadow = b.cls !== 'flat'; mesh.receiveShadow = true; + mesh.matrixAutoUpdate = false; mesh.updateMatrix(); mesh.visible = false; + R.scene.add(mesh); B.meshes.push(mesh); c[b.cls] = mesh; + B.tris += b.ni / 3; + }); + // the far town: every chunk's building boxes in one mesh; the index buffer lists only the chunks that are far + if (farParts.length) { + var nv = 0, ni = 0; farParts.forEach(function (b) { nv += b.n; ni += b.ni; }); + var all = new Bucket('far', 0, 0); all.need(nv, ni); + farParts.forEach(function (b) { + var c = chunkOf(b.cx, b.cz), base = all.n; + all.pos.set(b.pos.subarray(0, b.n * 3), base * 3); all.nrm.set(b.nrm.subarray(0, b.n * 3), base * 3); + all.uv.set(b.uv.subarray(0, b.n * 2), base * 2); all.col.set(b.col.subarray(0, b.n * 4), base * 4); + var idx = new Uint32Array(b.ni); for (var i = 0; i < b.ni; i++) idx[i] = b.idx[i] + base; + c.farTown = idx; all.n += b.n; + }); + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.BufferAttribute(all.pos.slice(0, nv * 3), 3)); + g.setAttribute('normal', new T.BufferAttribute(all.nrm.slice(0, nv * 3), 3, true)); + g.setAttribute('uv', new T.BufferAttribute(all.uv.slice(0, nv * 2), 2)); + g.setAttribute('aCol', new T.BufferAttribute(all.col.slice(0, nv * 4), 4, true)); + var ia = new T.BufferAttribute(new Uint32Array(ni), 1); ia.setUsage(T.DynamicDrawUsage); g.setIndex(ia); g.setDrawRange(0, 0); + var fm = new T.Mesh(g, RP.mat.town); fm.frustumCulled = false; fm.castShadow = false; fm.receiveShadow = false; fm.matrixAutoUpdate = false; + R.scene.add(fm); B.farTown = fm; + } + B.buckets = {}; B.handles = {}; + // leaf cards + var q = R.q.fol; + Object.keys(B.leaves).forEach(function (k) { + var l = B.leaves[k], n = l.c.length / 3, keep = []; + for (var i = 0; i < n; i++) if (q >= 1 || M.hash2(i * 0.37 + l.cx, 1.3 + l.cz) < q) keep.push(i); + if (!keep.length) return; + var im = new T.InstancedMesh(B.geos.clump, RP.mat.leaves, keep.length), col = new T.Color(); + for (i = 0; i < keep.length; i++) { + var s = keep[i]; _lm.fromArray(l.m, s * 16); im.setMatrixAt(i, _lm); + im.setColorAt(i, col.setRGB(l.c[s * 3], l.c[s * 3 + 1], l.c[s * 3 + 2])); + } + im.instanceColor.needsUpdate = true; im.castShadow = !low; im.receiveShadow = true; im.matrixAutoUpdate = false; + im.computeBoundingSphere(); im.visible = false; + R.scene.add(im); B.instanced.push(im); chunkOf(l.cx, l.cz).leaf = im; + B.tris += keep.length * 8; + }); + B.leaves = {}; + // the far coast is seen well past the preset's draw distance (as bare terrain and plain boxes), so the camera's + // far plane moves out; the chunks' own ranges keep the cost where it was + R.camera.far = 9000; R.camera.updateProjectionMatrix(); + B._farKey = ''; + }; + + // ------------------------------------------------------------------ terrain chunks + // B.setLand({ hf, bounds, outer(x, z) -> height beyond the bounds, colour(x, z, h, slope, out[4]) }) + // builds the land textures (normals and tint, one texel per heightfield cell) and the far mesh (8 m cells for + // every chunk plus a coarse ring of hills beyond the map's edge); 2 m and 4 m meshes are made when first shown. + B.setLand = function (land) { + B.land = land; + var hf = land.hf, R = RP.R; + B.range = B.RANGE[R.qname] || B.RANGE.medium; + var ST = B.range.steps; + RP.MapTex.land(land); + // mid and far meshes: every chunk at the middle and the coarse cell size, each merged into one mesh whose index + // buffer lists only the chunks at that distance; the far one also carries the ring of hills beyond the map + var cx0 = Math.floor(hf.x0 / CH), cx1 = Math.ceil((hf.x0 + (hf.nx - 1) * hf.cell) / CH) - 1, cz0 = Math.floor(hf.z0 / CH), cz1 = Math.ceil((hf.z0 + (hf.nz - 1) * hf.cell) / CH) - 1; + var mp = [], mn = [], mc = [], mi = [], cz, cx, c, i0; + for (cz = cz0; cz <= cz1; cz++) for (cx = cx0; cx <= cx1; cx++) { + c = chunkOf(cx, cz); i0 = mi.length; + gridPatch(mp, mn, mc, mi, c.x0, c.z0, CH, CH, ST[1], null, ST[1] * 1.2); + c.midLand = new Uint32Array(mi.slice(i0)); mi.length = i0; + // the chunk's box (for the view test): the terrain's height range, with room for buildings on top + var lo = 1e9, hi = -1e9; + for (var zz = Math.max(c.z0, hf.z0); zz <= Math.min(c.z1, hf.z0 + (hf.nz - 1) * hf.cell); zz += 8) for (var xx = Math.max(c.x0, hf.x0); xx <= Math.min(c.x1, hf.x0 + (hf.nx - 1) * hf.cell); xx += 8) { var hh = W.terrainH(xx, zz); if (hh < lo) lo = hh; if (hh > hi) hi = hh; } + c.box = new T.Box3(new T.Vector3(c.x0, Math.min(lo, 0) - 4, c.z0), new T.Vector3(c.x1, hi + 45, c.z1)); + } + B.midLand = landGlobal(mp, mn, mc, B.chunkList.reduce(function (n, q) { return n + (q.midLand ? q.midLand.length : 0); }, 0)); + var pos = [], nrm = [], col = [], idx = []; + for (cz = cz0; cz <= cz1; cz++) for (cx = cx0; cx <= cx1; cx++) { + c = chunkOf(cx, cz); i0 = idx.length; + gridPatch(pos, nrm, col, idx, c.x0, c.z0, CH, CH, ST[2], null, ST[2] * 0.9); + c.farLand = new Uint32Array(idx.slice(i0)); idx.length = i0; + } + B._ringStart = 0; + var ring = []; + if (land.outer) { + var S = land.ringCell || 64, bx0 = hf.x0, bx1 = hf.x0 + (hf.nx - 1) * hf.cell, bz0 = hf.z0, bz1 = hf.z0 + (hf.nz - 1) * hf.cell; + var ex = land.ringX || 1536, en = land.ringN || 1280; + var rx0 = bx0 - ex, rx1 = bx1 + ex, rz0 = bz0 - en, rz1 = bz1; + var nxr = Math.round((rx1 - rx0) / S), nzr = Math.round((rz1 - rz0) / S), base = pos.length / 3, tmpC = [0, 0, 0, 0], nn = new T.Vector3(); + for (var j = 0; j <= nzr; j++) for (var i = 0; i <= nxr; i++) { + var x = rx0 + i * S, z = rz0 + j * S, inside = x >= bx0 && x <= bx1 && z >= bz0 && z <= bz1; + var h = inside ? W.terrainH(x, z) : land.outer(x, z); + if (inside) { W.terrainN(x, z, nn); h -= 0.5; } + else { var e = 12, hx = land.outer(x + e, z) - land.outer(x - e, z), hz = land.outer(x, z + e) - land.outer(x, z - e); nn.set(-hx, 2 * e, -hz).normalize(); } + pos.push(x, h, z); nrm.push(nn.x * 127, nn.y * 127, nn.z * 127); + land.colour(x, z, h, 1 - nn.y, tmpC, true); + col.push(enc(tmpC[0] * 0.5), enc(tmpC[1] * 0.5), enc(tmpC[2] * 0.5), Math.min(tmpC[3], 0.95) * 250); + } + for (j = 0; j < nzr; j++) for (i = 0; i < nxr; i++) { + var xa = rx0 + i * S, za = rz0 + j * S; + if (xa >= bx0 && xa + S <= bx1 && za >= bz0 && za + S <= bz1) continue; // the map itself fills the hole + var a = base + j * (nxr + 1) + i, b = a + 1, cc = a + nxr + 1, d = cc + 1; + if (pos[a * 3 + 1] < -6 && pos[b * 3 + 1] < -6 && pos[cc * 3 + 1] < -6 && pos[d * 3 + 1] < -6) continue; // open sea + ring.push(a, cc, b, b, cc, d); + } + // a curtain hanging from the ring's inner edge closes the slit where it stands above the map's own edge + var curtain = function (i0, j0, i1, j1) { + var va = base + j0 * (nxr + 1) + i0, vb = base + j1 * (nxr + 1) + i1, s0 = pos.length / 3; + if (pos[va * 3 + 1] < 0 && pos[vb * 3 + 1] < 0) return; + [va, vb].forEach(function (v) { pos.push(pos[v * 3], pos[v * 3 + 1] - 70, pos[v * 3 + 2]); nrm.push(nrm[v * 3], nrm[v * 3 + 1], nrm[v * 3 + 2]); col.push(col[v * 4], col[v * 4 + 1], col[v * 4 + 2], col[v * 4 + 3]); }); + ring.push(va, vb, s0, vb, s0 + 1, s0, va, s0, vb, vb, s0, s0 + 1); + }; + var ia = Math.round((bx0 - rx0) / S), ib = Math.round((bx1 - rx0) / S), ja = Math.round((bz0 - rz0) / S), jb = Math.round((bz1 - rz0) / S); + for (i = ia; i < ib; i++) curtain(i, ja, i + 1, ja); + for (j = ja; j < jb; j++) { curtain(ia, j, ia, j + 1); curtain(ib, j, ib, j + 1); } + } + B._ring = new Uint32Array(ring); + B.farLand = landGlobal(pos, nrm, col, B._ring.length + B.chunkList.reduce(function (n, q) { return n + (q.farLand ? q.farLand.length : 0); }, 0)); + B._farKey = B._midKey = ''; + }; + function landGlobal(pos, nrm, col, indexCount) { + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.BufferAttribute(new Float32Array(pos), 3)); + g.setAttribute('normal', new T.BufferAttribute(new Int8Array(nrm), 3, true)); + g.setAttribute('aCol', new T.BufferAttribute(new Uint8Array(col), 4, true)); + var ia = new T.BufferAttribute(new Uint32Array(indexCount), 1); ia.setUsage(T.DynamicDrawUsage); g.setIndex(ia); g.setDrawRange(0, 0); + var m = new T.Mesh(g, RP.mat.land); m.frustumCulled = false; m.receiveShadow = false; m.castShadow = false; m.matrixAutoUpdate = false; + RP.R.scene.add(m); + return m; + } + // a square patch of the heightfield as a grid with skirts round the edge. Appends to plain arrays (pos, nrm, col, + // idx); positions outside the heightfield are clamped onto its edge. + var _tn = new T.Vector3(); + function gridPatch(pos, nrm, col, idx, x0, z0, w, d, step, unused, skirt0) { + var hf = B.land.hf, bx0 = hf.x0, bx1 = hf.x0 + (hf.nx - 1) * hf.cell, bz0 = hf.z0, bz1 = hf.z0 + (hf.nz - 1) * hf.cell; + var xa = Math.max(x0, bx0), xb = Math.min(x0 + w, bx1), za = Math.max(z0, bz0), zb = Math.min(z0 + d, bz1); + if (xb <= xa || zb <= za) return; + var nx = Math.round((xb - xa) / step), nz = Math.round((zb - za) / step), base = pos.length / 3; + for (var j = 0; j <= nz; j++) for (var i = 0; i <= nx; i++) { + var x = xa + i * step, z = za + j * step, th = W.terrainH(x, z); + if (step > hf.cell && B.land.cap) { var cp = B.land.cap(x, z, step); if (cp < th) th = cp; } // coarse cells keep off the roads + pos.push(x, th, z); + W.terrainN(x, z, _tn); nrm.push(_tn.x * 127, _tn.y * 127, _tn.z * 127); + col.push(181, 181, 181, 200); + } + for (j = 0; j < nz; j++) for (i = 0; i < nx; i++) { var a = base + j * (nx + 1) + i; idx.push(a, a + nx + 1, a + 1, a + 1, a + nx + 1, a + nx + 2); } + // skirts: a strip hanging from each edge hides the cracks between resolutions + function skirtEdge(get, n, onEdge) { + var s0 = pos.length / 3, skirt = onEdge ? Math.max(skirt0, 30) : skirt0; // the map's own edge hangs lower: the far ring beyond it is coarse + for (var k = 0; k <= n; k++) { + var a = base + get(k), px = pos[a * 3], py = pos[a * 3 + 1], pz = pos[a * 3 + 2]; + pos.push(px, py - skirt, pz); nrm.push(nrm[a * 3], nrm[a * 3 + 1], nrm[a * 3 + 2]); col.push(181, 181, 181, 200); + } + for (k = 0; k < n; k++) { + var t0 = base + get(k), t1 = base + get(k + 1), b0 = s0 + k, b1 = s0 + k + 1; + idx.push(t0, b0, t1, t1, b0, b1, t0, t1, b0, t1, b1, b0); // both ways round: seen from either side + } + } + skirtEdge(function (k) { return k; }, nx, za <= bz0); // north edge (j = 0) + skirtEdge(function (k) { return nz * (nx + 1) + k; }, nx, zb >= bz1); // south edge + skirtEdge(function (k) { return k * (nx + 1); }, nz, xa <= bx0); // west edge + skirtEdge(function (k) { return k * (nx + 1) + nx; }, nz, xb >= bx1); // east edge + } + function landMesh(c, step) { + var pos = [], nrm = [], col = [], idx = []; + gridPatch(pos, nrm, col, idx, c.x0, c.z0, CH, CH, step, null, step * 1.2); + if (!idx.length) return null; + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.BufferAttribute(new Float32Array(pos), 3)); + g.setAttribute('normal', new T.BufferAttribute(new Int8Array(nrm), 3, true)); + g.setAttribute('aCol', new T.BufferAttribute(new Uint8Array(col), 4, true)); + g.setIndex(new T.BufferAttribute(new Uint16Array(idx), 1)); + g.computeBoundingSphere(); + var m = new T.Mesh(g, RP.mat.land); m.receiveShadow = true; m.castShadow = false; m.matrixAutoUpdate = false; m.visible = false; + RP.R.scene.add(m); + return m; + } + + // ------------------------------------------------------------------ streaming: called every frame with the camera + function setVis(m, on) { if (m && m.visible !== on) m.visible = on; } + var _fr = new T.Frustum(), _pm = new T.Matrix4(), _pv = new T.Matrix4(); + B.stream = function (cam) { + var L = B.chunkList; if (!L || !L.length || !B.range) return; + var px = cam.position.x, pz = cam.position.z, rg = B.range, fkey = '', mkey = '', H = 10, t0 = performance.now(), i; + // the merged middle and far meshes list only the chunks the camera can see + cam.updateMatrixWorld(); _pm.multiplyMatrices(cam.projectionMatrix, _pv.copy(cam.matrixWorld).invert()); _fr.setFromProjectionMatrix(_pm); + for (i = 0; i < L.length; i++) { + var c = L[i]; + var dx = px < c.x0 ? c.x0 - px : px > c.x1 ? px - c.x1 : 0, dz = pz < c.z0 ? c.z0 - pz : pz > c.z1 ? pz - c.z1 : 0; + var d = Math.sqrt(dx * dx + dz * dz); c.d = d; + // each flag has a little hysteresis so a chunk on the edge does not flicker + c.vFar = c.vFar ? d > rg.far - H : d > rg.far; + c.vNear = c.vNear ? d < rg.near + H : d < rg.near; + c.vFol = c.vFol ? d < rg.fol + H : d < rg.fol; + c.vTn = c.vTn ? d < rg.tnear + H : d < rg.tnear; + var inR = !c.vFar; + setVis(c.shell, inR); setVis(c.detail, c.vNear); setVis(c.flat, c.vNear); setVis(c.leaf, c.vFol); + if (c.detail) c.detail.castShadow = d < 70; // small things only throw shadows worth drawing close by + if (c.extra) for (var q = 0; q < c.extra.length; q++) setVis(c.extra[q], inR); + if (B.land && c.farLand) { + // the finest terrain mesh is made the first time it is wanted, a few milliseconds' worth a frame; until + // then the chunk shows in the middle mesh + var wantN = inR && c.vTn; + if (wantN && !c.tn && !c._tnTried && performance.now() - t0 < 6) { c.tn = landMesh(c, rg.steps[0]); c._tnTried = true; } + if (wantN && !c.tn) wantN = false; + setVis(c.tn, wantN); + var seen = !c.box || _fr.intersectsBox(c.box); + c.mid = inR && !wantN && seen; c.far = !inR && seen; c.farT = c.vFar && seen; + if (c.mid) mkey += i + ','; + } else { c.far = c.vFar; c.farT = c.vFar; } + if (c.farT) fkey += i + ','; + } + if (mkey !== B._midKey) { B._midKey = mkey; refill(B.midLand, 'midLand', null, function (c) { return c.mid; }); } + if (fkey !== B._farKey) { + B._farKey = fkey; + refill(B.farLand, 'farLand', B._ring, function (c) { return c.far; }); + refill(B.farTown, 'farTown', null, function (c) { return c.farT; }); + } + // people past the draw distance are not drawn (the far plane used to do this); bystanders drop out sooner + var G = RP.G, E = G && G.ents, far2 = RP.R.q.far * RP.R.q.far, civ2 = rg.civ * rg.civ; + if (E) for (i = 0; i < E.length; i++) { + var e = E[i], a = e.actor; if (!a || !a.root || e === G.player || e.ghost) continue; + var ex = e.pos.x - px, ez = e.pos.z - pz, d2 = ex * ex + ez * ez, farE = d2 > far2 || (d2 > civ2 && e.team === 'civ' && e.alive); + if (farE && a.root.visible) { a.root.visible = false; a._farHid = true; } + else if (!farE && a._farHid) { a.root.visible = true; a._farHid = false; } + } + // the same for pickups and dropped weapons + var IL = RP.Items && RP.Items.list; + if (IL) for (i = 0; i < IL.length; i++) { + var it = IL[i], g = it.g; if (!g) continue; + var ix = g.position.x - px, iz = g.position.z - pz, farI = ix * ix + iz * iz > far2; + if (farI && g.visible) { g.visible = false; it._farHid = true; } + else if (!farI && it._farHid) { g.visible = true; it._farHid = false; } + } + // and parked cars and boats + var VL = RP.Vehicles && RP.Vehicles.list; + if (VL) for (i = 0; i < VL.length; i++) { + var vh = VL[i], vg = vh.g; if (!vg || !vh.pos) continue; + var vx = vh.pos.x - px, vz = vh.pos.z - pz, farV = vx * vx + vz * vz > far2; + if (farV && vg.visible) { vg.visible = false; vh._farHid = true; } + else if (!farV && vh._farHid) { vg.visible = true; vh._farHid = false; } + } + }; + function refill(mesh, field, always, test) { + if (!mesh) return; + var ia = mesh.geometry.index, arr = ia.array, n = 0, L = B.chunkList; + if (always) { arr.set(always, 0); n = always.length; } + for (var i = 0; i < L.length; i++) { var c = L[i]; if (c[field] && test(c)) { arr.set(c[field], n); n += c[field].length; } } + ia.needsUpdate = true; mesh.geometry.setDrawRange(0, n); + } + // triangles a preset would draw if everything in range were on screen (for the notes; the real count is in R.stats) + B.count = function () { var n = 0; B.meshes.forEach(function (m) { if (m.visible) n += m.geometry.index.count / 3; }); return n; }; + + // ------------------------------------------------------------------ shared prop geometries (made once) + B.geos = {}; + B.makeGeos = function () { + var G = B.geos; if (G.cyl) return; + G.cyl = new T.CylinderGeometry(0.5, 0.5, 1, 12, 1); G.cyl.translate(0, 0.5, 0); + G.cyl8 = new T.CylinderGeometry(0.5, 0.5, 1, 8, 1); G.cyl8.translate(0, 0.5, 0); + G.cyl6 = new T.CylinderGeometry(0.5, 0.5, 1, 6, 1); G.cyl6.translate(0, 0.5, 0); + G.cone = new T.ConeGeometry(0.5, 1, 10, 1); G.cone.translate(0, 0.5, 0); + G.cone8 = new T.ConeGeometry(0.5, 1, 8, 1, true); G.cone8.translate(0, 0.5, 0); + G.cone5 = new T.ConeGeometry(0.5, 1, 5, 1); G.cone5.translate(0, 0.5, 0); + G.sphere = new T.SphereGeometry(0.5, 12, 8); + G.blob = new T.SphereGeometry(0.5, 6, 4); + G.hemi = new T.SphereGeometry(0.5, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2); + G.hemi8 = new T.SphereGeometry(0.5, 8, 3, 0, Math.PI * 2, 0, Math.PI / 2); + // barrel vault (half cylinder along local z, arching up from y = 0), 1 x 0.5 x 1, open at both ends (close them + // with halfDisc); drawn with { inside: true } it is the ceiling of a passage or tunnel + G.vault = new T.CylinderGeometry(0.5, 0.5, 1, 12, 1, true, -Math.PI / 2, Math.PI); G.vault.rotateX(-Math.PI / 2); + G.vault8 = new T.CylinderGeometry(0.5, 0.5, 1, 7, 1, true, -Math.PI / 2, Math.PI); G.vault8.rotateX(-Math.PI / 2); // house roofs + G.halfDisc7 = new T.CircleGeometry(0.5, 7, 0, Math.PI); + // half disc (the end wall of a vault, the head of an arched window): unit diameter, in the xy plane, facing +z + G.halfDisc = new T.CircleGeometry(0.5, 10, 0, Math.PI); + // leaf clump: three crossed cards + var cards = []; + for (var i = 0; i < 3; i++) { var p = new T.PlaneGeometry(1, 1); p.rotateY(i * Math.PI / 3); cards.push(p); } + var h = new T.PlaneGeometry(1, 1); h.rotateX(-Math.PI / 2); h.translate(0, 0.12, 0); cards.push(h); + G.clump = mergeGeos(cards); + // canopy normals: out from a point a little below the clump's centre, so the crown is lit like a rounded mass + var CP = G.clump.attributes.position, CN = G.clump.attributes.normal, cv = new T.Vector3(); + for (i = 0; i < CP.count; i++) { cv.set(CP.getX(i), CP.getY(i) + 0.35, CP.getZ(i)).normalize(); CN.setXYZ(i, cv.x, cv.y, cv.z); } + CN.needsUpdate = true; + }; + function mergeGeos(list) { + var pos = [], nrm = [], uv = [], idx = [], base = 0; + list.forEach(function (g) { + var P = g.attributes.position, N = g.attributes.normal, U = g.attributes.uv; + for (var i = 0; i < P.count; i++) { pos.push(P.getX(i), P.getY(i), P.getZ(i)); nrm.push(N.getX(i), N.getY(i), N.getZ(i)); uv.push(U.getX(i), U.getY(i)); } + var I = g.index; for (i = 0; i < I.count; i++) idx.push(base + I.getX(i)); + base += P.count; + }); + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setAttribute('normal', new T.Float32BufferAttribute(nrm, 3)); + g.setAttribute('uv', new T.Float32BufferAttribute(uv, 2)); g.setIndex(idx); return g; + } + B.mergeGeos = mergeGeos; +})(); diff --git a/e63334287a3deaa3/blacktie/js/camera.js b/e63334287a3deaa3/blacktie/js/camera.js new file mode 100644 index 00000000..ff2ff29f --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/camera.js @@ -0,0 +1,173 @@ +/* + * Camera (RP.Cam): orbits freely round the player without turning them; pulls into a closer right-shoulder view when + * aiming, widens with a little motion when sprinting, shifts to the open side in cover, goes to a scope view with the + * sniper rifle, and V switches to first person. It never passes through walls (a cast from the pivot pulls it in). + * Aim assist lives here too: Assisted Full (snap and follow), Assisted Partial (snap on aim, then free), Free Aim + * Assisted (slows over targets), Free Aim (none). Flick the look input while locked to switch targets. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W, TU = RP.TUNING; + var C = RP.Cam = { yaw: 0, pitch: -0.12, dist: TU.camDist, fov: TU.camFov, side: 1, shoulder: TU.camShoulder, h: TU.camHeight, fp: false, scoped: false, lock: null, kickP: 0, kickY: 0, shakeK: 0 }; + var pivot = new T.Vector3(), want = new T.Vector3(), cur = new T.Vector3(), first = true; + + C.reset = function (p) { C.yaw = p.yaw; C.pitch = -0.1; first = true; C.lock = null; }; + C.kick = function (dp, dy) { C.kickP += dp; C.kickY += dy; }; + C.shake = function (k) { if (RP.settings.camShake) C.shakeK = Math.min(1.5, C.shakeK + k); }; + + C.aimRay = function () { + var cam = RP.R.camera, dir = new T.Vector3(0, 0, -1).applyQuaternion(cam.quaternion); + return { o: cam.position.clone(), dir: dir }; + }; + // the first thing the crosshair ray meets (world or a person), skipping the player and points behind the shoulder + C.aimPoint = function (ray, maxT) { + var p = RP.G.player, o = ray.o.clone(), d = ray.dir; + // start the ray level with the player so walls between camera and player aren't hit + var skip = Math.max(0, p.pos.clone().setY(p.pos.y + 1.4).sub(o).dot(d)); + o.addScaledVector(d, skip); + var h = W.ray(o.x, o.y, o.z, d.x, d.y, d.z, maxT); + var e = RP.Combat.hitEnts(o, d, h ? h.t : maxT, p); + if (e) return e.point; + if (h) return new T.Vector3(h.x, h.y, h.z); + return o.addScaledVector(d, maxT); + }; + + // ---- aim assist + function targets(p) { + var cam = RP.R.camera, list = []; + RP.G.guards.forEach(function (g) { + if (!g.alive) return; + var c = g.actor.chest(new T.Vector3()); c.y += 0.05; + var d = c.distanceTo(cam.position), def = RP.Weapons.DEFS[p.cur]; + var range = def.range && def.range[1] ? def.range[1] * 1.3 : 60; + if (d > range) return; + var sp = c.clone().project(cam); + if (sp.z > 1 || Math.abs(sp.x) > 1 || Math.abs(sp.y) > 1) return; + if (!W.los(cam.position.x, cam.position.y, cam.position.z, c.x, c.y, c.z) && !W.los(p.pos.x, p.pos.y + 1.5, p.pos.z, c.x, c.y, c.z)) return; + list.push({ g: g, c: c, sx: sp.x * cam.aspect, sy: sp.y, d: d }); + }); + return list; + } + function aimAt(c, k, dt) { + var cam = RP.R.camera, to = c.clone().sub(cam.position); + var y = Math.atan2(to.x, to.z), pch = Math.atan2(to.y, Math.hypot(to.x, to.z)); + // camera looks along (sin yaw, ., cos yaw): adjust yaw/pitch toward the target + C.yaw = M.dampAngle(C.yaw, y + 0.035 * C.side, k, dt); C.pitch = M.damp(C.pitch, pch, k, dt); + } + function assist(p, dt) { + var I = RP.In, mode = RP.settings.targeting; + if (RP.In.lastDevice === 'kbm' && mode !== 'free' && mode !== 'freeAssist') { /* keyboard players can still pick assisted modes */ } + if (!p.aiming || mode === 'free' || RP.Weapons.DEFS[p.cur].melee) { C.lock = null; return; } + var list = targets(p); + if (I.pressed('aim') || (p.aiming && C._wasAim === false)) { + // on aim: pick the target nearest the crosshair (assisted modes snap) + var best = null, bs = 0.35; + list.forEach(function (t) { var s = Math.hypot(t.sx, t.sy); if (s < bs) { bs = s; best = t; } }); + if (best && mode !== 'freeAssist') C.lock = { g: best.g, t: 0 }; + else if (best && mode === 'freeAssist') C.snapT = { c: best.c, t: 0.12 }; + } + C._wasAim = p.aiming; + if (C.snapT) { aimAt(C.snapT.c, 22, dt); C.snapT.t -= dt; if (C.snapT.t <= 0) C.snapT = null; } + if (C.lock) { + var g = C.lock.g, ok = g.alive && list.some(function (t) { return t.g === g; }); + if (!ok) { C.lock = null; return; } + C.lock.t += dt; + // flick to switch: a quick look movement picks the next target on that side + var flick = I.look.x / Math.max(dt, 1e-3); + if (Math.abs(flick) > 6 && C.lock.t > 0.2) { + var cur = list.filter(function (t) { return t.g === g; })[0], nxt = null, nd = 9; + list.forEach(function (t) { if (t.g === g) return; var dx = t.sx - cur.sx; if (Math.sign(dx) === Math.sign(flick) && Math.abs(dx) < nd) { nd = Math.abs(dx); nxt = t; } }); + if (nxt) { C.lock = { g: nxt.g, t: 0 }; } + } + var tc = C.lock.g.actor.chest(new T.Vector3()); tc.y += mode === 'assistFull' ? 0.05 : 0; + if (mode === 'assistFull') aimAt(tc, 14, dt); + else if (C.lock.t < 0.18) aimAt(tc, 20, dt); // partial: snap, then free + else C.lock = null; + } else if (mode === 'freeAssist' || mode === 'assistPartial') { + // friction: slow the look while the crosshair is over a target + var over = list.some(function (t) { return Math.hypot(t.sx, t.sy) < 0.06; }); + C.friction = over ? 0.55 : 1; + } + } + + C.update = function (dt, p) { + var I = RP.In, d = RP.Player.def(p); + if (I.pressed('camera')) { C.fp = !C.fp; RP.settings.firstPerson = C.fp; } + // look + var fr = C.friction || 1; C.friction = 1; + var aimSlow = p.aiming ? (C.scoped ? 0.35 : 0.65) : 1; + if (!p.wheelOpen) { C.yaw -= I.look.x * aimSlow * fr; C.pitch -= I.look.y * aimSlow * fr; } + assist(p, dt); + // recoil kicks the view up; it recovers + C.pitch += C.kickP * Math.min(1, dt * 30); C.yaw += C.kickY * Math.min(1, dt * 30); + C.kickP *= Math.exp(-dt * 30); C.kickY *= Math.exp(-dt * 30); + C.pitch = M.clamp(C.pitch, -1.35, 1.2); + // mode targets + var aim = p.aimW, sprint = p.sprinting ? 1 : 0, cover = p.cover && !p.cover.entering ? 1 : 0; + C.scoped = p.aiming && d.scope && p.aimW > 0.85; + var dist = M.lerp(TU.camDist, TU.aimDist, aim), fov = M.lerp(TU.camFov, TU.aimFov, aim) + (RP.settings.fov || 0); + var sh = M.lerp(TU.camShoulder, TU.aimShoulder, aim), h = M.lerp(TU.camHeight, TU.aimHeight, aim); + if (d.zoom) fov = M.lerp(fov, fov * d.zoom, aim); // a fitted scope brings the view closer + if (sprint) { dist = M.lerp(dist, TU.sprintDist, 0.8); fov = M.lerp(fov, TU.sprintFov, 0.8); } + if (cover && !p.aiming) { dist = TU.coverDist; if (p.cover.low) h -= 0.35; } + if (p.stealth && !p.aiming) h -= 0.25; + if (p.state === 'ragdoll' || p.state === 'dead') { dist = 4; h = 0.8; } + if (p.vehicle) { + // chase view: further back and higher, wider with speed; swings in behind the car when the look is left alone + var vs = Math.abs(p.vehicle.v) / p.vehicle.ty.top; + dist = (p.vehicle.ty.water ? 9 : 6.2) + vs * 1.6 - aim * 2.2; h = 1.55 + (p.vehicle.ty.water ? 0.9 : 0.35); sh = aim * 0.5; fov += vs * 9; + C._idleLook = Math.abs(I.look.x) + Math.abs(I.look.y) > 1e-4 || p.aiming ? 0 : (C._idleLook || 0) + dt; + if (C._idleLook > 1.1 && Math.abs(p.vehicle.v) > 2) { C.yaw = M.dampAngle(C.yaw, p.vehicle.yaw + (p.vehicle.v < -1 ? Math.PI : 0), 2.2, dt); C.pitch = M.damp(C.pitch, -0.16, 1.5, dt); } + } + // shoulder side: in cover, the side the player faces; otherwise right + var side = cover ? (p.cover.side > 0 ? -1 : 1) : 1; + C.side = M.damp(C.side, side, 6, dt); + C.dist = M.damp(C.dist, dist, 9, dt); C.fov = M.damp(C.fov, fov, 10, dt); C.shoulder = M.damp(C.shoulder, sh, 9, dt); C.h = M.damp(C.h, h, 8, dt); + var cam = RP.R.camera; + var fwd = new T.Vector3(Math.sin(C.yaw) * Math.cos(C.pitch), Math.sin(C.pitch), Math.cos(C.yaw) * Math.cos(C.pitch)); + var right = new T.Vector3(-Math.cos(C.yaw), 0, Math.sin(C.yaw)); + var tgtPos = p.state === 'ragdoll' || p.state === 'dead' ? p.actor.pelvis(new T.Vector3()) : p.pos; + pivot.set(tgtPos.x, (p.state === 'ragdoll' || p.state === 'dead' ? tgtPos.y - 0.6 : tgtPos.y) + C.h, tgtPos.z); + if (first) { cur.copy(pivot); first = false; } + // the pivot follows smoothly vertically (stairs), tightly horizontally + cur.x = pivot.x; cur.z = pivot.z; cur.y = M.damp(cur.y, pivot.y, 14, dt); + if (C.fp || C.scoped) { + // first person / scope: at the eyes + var eye = p.actor.head(new T.Vector3()); eye.y += 0.08; eye.addScaledVector(new T.Vector3(Math.sin(C.yaw), 0, Math.cos(C.yaw)), 0.14); + cam.position.copy(eye); + cam.fov = C.scoped ? 14 : 72; + p.actor.root.visible = C.scoped ? false : true; + if (p.actor.hat) p.actor.hat.visible = false; + // no head of your own in view (the run leans it past the eye): the head bone shrinks to nothing, taking the face, + // hair and eyes with it; its position (the eye) is unchanged + if (p.actor.bones.Head) p.actor.bones.Head.scale.setScalar(0.001); + } else { + p.actor.root.visible = true; if (p.actor.hat) p.actor.hat.visible = true; + if (p.actor.bones.Head && p.actor.bones.Head.scale.x !== 1) p.actor.bones.Head.scale.setScalar(1); + want.copy(cur).addScaledVector(right, C.shoulder * C.side).addScaledVector(fwd, -C.dist); + // sprint: a little bob and roll + if (sprint && p.speed > 4) { var tb = RP.G.time * 11; want.y += Math.sin(tb) * 0.035; } + // keep the camera out of walls: cast from the pivot (shoulder) toward it + var from = cur.clone().addScaledVector(right, C.shoulder * C.side * 0.6); + var to = want.clone().sub(from), L = to.length(); to.divideScalar(L || 1); + var hit = W.ray(from.x, from.y, from.z, to.x, to.y, to.z, L + 0.25, { noWater: true, skip: function (b) { return b.see || b.y1 - b.y0 < 0.6; } }); + if (hit) want.copy(from).addScaledVector(to, Math.max(0.3, hit.t - 0.25)); + var gy = W.terrainH(want.x, want.z) + 0.25; if (want.y < gy) want.y = gy; + cam.position.copy(want); + cam.fov = C.fov; + } + // look direction + var look = cam.position.clone().add(fwd); + cam.up.set(0, 1, 0); + cam.lookAt(look); + // shake + if (C.shakeK > 0.001) { + var s = C.shakeK * C.shakeK * 0.05, t = RP.G.time * 40; + cam.rotateX(Math.sin(t * 1.1) * s); cam.rotateY(Math.sin(t * 0.9 + 1) * s); cam.rotateZ(Math.sin(t * 1.3 + 2) * s * 0.5); + C.shakeK *= Math.exp(-dt * 5); + } + if (sprint && p.speed > 4 && !C.fp) cam.rotateZ(Math.sin(RP.G.time * 5.5) * 0.004 + M.clamp(-(p.turnRate || 0) * 0.01, -0.02, 0.02)); + cam.updateProjectionMatrix(); + cam.updateMatrixWorld(); + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/chars.js b/e63334287a3deaa3/blacktie/js/chars.js new file mode 100644 index 00000000..5736a172 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/chars.js @@ -0,0 +1,1012 @@ +/* + * Characters (RP.Chars): loads the rigged people and the animation clips, and drives them. + * + * Assets (assets/, copied unchanged from Midnight Ops' build; licences in CREDITS.md): hero.glb (the agent's body), + * enemy.glb (four outfits on one body, used for the guards and, recoloured, for guests), anims.glb (71 clips on the + * shared skeleton) and anims.json (stride and speed of the motion-capture loops). The clothes are recoloured in the + * shader (skin, eyes and hair keep their colours), so the agent wears dark navy, the guards black or grey, the guests + * light summer colours. + * + * Actor (1 unit = 1 m, feet at the origin, facing +Z, +X is the character's left): + * a.root Group to place in the world (position = feet, rotation.y = yaw) + * a.drive(st) the locomotion graph input, once per frame: + * st.speed (m/s along the ground), st.dir (move direction relative to facing, rad, +left), + * st.strafe (0..1: 8-way strafing vs. turning to the move direction), st.stealth (0..1), st.sprint (0..1), + * st.turnRate (rad/s, for steps in place and lean), st.accel (m/s^2 forward, for lean) + * a.setUpper(name|null, fade) a held upper-body pose (holdRifle, holdPistol, aimIdle, aimPistol, crouchAim, ...) + * a.playUpper(name, {speed, fade}) one-shot over the upper body (fire, firePistol, reload, throw, melee ...) + * a.playFull(name, {speed, fade, hold}) one-shot over the whole body (vault, takedown, deathFront, stagger, hit ...) + * a.move(name, {speed, side}) a code-authored move on top of everything (punches, kicks, roll, dodge, jump, + * climb, get-up, melee swings, draw, holster, pistol whip): see MOVES + * a.setAim(pitch, yaw) aim offset over the spine, neck and head (rad; yaw +left) + * a.hold(weaponObject|null) put a weapon in the right hand (on the weapon_r prop bone); its userData.gripL + * (Object3D) pulls the left hand on by IK when a two-handed pose is up + * a.flinch(dirX, dirZ, k) a quick additive hit reaction (world direction the hit came FROM) + * a.update(dt) advance (call once per rendered frame after drive) + * a.bone(name), a.head(), a.chest(): world positions for aiming, hit boxes and sight lines + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M; + var C = RP.Chars = { info: { loaded: false, errors: [], bytes: 0 }, lod: [12, 30] }; + var ASSETS = 'assets/', VERSION = '1'; + var gltf = {}, META = {}, CLIPS = {}, UPPER = {}, LOWER = {}, TEMPLATES = {}; + + // ------------------------------------------------------------------ outfits (sRGB): which mesh, cloth colours + var KINDS = { + // 'real' kinds are the MakeHuman-built people (tools/chars): their own clothes textures, hair and eyes, no recolour + agent: { file: 'agent', meshes: ['Agent', 'AgentHair', 'AgentEyes'], lod: ['AgentLOD1', 'AgentLOD2'], h: 1.84, real: true }, + sentry: { file: 'tac', meshes: ['Tac', 'TacHair', 'TacEyes'], lod: ['TacLOD1', 'TacLOD2'], h: 1.82, real: true }, + enforcer: { file: 'tac', meshes: ['Tac', 'TacHair', 'TacEyes'], lod: ['TacLOD1', 'TacLOD2'], h: 1.82, real: true, hw: ['cap', '#141416'] }, + elite: { file: 'suit', meshes: ['Suit', 'SuitHair', 'SuitEyes'], lod: ['SuitLOD1', 'SuitLOD2'], h: 1.84, real: true, glasses: true }, + marksman: { file: 'tac', meshes: ['Tac', 'TacHair', 'TacEyes'], lod: ['TacLOD1', 'TacLOD2'], h: 1.82, real: true, hw: ['beanie', '#2a2b28'] }, + civm1: { file: 'civm1', meshes: ['CivM1', 'CivM1Hair', 'CivM1Eyes'], lod: ['CivM1LOD1', 'CivM1LOD2'], h: 1.78, real: true, civ: true }, + civm2: { file: 'civm2', meshes: ['CivM2', 'CivM2Hair', 'CivM2Eyes'], lod: ['CivM2LOD1', 'CivM2LOD2'], h: 1.76, real: true, civ: true }, + civf1: { file: 'civf1', meshes: ['CivF1', 'CivF1Hair', 'CivF1Eyes'], lod: ['CivF1LOD1', 'CivF1LOD2'], h: 1.64, real: true, civ: true }, + civf2: { file: 'civf2', meshes: ['CivF2', 'CivF2Hair', 'CivF2Eyes'], lod: ['CivF2LOD1', 'CivF2LOD2'], h: 1.56, real: true, civ: true } + }; + var GUEST_COLS = [['#efe8d8', '#ddd3bf'], ['#a9c4dd', '#94adc4'], ['#e8b4a0', '#d29f8b'], ['#f4f1ea', '#e3ded4'], ['#c8d6b0', '#b3c19c'], ['#2f3f5a', '#25324a'], ['#d9d2c4', '#c4bcae']]; + + // ------------------------------------------------------------------ loading + 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(src)); }; document.head.appendChild(s); }); + } + 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 + name + '.glb?v=' + VERSION, res, function (e) { prog(name, e.loaded, e.total); }, rej); + }); + } + C.load = function (onProgress) { + if (C._p) return C._p; + var seen = {}, totals = { agent: 1.78e6, tac: 1.88e6, suit: 1.68e6, civm1: 1.66e6, civm2: 1.7e6, civf1: 1.84e6, civf2: 1.38e6, anims: 2.89e6 }; + var files = ['anims']; Object.keys(KINDS).forEach(function (k) { if (files.indexOf(KINDS[k].file) < 0) files.push(KINDS[k].file); }); + function prog(n, a, b) { seen[n] = a; if (b) totals[n] = b; var x = 0, y = 0; for (var k in totals) { x += Math.min(seen[k] || 0, totals[k]); y += totals[k]; } if (onProgress) onProgress(Math.min(0.99, x / y)); } + C._p = (window.MeshoptDecoder ? Promise.resolve() : addScript(ASSETS + 'lib/meshopt_decoder.js')).then(function () { return window.MeshoptDecoder && MeshoptDecoder.ready; }) + .then(function () { + return Promise.all(files.map(function (n) { return loadGLB(n, prog).then(function (g) { gltf[n] = g; }); })) + .then(function () { return fetch(ASSETS + 'anims.json?v=' + VERSION).then(function (r) { return r.json(); }).then(function (j) { META = j; }); }); + }).then(function () { + prepClips(gltf.anims.animations); + Object.keys(KINDS).forEach(function (k) { TEMPLATES[k] = template(k); }); + C.info.loaded = true; for (var k in seen) C.info.bytes += seen[k]; + return C; + }).catch(function (e) { C.info.errors.push(String(e && e.message || e)); throw e; }); + return C._p; + }; + + var upperSet = {}; + function prepClips(anims) { + ['spine_01', 'spine_02', 'spine_03', 'neck_01', 'Head', 'weapon_r'].forEach(function (b) { upperSet[b] = 1; }); + anims.forEach(function (c) { + c.tracks = c.tracks.filter(function (t) { + var bn = t.name.split('.')[0], pr = t.name.split('.')[1]; + if (/(clavicle|upperarm|lowerarm|hand|thumb|index|middle|ring|pinky)_/.test(bn)) upperSet[bn] = 1; + if (pr === 'scale') return false; + if (pr === 'position' && bn !== 'pelvis') return false; + return true; + }); + }); + 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]]; })); + }); + C.clips = Object.keys(CLIPS); + } + // The clips carry the hip height of the body they were made on (pelvis 0.995 m above the feet). People of other + // heights get a copy with the pelvis track scaled to their own hips (and their stride with it), so legs keep the + // authored bend instead of crouching (taller) or stretching off the ground (shorter). + var REF_PELVIS = 0.995, SETS = {}; + function clipSet(r) { + var key = r.toFixed(3); + if (SETS[key]) return SETS[key]; + if (Math.abs(r - 1) < 0.005) return (SETS[key] = { C: CLIPS, L: LOWER, r: 1 }); + var cs = { C: {}, L: {}, r: r }; + Object.keys(CLIPS).forEach(function (n) { + var c = CLIPS[n], tracks = c.tracks.map(function (t) { + if (t.name !== 'pelvis.position') return t; + var t2 = t.clone(); for (var i = 0; i < t2.values.length; i++) t2.values[i] *= r; return t2; + }); + cs.C[n] = new T.AnimationClip(c.name, c.duration, tracks); + cs.L[n] = new T.AnimationClip(c.name + '#L', c.duration, tracks.filter(function (t) { return !upperSet[t.name.split('.')[0]]; })); + }); + return (SETS[key] = cs); + } + function meshName(o) { 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 template(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 root = T.SkeletonUtils.clone(g.scene), drop = []; + root.traverse(function (o) { if (o.isBone && o.name === 'pelvis' && def.real) root.userData.pelvisR = o.position.length() / REF_PELVIS; }); + root.traverse(function (o) { if (o.isMesh && !keep[meshName(o)]) drop.push(o); }); + drop.forEach(function (o) { o.parent.remove(o); }); + root.traverse(function (o) { + if (!o.isMesh) return; + o.castShadow = true; o.receiveShadow = true; o.frustumCulled = true; + o.geometry.boundingSphere = new T.Sphere(new T.Vector3(0, 0.9, 0), 1.5); + o.userData.lod = def.lod.indexOf(meshName(o)) + 1; + o.userData.part = /Hair/.test(o.name) ? 'hair' : /Eye/.test(o.name) ? 'eye' : 'body'; + if (o.userData.part === 'body' && o.isSkinnedMesh && !def.real) o.geometry = bodyGeo(o, def); + }); + return root; + } + // Per body mesh: an 'aSkin' attribute (1 on the head and hands, from the bone weights) so the recolour shader keeps + // skin and recolours everything else, and the military headgear removed (helmet, beret, cap: vertices weighted to + // the head that sit outside the skull or above the hairline collapse to the head centre, so their triangles vanish; + // the hair mesh then shows). Results cached per source geometry. + var _bodyGeo = new Map(); + function bodyGeo(mesh, def) { + var src = mesh.geometry, key = src.uuid + (def.hat ? 'h' : ''); + if (_bodyGeo.has(key)) return _bodyGeo.get(key); + var g = src.clone(), sk = mesh.skeleton, bones = sk.bones; + var idx = {}; bones.forEach(function (b, i) { idx[b.name] = i; }); + var skinB = {}; bones.forEach(function (b, i) { if (/^(Head|neck_01|hand_[lr]|(thumb|index|middle|ring|pinky)_0\d_[lr])/.test(b.name)) skinB[i] = 1; }); + var SI = g.attributes.skinIndex, SW = g.attributes.skinWeight, P = g.attributes.position, n = P.count; + var skin = new Float32Array(n); + var headI = idx.Head, hp = new T.Vector3().setFromMatrixPosition(new T.Matrix4().copy(sk.boneInverses[headI]).invert()); + var v = new T.Vector3(), inv = new T.Matrix4().copy(mesh.bindMatrix).invert(), removed = 0; + // measured on these meshes (head-bone origin, y up, z forward): the face reaches r 0.14 at z > 0.07, the hair + // r 0.144 up to y 0.12; helmets and caps stand outside that (r up to 0.166, y up to 0.24) + var centre = new T.Vector3(hp.x, hp.y + 0.05, hp.z - 0.01).applyMatrix4(inv); + for (var i = 0; i < n; i++) { + var hw = 0, sw = 0; + for (var k = 0; k < 4; k++) { var bi = SI.getComponent(i, k), w = SW.getComponent(i, k); if (skinB[bi]) sw += w; if (bi === headI) hw += w; } + skin[i] = sw > 0.5 ? 1 : 0; + if (!def.hat && hw > 0.5) { + v.fromBufferAttribute(P, i).applyMatrix4(mesh.bindMatrix).sub(hp); + var r = Math.hypot(v.x, v.z); + if (v.y > 0.125 || (r > 0.139 && v.z < 0.07 && v.y > -0.06) || (v.y > 0.06 && r > 0.112 && v.z < 0.075) || (v.y > -0.03 && r > 0.117 && v.z < 0.06)) { P.setXYZ(i, centre.x, centre.y, centre.z); removed++; } + } + } + g.setAttribute('aSkin', new T.BufferAttribute(skin, 1)); + g.userData.removed = removed; + _bodyGeo.set(key, g); + return g; + } + + // ------------------------------------------------------------------ cloth recolour shader + // Texels that look like skin (warm: red over green over blue, fairly saturated) or very dark (eyes, boots) keep + // their colour; the rest (uniform cloth, webbing) keeps its light and shade but takes the outfit's colour: the + // lighter half of the cloth takes uCloth, darker straps and gear take uCloth2. + function recolour(m, c1, c2) { + m.userData.cols = { uCloth: { value: RP.col(c1) }, uCloth2: { value: RP.col(c2) } }; + m.onBeforeCompile = function (sh) { + sh.uniforms.uCloth = m.userData.cols.uCloth; sh.uniforms.uCloth2 = m.userData.cols.uCloth2; + sh.vertexShader = 'attribute float aSkin; varying float vSkin;\n' + sh.vertexShader.replace('#include ', '#include \n vSkin = aSkin;'); + sh.fragmentShader = 'uniform vec3 uCloth; uniform vec3 uCloth2; varying float vSkin;\n' + sh.fragmentShader.replace('#include ', [ + '#include ', + '{ vec3 c = diffuseColor.rgb; float mx = max(c.r, max(c.g, c.b)), mn = min(c.r, min(c.g, c.b));', + ' float sat = (mx - mn) / max(mx, 1e-4);', + ' float skin = smoothstep(0.18, 0.32, (c.r - c.b) / max(c.r, 1e-4)) * smoothstep(0.08, 0.16, (c.r - c.g) / max(c.r, 1e-4)) * step(c.b, c.g) * smoothstep(0.03, 0.08, c.r);', + ' float l = dot(c, vec3(0.3, 0.59, 0.11));', + ' float gear = smoothstep(0.06, 0.025, l);', + ' vec3 cloth = mix(uCloth, uCloth2, gear) * clamp(l / 0.09, 0.35, 1.8);', + ' diffuseColor.rgb = mix(cloth, c, clamp(vSkin * (0.4 + skin), 0.0, 1.0)); }' + ].join('\n')); + }; + m.customProgramCacheKey = function () { return 'rp-cloth'; }; + } + + // Materials of the MakeHuman-built people: cloth keeps its maps (ORM: roughness in G); skin gets a soft wrap and + // a warm subsurface tint where light falls off, so faces do not look like painted plastic; eyes are glossy. + function realMat(m, o) { + m.metalness = 0; if (m.metalnessMap) m.metalnessMap = null; + if (/Skin/.test(m.name)) { + m.roughness = 1; + m.onBeforeCompile = function (sh) { + sh.fragmentShader = sh.fragmentShader.replace('#include ', [ + '#include ', + '{ float wrap = clamp(dot(normal, normalize(vec3(0.2, 1.0, 0.3))) * 0.5 + 0.5, 0.0, 1.0);', + ' reflectedLight.indirectDiffuse += diffuseColor.rgb * vec3(0.20, 0.06, 0.03) * (1.0 - wrap) * 0.6; }'].join('\n')); + }; + m.customProgramCacheKey = function () { return 'rp-skin'; }; + } else if (/Eye/.test(m.name)) { m.roughness = 0.08; } + else m.roughness = 1; + } + + // ------------------------------------------------------------------ helpers + var _q = new T.Quaternion(), _q2 = new T.Quaternion(), _v = new T.Vector3(), _v2 = new T.Vector3(), _m = new T.Matrix4(); + function worldQuat(o, out) { return o.getWorldQuaternion(out); } + function worldPos(o, out) { return o.getWorldPosition(out); } + // rotate a bone by a world-space rotation q (keeps its parent) + // (own scratch quaternions: callers pass the shared _q as q, which must not be overwritten here) + var _rw1 = new T.Quaternion(), _rw2 = new T.Quaternion(); + function rotWorld(b, q) { + var pq = worldQuat(b.parent, _rw2), bw = _rw1.copy(pq).multiply(b.quaternion); + bw.premultiply(q); + b.quaternion.copy(pq.invert().multiply(bw)); + b.updateMatrixWorld(true); + } + C.rotWorld = rotWorld; + // two-bone IK: put the end of a-b-c on target (world), pole hint (world dir) keeps the elbow/knee plane + var _a = new T.Vector3(), _b = new T.Vector3(), _c = new T.Vector3(), _t = new T.Vector3(); + function twoBone(A, Bn, Cn, target, w, pole) { + if (w <= 0) return; + worldPos(A, _a); worldPos(Bn, _b); worldPos(Cn, _c); + var la = _a.distanceTo(_b), lb = _b.distanceTo(_c); + _t.copy(target); + var d = M.clamp(_t.distanceTo(_a), Math.abs(la - lb) + 1e-3, la + lb - 1e-3); + // current and wanted angle at the middle joint + var cur = Math.acos(M.clamp(_v.subVectors(_a, _b).normalize().dot(_v2.subVectors(_c, _b).normalize()), -1, 1)); + var want = Math.acos(M.clamp((la * la + lb * lb - d * d) / (2 * la * lb), -1, 1)); + var axis = new T.Vector3().crossVectors(_v.subVectors(_b, _a), _v2.subVectors(_c, _b)); + if (axis.lengthSq() < 1e-8) axis.copy(pole || new T.Vector3(1, 0, 0)); axis.normalize(); + rotWorld(Bn, _q.setFromAxisAngle(axis, (cur - want) * w)); + // swing the root so the end points at the target + worldPos(Cn, _c); worldPos(A, _a); + var from = _v.subVectors(_c, _a).normalize(), to = _v2.subVectors(_t, _a).normalize(); + var q = new T.Quaternion().setFromUnitVectors(from, to); + if (w < 1) q.slerp(new T.Quaternion(), 1 - w); + rotWorld(A, q); + } + C.twoBone = twoBone; + + // ------------------------------------------------------------------ code-authored moves + // Keys: [time s, {bone: [[axis, angle], ...]}] with axes in the character's own frame: 'x' its left, 'y' up, + // 'z' forward. Angles are added on top of the animated pose and eased between keys. 'root' moves the whole body + // (y lift and z forward in metres via 'lift'/'push', pitch via axis x). Each move has a hit window [start, end] (s) + // that the combat code reads, and a recovery end. + var D = Math.PI / 180; + var MOVES = { + // swimming (looping): arms sweep out and back, legs kick; the body's forward tip comes from the move's pitch (0..1) + swim: { dur: 1.3, loop: true, hold: true, keys: [ + [0, { upperarm_l: [['x', -150 * D], ['z', 10 * D]], upperarm_r: [['x', -150 * D], ['z', -10 * D]], lowerarm_l: [['x', -10 * D]], lowerarm_r: [['x', -10 * D]], thigh_l: [['x', -15 * D]], thigh_r: [['x', -15 * D]], calf_l: [['x', 40 * D]], calf_r: [['x', 40 * D]] }], + [0.45, { upperarm_l: [['x', -95 * D], ['z', 65 * D]], upperarm_r: [['x', -95 * D], ['z', -65 * D]], lowerarm_l: [['x', -30 * D]], lowerarm_r: [['x', -30 * D]], thigh_l: [['x', -55 * D], ['z', 25 * D]], thigh_r: [['x', -55 * D], ['z', -25 * D]], calf_l: [['x', 95 * D]], calf_r: [['x', 95 * D]] }], + [0.8, { upperarm_l: [['x', -40 * D], ['z', 25 * D]], upperarm_r: [['x', -40 * D], ['z', -25 * D]], lowerarm_l: [['x', -110 * D]], lowerarm_r: [['x', -110 * D]], thigh_l: [['x', -5 * D]], thigh_r: [['x', -5 * D]], calf_l: [['x', 10 * D]], calf_r: [['x', 10 * D]] }], + [1.3, { upperarm_l: [['x', -150 * D], ['z', 10 * D]], upperarm_r: [['x', -150 * D], ['z', -10 * D]], lowerarm_l: [['x', -10 * D]], lowerarm_r: [['x', -10 * D]], thigh_l: [['x', -15 * D]], thigh_r: [['x', -15 * D]], calf_l: [['x', 40 * D]], calf_r: [['x', 40 * D]] }]] }, + // braking from a run: plant, lean back, settle + brake: { dur: 0.42, keys: [[0, {}], [0.12, { spine_01: [['x', -9 * D]], spine_02: [['x', -5 * D]], thigh_r: [['x', -22 * D]], calf_r: [['x', 12 * D]], thigh_l: [['x', 8 * D]], calf_l: [['x', 18 * D]], root: [['lift', -0.05]], upperarm_l: [['x', -14 * D]], upperarm_r: [['x', -14 * D]] }], [0.42, {}]] }, + jab: { dur: 0.42, hit: [0.1, 0.18], keys: [ + [0, {}], + [0.08, { spine_02: [['y', 12 * D]], upperarm_r: [['x', 10 * D]] }], + [0.15, { spine_02: [['y', -22 * D]], spine_03: [['y', -10 * D]], clavicle_r: [['y', -12 * D]], upperarm_r: [['x', -75 * D], ['y', -20 * D]], lowerarm_r: [['x', -50 * D]] }], + [0.42, {}]] }, + cross: { dur: 0.5, hit: [0.14, 0.24], keys: [ + [0, {}], + [0.1, { spine_02: [['y', -16 * D]], upperarm_l: [['x', 10 * D]] }], + [0.2, { spine_01: [['y', 14 * D]], spine_02: [['y', 24 * D]], clavicle_l: [['y', 12 * D]], upperarm_l: [['x', -80 * D], ['y', 20 * D]], lowerarm_l: [['x', -45 * D]] }], + [0.5, {}]] }, + hook: { dur: 0.6, hit: [0.2, 0.3], keys: [ + [0, {}], + [0.14, { spine_01: [['y', 18 * D]], spine_02: [['y', 22 * D]], upperarm_r: [['z', 30 * D]] }], + [0.26, { spine_01: [['y', -20 * D]], spine_02: [['y', -32 * D]], upperarm_r: [['x', -60 * D], ['z', -70 * D]], lowerarm_r: [['y', 70 * D]] }], + [0.6, {}]] }, + uppercut: { dur: 0.62, hit: [0.22, 0.32], keys: [ + [0, {}], + [0.16, { spine_01: [['x', 14 * D]], spine_02: [['y', 14 * D]], upperarm_r: [['x', 30 * D]], root: [['lift', -0.12]] }], + [0.28, { spine_01: [['x', -10 * D]], spine_02: [['y', -20 * D]], upperarm_r: [['x', -110 * D]], lowerarm_r: [['x', -80 * D]], root: [['lift', 0.03]] }], + [0.62, {}]] }, + kick: { dur: 0.72, hit: [0.26, 0.38], keys: [ + [0, {}], + [0.16, { thigh_r: [['x', -55 * D]], calf_r: [['x', 70 * D]], spine_01: [['x', -8 * D]] }], + [0.3, { thigh_r: [['x', -85 * D]], calf_r: [['x', 5 * D]], spine_01: [['x', -18 * D]], spine_02: [['x', -8 * D]], upperarm_l: [['z', 25 * D]] }], + [0.48, { thigh_r: [['x', -40 * D]], calf_r: [['x', 60 * D]] }], + [0.72, {}]] }, + runPunch: { dur: 0.55, hit: [0.14, 0.26], push: 1.2, keys: [ + [0, {}], + [0.1, { spine_02: [['y', 18 * D], ['x', 10 * D]], upperarm_r: [['x', 30 * D]] }], + [0.22, { spine_01: [['x', 12 * D]], spine_02: [['y', -30 * D]], upperarm_r: [['x', -90 * D], ['y', -15 * D]], lowerarm_r: [['x', -20 * D]] }], + [0.55, {}]] }, + stomp: { dur: 0.7, hit: [0.3, 0.4], keys: [ + [0, {}], + [0.2, { thigh_r: [['x', -70 * D]], calf_r: [['x', 80 * D]], spine_01: [['x', 15 * D]] }], + [0.34, { thigh_r: [['x', -20 * D]], calf_r: [['x', 20 * D]], spine_01: [['x', 25 * D]], root: [['lift', -0.1]] }], + [0.7, {}]] }, + gunWhip: { dur: 0.6, hit: [0.2, 0.3], keys: [ + [0, {}], + [0.14, { spine_02: [['y', 20 * D]], upperarm_r: [['x', -80 * D], ['z', 40 * D]], lowerarm_r: [['x', -40 * D]] }], + [0.26, { spine_02: [['y', -30 * D]], upperarm_r: [['x', -60 * D], ['z', -40 * D]], lowerarm_r: [['x', -10 * D]] }], + [0.6, {}]] }, + // melee weapons: one-handed horizontal swing, overhead chop, two-handed swing (bat/club), stab + swing: { dur: 0.7, hit: [0.24, 0.36], keys: [ + [0, {}], + [0.18, { spine_01: [['y', 25 * D]], spine_02: [['y', 30 * D]], upperarm_r: [['x', -70 * D], ['z', 60 * D]], lowerarm_r: [['x', -60 * D]] }], + [0.32, { spine_01: [['y', -25 * D]], spine_02: [['y', -35 * D]], upperarm_r: [['x', -80 * D], ['z', -50 * D]], lowerarm_r: [['x', -5 * D]] }], + [0.7, {}]] }, + chop: { dur: 0.75, hit: [0.3, 0.4], keys: [ + [0, {}], + [0.22, { spine_01: [['x', -8 * D]], upperarm_r: [['x', -150 * D]], lowerarm_r: [['x', -70 * D]] }], + [0.36, { spine_01: [['x', 18 * D]], spine_02: [['x', 10 * D]], upperarm_r: [['x', -50 * D]], lowerarm_r: [['x', -5 * D]] }], + [0.75, {}]] }, + bigSwing: { dur: 0.95, hit: [0.36, 0.5], keys: [ + [0, {}], + [0.3, { spine_01: [['y', 40 * D]], spine_02: [['y', 35 * D]], upperarm_r: [['x', -90 * D], ['z', 70 * D]], upperarm_l: [['x', -60 * D], ['z', -20 * D]], lowerarm_r: [['x', -70 * D]], lowerarm_l: [['x', -60 * D]] }], + [0.46, { spine_01: [['y', -35 * D]], spine_02: [['y', -40 * D]], upperarm_r: [['x', -85 * D], ['z', -50 * D]], upperarm_l: [['x', -80 * D], ['z', -40 * D]], lowerarm_r: [['x', -10 * D]], lowerarm_l: [['x', -30 * D]] }], + [0.95, {}]] }, + stab: { dur: 0.48, hit: [0.14, 0.22], keys: [ + [0, {}], + [0.08, { upperarm_r: [['x', 20 * D]], lowerarm_r: [['x', -90 * D]] }], + [0.18, { spine_02: [['y', -18 * D]], upperarm_r: [['x', -70 * D]], lowerarm_r: [['x', -15 * D]] }], + [0.48, {}]] }, + // movement moves + dodge: { dur: 0.42, keys: [ + [0, {}], [0.1, { spine_01: [['x', 14 * D]], spine_02: [['x', 10 * D]], root: [['lift', -0.18]] }], + [0.28, { spine_01: [['x', 10 * D]], root: [['lift', -0.12]] }], [0.42, {}]] }, + roll: { dur: 0.62, keys: [ + [0, {}], [0.08, { root: [['lift', -0.35], ['x', 30 * D]], spine_01: [['x', 30 * D]], spine_02: [['x', 25 * D]], thigh_l: [['x', -70 * D]], thigh_r: [['x', -70 * D]], calf_l: [['x', 100 * D]], calf_r: [['x', 100 * D]] }], + [0.32, { root: [['lift', -0.55], ['x', 200 * D]], spine_01: [['x', 35 * D]], spine_02: [['x', 30 * D]], Head: [['x', 30 * D]], thigh_l: [['x', -110 * D]], thigh_r: [['x', -110 * D]], calf_l: [['x', 130 * D]], calf_r: [['x', 130 * D]] }], + [0.5, { root: [['lift', -0.35], ['x', 360 * D]], spine_01: [['x', 20 * D]], thigh_l: [['x', -60 * D]], thigh_r: [['x', -50 * D]], calf_l: [['x', 90 * D]], calf_r: [['x', 70 * D]] }], + [0.62, { root: [['x', 360 * D]] }]], spinRoot: true }, + jump: { dur: 0.5, keys: [[0, {}], [0.12, { thigh_l: [['x', -40 * D]], calf_l: [['x', 60 * D]], thigh_r: [['x', 10 * D]], calf_r: [['x', 30 * D]], upperarm_l: [['x', -30 * D]], upperarm_r: [['x', 20 * D]] }], [0.5, { thigh_l: [['x', -30 * D]], calf_l: [['x', 50 * D]], thigh_r: [['x', -10 * D]], calf_r: [['x', 40 * D]] }]], hold: true }, + land: { dur: 0.32, keys: [[0, { root: [['lift', -0.22]], spine_01: [['x', 12 * D]], thigh_l: [['x', -35 * D]], thigh_r: [['x', -35 * D]], calf_l: [['x', 60 * D]], calf_r: [['x', 60 * D]] }], [0.32, {}]] }, + hardLand: { dur: 0.7, keys: [[0, { root: [['lift', -0.5]], spine_01: [['x', 30 * D]], spine_02: [['x', 15 * D]], thigh_l: [['x', -80 * D]], thigh_r: [['x', -80 * D]], calf_l: [['x', 120 * D]], calf_r: [['x', 120 * D]] }], [0.35, { root: [['lift', -0.4]], spine_01: [['x', 22 * D]], thigh_l: [['x', -60 * D]], thigh_r: [['x', -60 * D]], calf_l: [['x', 95 * D]], calf_r: [['x', 95 * D]] }], [0.7, {}]] }, + climb: { dur: 0.95, keys: [ + [0, { upperarm_l: [['x', -160 * D]], upperarm_r: [['x', -160 * D]], root: [['lift', -1.2]] }], + [0.35, { upperarm_l: [['x', -120 * D]], upperarm_r: [['x', -120 * D]], lowerarm_l: [['x', -60 * D]], lowerarm_r: [['x', -60 * D]], thigh_l: [['x', -90 * D]], calf_l: [['x', 100 * D]], spine_01: [['x', 25 * D]], root: [['lift', -0.6]] }], + [0.7, { upperarm_l: [['x', -30 * D]], upperarm_r: [['x', -30 * D]], thigh_l: [['x', -70 * D]], calf_l: [['x', 90 * D]], spine_01: [['x', 30 * D]], root: [['lift', -0.2]] }], + [0.95, {}]] }, + getUp: { dur: 1.1, keys: [ + [0, { root: [['lift', -0.85], ['x', 70 * D]], spine_01: [['x', 30 * D]], thigh_l: [['x', -100 * D]], thigh_r: [['x', -60 * D]], calf_l: [['x', 120 * D]], calf_r: [['x', 100 * D]] }], + [0.5, { root: [['lift', -0.5], ['x', 25 * D]], spine_01: [['x', 25 * D]], thigh_l: [['x', -80 * D]], calf_l: [['x', 100 * D]], thigh_r: [['x', -20 * D]], calf_r: [['x', 50 * D]] }], + [1.1, {}]] }, + // pistol from the shoulder holster under the jacket: right hand across to the left side of the chest and out + drawChest: { dur: 0.45, keys: [[0, { upperarm_r: [['x', -25 * D], ['y', 55 * D]], lowerarm_r: [['x', -115 * D]], hand_r: [['y', 20 * D]], spine_02: [['y', 8 * D]] }], + [0.18, { upperarm_r: [['x', -35 * D], ['y', 40 * D]], lowerarm_r: [['x', -95 * D]] }], [0.45, {}]] }, + holsterChest: { dur: 0.4, keys: [[0, {}], [0.22, { upperarm_r: [['x', -25 * D], ['y', 55 * D]], lowerarm_r: [['x', -115 * D]], hand_r: [['y', 20 * D]], spine_02: [['y', 8 * D]] }], + [0.4, { upperarm_r: [['x', -25 * D], ['y', 50 * D]], lowerarm_r: [['x', -110 * D]] }]] }, + // long gun from the sling on the back: reach over the right shoulder, pull it round + drawBack: { dur: 0.55, keys: [[0, { upperarm_r: [['x', -150 * D], ['z', 20 * D]], lowerarm_r: [['x', -110 * D]], spine_02: [['y', -12 * D]] }], + [0.25, { upperarm_r: [['x', -90 * D]], lowerarm_r: [['x', -70 * D]] }], [0.55, {}]] }, + holsterBack: { dur: 0.45, keys: [[0, {}], [0.25, { upperarm_r: [['x', -150 * D], ['z', 20 * D]], lowerarm_r: [['x', -110 * D]], spine_02: [['y', -12 * D]] }], + [0.45, { upperarm_r: [['x', -140 * D], ['z', 15 * D]], lowerarm_r: [['x', -100 * D]] }]] }, + draw: { dur: 0.42, keys: [[0, { upperarm_r: [['x', 30 * D], ['z', 20 * D]], lowerarm_r: [['x', -80 * D]] }], [0.2, { upperarm_r: [['x', 20 * D]], lowerarm_r: [['x', -60 * D]] }], [0.42, {}]] }, + holster: { dur: 0.38, keys: [[0, {}], [0.2, { upperarm_r: [['x', 30 * D], ['z', 20 * D]], lowerarm_r: [['x', -80 * D]] }], [0.38, { upperarm_r: [['x', 25 * D], ['z', 15 * D]], lowerarm_r: [['x', -70 * D]] }]] }, + // crouch and grab something from the ground with the right hand, then stand + pickup: { dur: 0.75, keys: [[0, {}], + [0.28, { root: [['lift', -0.42]], spine_01: [['x', 32 * D]], spine_02: [['x', 18 * D]], thigh_l: [['x', -75 * D]], thigh_r: [['x', -40 * D]], calf_l: [['x', 95 * D]], calf_r: [['x', 70 * D]], upperarm_r: [['x', 35 * D]], lowerarm_r: [['x', -10 * D]] }], + [0.4, { root: [['lift', -0.42]], spine_01: [['x', 30 * D]], spine_02: [['x', 18 * D]], thigh_l: [['x', -75 * D]], thigh_r: [['x', -40 * D]], calf_l: [['x', 95 * D]], calf_r: [['x', 70 * D]], upperarm_r: [['x', 25 * D]], lowerarm_r: [['x', -35 * D]] }], + [0.75, {}]] }, + // let a weapon fall from the hand: arm out and down, a flick of the wrist + dropW: { dur: 0.45, keys: [[0, {}], [0.15, { upperarm_r: [['x', -35 * D]], lowerarm_r: [['x', -20 * D]], hand_r: [['x', 30 * D]] }], [0.45, {}]] }, + shellLoad: { dur: 0.48, keys: [[0, {}], [0.2, { upperarm_l: [['x', 20 * D]], lowerarm_l: [['x', -30 * D]] }], [0.34, { upperarm_l: [['x', -30 * D]], lowerarm_l: [['x', -70 * D]] }], [0.48, {}]] }, + // boxing guard: a bladed torso; the fists are held up by IK (holdReach below): lead hand out, rear hand by the chin + guard: { dur: 1, keys: [[0, { spine_02: [['y', -14 * D]], spine_01: [['x', 4 * D]] }], [1, { spine_02: [['y', -14 * D]], spine_01: [['x', 4 * D]] }]], hold: true, holdReach: [{ limb: 'arm_l', p: [0.1, 1.43, 0.36] }, { limb: 'arm_r', p: [-0.16, 1.36, 0.2] }] }, + stumble: { dur: 0.9, keys: [[0, {}], [0.2, { spine_01: [['x', -20 * D]], spine_02: [['x', -15 * D]], upperarm_l: [['z', 60 * D]], upperarm_r: [['z', -60 * D]] }], [0.5, { spine_01: [['x', 10 * D]], upperarm_l: [['z', 30 * D]], upperarm_r: [['z', -30 * D]] }], [0.9, {}]] }, + coverHigh: { dur: 1, keys: [[0, { spine_01: [['x', -4 * D]], Head: [['y', 10 * D]] }], [1, { spine_01: [['x', -4 * D]], Head: [['y', 10 * D]] }]], hold: true }, + blindFire: { dur: 1, keys: [[0, { upperarm_r: [['x', -150 * D]], lowerarm_r: [['x', -10 * D]], spine_01: [['x', 15 * D]], Head: [['x', 25 * D]] }], [1, { upperarm_r: [['x', -150 * D]], lowerarm_r: [['x', -10 * D]], spine_01: [['x', 15 * D]], Head: [['x', 25 * D]] }]], hold: true } + }; + // Strikes land by IK: where the fist (or foot, or the weapon hand) should be at contact, in the character's own + // frame for a 1.8 m person [x left, y up, z forward], and the time window [start, contact, end] over which the limb + // is pulled onto it and let go. With a target in reach (actor.strikeAt, a world point on the victim) the limb goes + // there instead, so punches connect with the head or chest in front of them. + var REACH = { + jab: { limb: 'arm_r', p: [-0.1, 1.44, 0.7], t: [0.05, 0.15, 0.32] }, cross: { limb: 'arm_l', p: [0.06, 1.44, 0.74], t: [0.09, 0.21, 0.4] }, + hook: { limb: 'arm_r', p: [0.1, 1.46, 0.52], t: [0.15, 0.27, 0.44] }, uppercut: { limb: 'arm_r', p: [-0.04, 1.52, 0.44], t: [0.17, 0.29, 0.46] }, + runPunch: { limb: 'arm_r', p: [-0.06, 1.42, 0.78], t: [0.08, 0.21, 0.42] }, gunWhip: { limb: 'arm_r', p: [0, 1.48, 0.6], t: [0.13, 0.26, 0.42] }, + stab: { limb: 'arm_r', p: [-0.06, 1.2, 0.72], t: [0.07, 0.18, 0.32] }, kick: { limb: 'leg_r', p: [-0.1, 0.98, 0.9], t: [0.18, 0.32, 0.5] }, + stomp: { limb: 'leg_r', p: [-0.12, 0.08, 0.45], t: [0.24, 0.35, 0.5] } + }; + Object.keys(REACH).forEach(function (k) { if (MOVES[k]) MOVES[k].reach = REACH[k]; }); + C.MOVES = MOVES; + + var AXES = { x: new T.Vector3(1, 0, 0), y: new T.Vector3(0, 1, 0), z: new T.Vector3(0, 0, 1) }; + + // ------------------------------------------------------------------ locomotion graph nodes + var DIRS = [['F', 0], ['FL', 45], ['L', 90], ['BL', 135], ['B', 180], ['BR', -135], ['R', -90], ['FR', -45]]; + var GAITS = ['walk', 'jog', 'crouch']; + function stride(name) { var m = META[name]; return m && m.stride ? m.stride : 1.6; } + + // ------------------------------------------------------------------ the actor + function Actor(kind, opts) { + opts = opts || {}; + var def = KINDS[kind]; + this.kind = kind; this.def = def; + this.root = new T.Group(); + var model = this.model = T.SkeletonUtils.clone(TEMPLATES[kind]); + this.cs = clipSet(TEMPLATES[kind].userData.pelvisR || 1); + this.root.add(model); + var bones = this.bones = {}, meshes = this.meshes = [], lods = this.lods = []; + var cols = opts.cols || [def.cloth, def.cloth2]; + var matCache = {}; + model.traverse(function (o) { + if (o.isBone) bones[o.name] = o; + if (o.isMesh) { + var key = o.material.name; + if (!matCache[key]) { + var m = o.material.clone(); + if (o.userData.part === 'hair') { + m.alphaTest = def.real ? 0.4 : 0.5; m.transparent = false; m.depthWrite = true; m.side = T.DoubleSide; + // dark hair at roughness 0.5 mirrored the blue sky and came out navy: a soft sheen, not a gloss + m.metalness = 0; m.roughness = 0.78; m.envMapIntensity = 0.3; + } + else if (def.real) realMat(m, o); + else if (o.userData.part === 'body') { m.metalness = 0; recolour(m, cols[0], cols[1]); } + if (m.map) m.map.anisotropy = 4; + matCache[key] = m; + } + o.material = matCache[key]; + (o.userData.lod ? lods : meshes).push(o); + } + }); + lods.forEach(function (m) { m.visible = false; }); + // the original hair was shaped to sit under the removed helmets: the code-made headwear replaces it + if (!def.real) meshes.forEach(function (m) { if (m.userData.part === 'hair') { m.visible = false; m.userData.off = true; } }); + this.lodLevel = 0; + this.height = def.h; + this.mixer = new T.AnimationMixer(model); + this.nodes = {}; this.upper = []; this.fulls = []; + this.phase = Math.random(); this.st = { speed: 0, dir: 0, strafe: 0, stealth: 0, sprint: 0, turnRate: 0, accel: 0 }; + this._strafeW = 0; this._stealthW = 0; this._sprintW = 0; this._lean = 0; this._pitchLean = 0; this._turnW = 0; this._idleT = 0; + this.aimP = 0; this.aimY = 0; this.aimPT = 0; this.aimYT = 0; this.aimW = 1; + this.moves = []; this.held = null; this.lhW = 0; this.lhWant = null; + this._flinch = new T.Vector3(); this._fl = 0; + this.visibleFlag = true; this.rag = null; + var self = this; + this.mixer.addEventListener('finished', function (e) { self._finished(e.action); }); + this.setUpper(null, 0); + this._snap = true; this.update(0); this._snap = false; + } + var AP = Actor.prototype; + AP.bone = function (n) { return this.bones[n]; }; + AP._node = function (name) { + var n = this.nodes[name]; + if (!n) { + if (!this.cs.C[name]) return null; + var full = this.mixer.clipAction(this.cs.C[name]), low = this.mixer.clipAction(this.cs.L[name]); + full.play(); low.play(); full.setEffectiveWeight(0); low.setEffectiveWeight(0); full.timeScale = 0; low.timeScale = 0; + n = this.nodes[name] = { name: name, full: full, low: low, w: 0, dur: this.cs.C[name].duration, stride: stride(name) * this.cs.r, t: Math.random() * this.cs.C[name].duration }; + } + return n; + }; + AP.drive = function (st) { for (var k in st) this.st[k] = st[k]; return this; }; + + // held upper-body pose (looping) + AP.setUpper = function (name, fade) { + if (this._upperName === name) return; + this._upperName = name; + fade = fade == null ? 0.2 : fade; + for (var i = 0; i < this.upper.length; i++) if (!this.upper[i].once) { this.upper[i].target = 0; this.upper[i].rate = 1 / Math.max(0.01, fade); } + if (name && UPPER[name]) { + var a = this.mixer.clipAction(UPPER[name]); a.reset(); a.setLoop(T.LoopRepeat); a.play(); a.setEffectiveWeight(0); + this.upper = this.upper.filter(function (u) { return u.action !== a; }); + this.upper.push({ name: name, action: a, w: 0, target: 1, rate: 1 / Math.max(0.01, fade), once: false }); + } + }; + AP.playUpper = function (name, o) { + o = o || {}; if (!UPPER[name]) return 0; + var a = this.mixer.clipAction(UPPER[name]); + a.reset(); a.setLoop(T.LoopOnce, 1); a.clampWhenFinished = true; a.timeScale = o.speed || 1; a.play(); + var fade = o.fade == null ? 0.08 : o.fade; + var e = null; + for (var i = 0; i < this.upper.length; i++) if (this.upper[i].action === a) e = this.upper[i]; + if (!e) { e = { name: name, action: a, w: 0, once: true }; this.upper.push(e); } + e.target = 1; e.rate = 1 / Math.max(0.01, fade); e.once = true; e.hold = !!o.hold; e.outFade = o.outFade || 0.18; + if (fade === 0) e.w = 1; + return this.cs.C[name].duration / (o.speed || 1); + }; + AP.stopUpper = function (name, fade) { + for (var i = 0; i < this.upper.length; i++) { var u = this.upper[i]; if (u.once && (!name || u.name === name)) { u.target = 0; u.rate = 1 / (fade || 0.15); } } + }; + AP.playFull = function (name, o) { + o = o || {}; if (!this.cs.C[name]) return 0; + var a = this.mixer.clipAction(this.cs.C[name]); + a.reset(); a.setLoop(o.loop ? T.LoopRepeat : T.LoopOnce, o.loop ? Infinity : 1); a.clampWhenFinished = true; a.timeScale = o.speed || 1; a.play(); + if (o.start) a.time = o.start; + var fade = o.fade == null ? 0.15 : o.fade; + this.fulls = this.fulls.filter(function (f) { return f.action !== a; }); + this.fulls.forEach(function (f) { f.target = 0; f.rate = 1 / Math.max(0.01, fade); }); + this.fulls.push({ name: name, action: a, w: fade === 0 ? 1 : 0, target: 1, rate: 1 / Math.max(0.01, fade), hold: !!o.hold, loop: !!o.loop, outFade: o.outFade || 0.25 }); + this.fullName = name; + return this.cs.C[name].duration / (o.speed || 1); + }; + AP.stopFull = function (fade) { this.fulls.forEach(function (f) { f.target = 0; f.rate = 1 / (fade || 0.25); }); this.fullName = null; }; + AP._finished = function (a) { + for (var i = 0; i < this.upper.length; i++) { var u = this.upper[i]; if (u.action === a && u.once && !u.hold) { u.target = 0; u.rate = 1 / u.outFade; } } + for (i = 0; i < this.fulls.length; i++) { var f = this.fulls[i]; if (f.action === a && !f.hold) { f.target = 0; f.rate = 1 / f.outFade; if (this.fullName === f.name) this.fullName = null; } } + if (this.onFinished) this.onFinished(a.getClip().name.replace(/#.$/, '')); + }; + AP.isFull = function (name) { return this.fullName === name; }; + + // code-authored moves: a.move('jab') -> {t, dur, def}; several can run (they add) + AP.move = function (name, o) { + var def = MOVES[name]; if (!def) return null; + o = o || {}; + if (!o.stack) this.moves = this.moves.filter(function (m) { return m.hold && m.name !== name; }); + var m = { name: name, def: def, t: 0, speed: o.speed || 1, side: o.side || 1, w: o.w == null ? 1 : o.w, hold: !!def.hold, fadeOut: 0 }; + this.moves.push(m); + return m; + }; + AP.endMove = function (name) { this.moves.forEach(function (m) { if (!name || m.name === name) m.fadeOut = 0.15; }); }; + AP.moveOf = function (name) { for (var i = 0; i < this.moves.length; i++) if (this.moves[i].name === name) return this.moves[i]; return null; }; + + AP.setAim = function (p, y) { this.aimPT = p; this.aimYT = y; }; + AP.flinch = function (fx, fz, k) { + // hit FROM direction (world): bend away from it + var yaw = this.root.rotation.y, c = Math.cos(yaw), s = Math.sin(yaw); + var lx = fx * c - fz * s, lz = fx * s + fz * c; + this._flinch.set(lx, 0, lz).normalize().multiplyScalar(Math.min(1, k)); this._fl = 1; + }; + AP.hold = function (obj) { + if (this.held && this.held.parent) this.held.parent.remove(this.held); + this.held = obj; + if (obj) { + if (obj.userData.far && RP.GunModels) RP.GunModels.setFar(obj, this.lodLevel || 0); + var id = obj.userData.id, d = RP.Weapons && RP.Weapons.DEFS[id]; + obj.userData.oneHandMelee = !!(d && (d.melee || d.cat === 'throw')); + this.root.add(obj); this._wAim = 0; + } + }; + // a long gun slung across the back on spine_03: butt low behind the right hip, muzzle over the left shoulder blade + var _slung = null; + AP.setBack = function (id) { + if (this._backId === id) return; + this._backId = id; + if (this._back) { this._back.parent && this._back.parent.remove(this._back); this._back = null; } + if (!id || !this.bones.spine_03) return; + var m = RP.Weapons.model(id); if (!m) return; + if (!_slung) { + var z = new T.Vector3(-0.36, 0.93, 0).normalize(), y = new T.Vector3(0, 0.05, -1).normalize(), x = new T.Vector3().crossVectors(y, z).normalize(); + y.crossVectors(z, x); _slung = new T.Matrix4().makeBasis(x, y, z); + } + // the carry pose in the character's frame, put on the bone through the bone's current world matrix + this.root.updateMatrixWorld(true); + var h = this.height || 1.8, want = _slung.clone().setPosition(0.03, h * 0.6, -0.19); + var local = new T.Matrix4().copy(this.bones.spine_03.matrixWorld).invert().multiply(this.root.matrixWorld).multiply(want); + local.decompose(m.position, m.quaternion, m.scale); + this.bones.spine_03.add(m); this._back = m; + if (m.userData.far && RP.GunModels) RP.GunModels.setFar(m, this.lodLevel || 0); + }; + AP.setVisible = function (v) { this.root.visible = v; this.visibleFlag = v; }; + + var _cam = new T.Vector3(); + AP.update = function (dt) { + if (this.rag) { this.rag.pose(this); return; } + var st = this.st, i, k; + // ---- LOD by camera distance + var cam = RP.R && RP.R.camera; + if (cam) { + var d = cam.position.distanceTo(this.root.position), L = RP.R.q ? RP.R.q.lod : C.lod; + var lvl = d < L[0] || this.isPlayer ? 0 : d < L[1] ? 1 : 2; + if (lvl !== this.lodLevel) { + this.lodLevel = lvl; + // far people are one mesh each (skin, clothes and a solid hair shape on one small atlas: see export_people.py) + this.meshes.forEach(function (m) { m.visible = !m.userData.off && lvl === 0; }); + this.lods.forEach(function (m) { m.visible = m.userData.lod === lvl; }); + if (this.held && this.held.userData.far) RP.GunModels.setFar(this.held, lvl); + if (this._back && this._back.userData.far) RP.GunModels.setFar(this._back, lvl); + } + // far actors update every other frame + this._skip = !this._skip && d > 45 && !this.isPlayer; + if (this._skip) { this._acc = (this._acc || 0) + dt; return; } + dt += this._acc || 0; this._acc = 0; + } + // ---- locomotion weights + this._strafeW = M.approach(this._strafeW, st.strafe, 5, dt); + this._stealthW = M.approach(this._stealthW, st.stealth, 4, dt); + this._sprintW = M.approach(this._sprintW, st.sprint, 3.5, dt); + var s = st.speed, TU = RP.TUNING; + var wIdle = 1 - M.smooth(s / 0.55), wWalk, wJog, wSprint = 0; + if (s <= TU.walk) { wWalk = 1 - wIdle; wJog = 0; } + else if (s <= TU.jog) { var t = (s - TU.walk) / (TU.jog - TU.walk); wWalk = 1 - t; wJog = t; } + else { var t2 = M.clamp((s - TU.jog) / (TU.sprint - TU.jog), 0, 1); wWalk = 0; wJog = 1 - t2; wSprint = t2; } + // turn steps in place + var turning = Math.abs(st.turnRate || 0); + this._turnW = M.approach(this._turnW, wIdle > 0.6 && turning > 0.8 ? 1 : 0, 6, dt); + // direction weights (8-way) for strafing + var dirW = [0, 0, 0, 0, 0, 0, 0, 0]; + var ang = M.wrap(st.dir || 0) * 180 / Math.PI; + for (i = 0; i < 8; i++) { + var dd = Math.abs(M.wrap((ang - DIRS[i][1]) * Math.PI / 180)) * 180 / Math.PI; + dirW[i] = Math.max(0, 1 - dd / 45); + } + var want = {}; + var stealth = this._stealthW, strafe = this._strafeW; + function add(n, w) { if (w > 0.0005) want[n] = (want[n] || 0) + w; } + // standing with a weapon up: the hold/aim clip's own legs (square to its upper body), not the relaxed idle's + // shifted hips, which twisted the body against the held pose + var idleN = this._upperName && /^(hold|aim)/.test(this._upperName) && this.cs.C[this._upperName] ? this._upperName : 'idle'; + this._idleN = idleN; + add(idleN, wIdle * (1 - stealth) * (1 - this._turnW)); + add('crouchIdle', wIdle * stealth * (1 - this._turnW)); + add('turnStep', wIdle * (1 - stealth) * this._turnW); add('crouchTurnStep', wIdle * stealth * this._turnW); + for (i = 0; i < 8; i++) { + var dw = dirW[i] * strafe + (i === 0 ? 1 - strafe : 0); + if (dw <= 0) continue; + var dn = DIRS[i][0]; + add('walk' + dn, wWalk * dw * (1 - stealth)); + add('jog' + dn, (wJog + (i === 0 ? 0 : wSprint)) * dw * (1 - stealth)); + add('crouch' + dn, (wWalk + wJog + wSprint) * dw * stealth); + } + add('sprintF', wSprint * (1 - strafe) * (1 - stealth)); + // phase: shared by every moving clip so feet stay in step while blending + var sw = 0, sStride = 0; + for (k in want) { var nd = this._node(k); if (!nd) continue; if (k !== 'idle' && k !== 'crouchIdle' && k !== idleN && !/turn/i.test(k)) { sw += want[k]; sStride += want[k] * nd.stride; } } + var strideL = sw > 0 ? sStride / sw : 1.6; + if (stealth > 0.5) strideL *= 0.85; + if (s > 0.05) this.phase = (this.phase + dt * s / Math.max(0.5, strideL)) % 1; + // full-body one-shots and the upper layer weights + var F = 0; + for (i = 0; i < this.fulls.length; i++) { var f = this.fulls[i]; f.w = M.approach(f.w, f.target, f.rate, dt); f.action.setEffectiveWeight(f.w); F = Math.max(F, f.w); } + this.fulls = this.fulls.filter(function (f) { if (f.w <= 0 && f.target === 0) { f.action.stop(); return false; } return true; }); + var U = 0; + for (i = 0; i < this.upper.length; i++) { var u = this.upper[i]; u.w = M.approach(u.w, u.target, u.rate, dt); U += u.w; } + var Uc = Math.min(1, U); + // a one-shot upper clip over a held pose: the one-shot wins in proportion to its weight + var onceW = 0; for (i = 0; i < this.upper.length; i++) if (this.upper[i].once) onceW = Math.max(onceW, this.upper[i].w); + for (i = 0; i < this.upper.length; i++) { u = this.upper[i]; u.action.setEffectiveWeight(u.once ? u.w * (1 - F) : u.w * (1 - onceW) * (1 - F)); } + this.upper = this.upper.filter(function (u) { if (u.w <= 0 && u.target === 0) { u.action.stop(); return false; } return true; }); + // apply graph node weights (full vs lower-only split by the upper layer weight) + for (k in this.nodes) { + var n = this.nodes[k], w = want[k] || 0; + n.w = this._snap ? w : M.approach(n.w, w, 8, dt); + var ew = n.w * (1 - F); + n.full.setEffectiveWeight(ew * (1 - Uc)); n.low.setEffectiveWeight(ew * Uc); + if (n.w > 0) { + if (k === 'idle' || k === 'crouchIdle' || k === this._idleN) n.t = (n.t + dt) % n.dur; + else if (/turn/i.test(k)) n.t = (n.t + dt * M.clamp(turning / 2, 0.6, 1.6)) % n.dur; + else n.t = this.phase * n.dur; + n.full.time = n.t; n.low.time = n.t; + } + } + // three.js only re-writes a bone when its mixed value changes; mark last frame's values unknown so the + // post-process edits below (aim, lean, moves, IK) never accumulate on a held pose + 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; } + // the graph actions' times are set by hand: update the mixer with dt for one-shots, then restore graph times + this.mixer.update(dt); + // after a ragdoll: blend from the lying pose back into animation + if (this._blendFrom) { + this._blendT -= dt; var bu = M.smooth(Math.max(0, this._blendT / this._blendMax)); + for (k in this._blendFrom) { var bb0 = this.bones[k]; if (bb0) bb0.quaternion.slerp(this._blendFrom[k], bu); } + if (this._blendPel) this.bones.pelvis.position.lerp(this._blendPel, bu); + if (this._blendT <= 0) this._blendFrom = null; + } + this.model.position.set(0, 0, 0); this.model.rotation.set(0, 0, 0); + this.root.updateMatrixWorld(true); + this._post(dt, F); + }; + + // lean, code moves, flinch, aim offset, left-hand IK + AP._post = function (dt, F) { + var b = this.bones, st = this.st; + var rq = this.root.quaternion, ax = {}; + for (var key in AXES) ax[key] = AXES[key].clone().applyQuaternion(rq); + // posture: the motion-capture loops lean far forward (jog ~25, sprint 35-80 degrees from hips to head); a + // GTA-style run is nearly upright. Measure the lean after the clips and pull it to a target by speed + // (walk 3, jog 9, sprint 15 degrees), and take out sideways roll, over spine_01 and spine_02. + if (b.Head && b.spine_02 && !this.rag) { + var pw = (1 - F) * M.clamp(st.speed / 1.2, 0, 1); + if (pw > 0.01) { + b.pelvis.getWorldPosition(_pv); b.Head.getWorldPosition(_hv); _hv.sub(_pv); + var len = _hv.length(); _hv.divideScalar(len); + var fz = _hv.dot(ax.z), tgt = (st.speed < 2 ? 3 : st.speed < 4.5 ? 3 + (st.speed - 2) / 2.5 * 6 : 9 + Math.min(1, (st.speed - 4.5) / 2) * 6) * Math.PI / 180; + _wv.copy(ax.y).multiplyScalar(Math.cos(tgt)).addScaledVector(ax.z, (fz >= 0 ? 1 : -1) * Math.sin(tgt)); + _pq.setFromUnitVectors(_hv, _wv); + _q.copy(_qI).slerp(_pq, 0.55 * pw); rotWorld(b.spine_01, _q); + _q.copy(_qI).slerp(_pq, 0.45 * pw); rotWorld(b.spine_02, _q); + } + } + // lean into turns (roll) and with acceleration (pitch), more when sprinting + var leanT = M.clamp(-(st.turnRate || 0) * st.speed * 0.035, -0.32, 0.32) * (1 - this._strafeW * 0.7); + this._lean = M.damp(this._lean, leanT, 6, dt); + var pitchT = M.clamp((st.accel || 0) * 0.025 + this._sprintW * 0.12, -0.18, 0.25); + this._pitchLean = M.damp(this._pitchLean, pitchT, 5, dt); + if (b.spine_01 && (Math.abs(this._lean) > 0.002 || Math.abs(this._pitchLean) > 0.002)) { + rotWorld(b.spine_01, _q.setFromAxisAngle(ax.z, this._lean * 0.6)); + rotWorld(b.spine_01, _q.setFromAxisAngle(ax.x, this._pitchLean)); + } + // code moves + var rootLift = 0, rootPitch = 0; + for (var i = 0; i < this.moves.length; i++) { + var m = this.moves[i], def = m.def; + m.t += dt * m.speed; + var w = m.w; + if (m.fadeOut > 0) { m.fadeT = (m.fadeT || 0) + dt; w *= Math.max(0, 1 - m.fadeT / m.fadeOut); if (m.fadeT >= m.fadeOut) { m.done = true; continue; } } + if (def.loop && m.t >= def.dur) m.t %= def.dur; + if (m.t >= def.dur && !m.hold) { m.done = true; continue; } + if (m.pitch) rootPitch += m.pitch * 0.7 * w; // swimming: the body tipped toward horizontal + var t = Math.min(m.t, def.dur), K = def.keys, a = K[0], c = K[K.length - 1]; + for (var j = 0; j < K.length - 1; j++) if (t >= K[j][0] && t <= K[j + 1][0]) { a = K[j]; c = K[j + 1]; break; } + var u = c[0] > a[0] ? M.smooth((t - a[0]) / (c[0] - a[0])) : 1; + var bonesSeen = {}; + for (var bn in a[1]) bonesSeen[bn] = 1; for (bn in c[1]) bonesSeen[bn] = 1; + for (bn in bonesSeen) { + var ra = a[1][bn] || [], rc = c[1][bn] || [], vals = {}; + ra.forEach(function (r) { vals[r[0]] = (vals[r[0]] || 0) + r[1] * (1 - u); }); + rc.forEach(function (r) { vals[r[0]] = (vals[r[0]] || 0) + r[1] * u; }); + if (bn === 'root') { rootLift += (vals.lift || 0) * w; rootPitch += (vals.x || 0) * w; continue; } + var bone = b[bn]; if (!bone) continue; + // mirror left/right for side -1 (moves authored for the right side) + for (var axn in vals) { + if (axn === 'lift') continue; + var angv = vals[axn] * w, axis = ax[axn]; + if (m.side < 0 && axn !== 'x') angv = -angv; + rotWorld(m.side < 0 ? (b[mirror(bn)] || bone) : bone, _q.setFromAxisAngle(axis, angv)); + } + } + } + // held stances (the boxing guard): hands kept at their points, elbows down + for (i = 0; i < this.moves.length; i++) { + var hm = this.moves[i], hr = hm.def.holdReach; if (!hr || hm.done) continue; + var hw2 = hm.w * (hm.fadeOut > 0 ? Math.max(0, 1 - (hm.fadeT || 0) / hm.fadeOut) : 1) * M.smooth(Math.min(1, hm.t / 0.18)); + for (var hi = 0; hi < hr.length; hi++) { + var s2 = hr[hi].limb.slice(-1), hs2 = this.height / 1.8; + _rlA.set(hr[hi].p[0], hr[hi].p[1] * hs2, hr[hi].p[2] * hs2).applyMatrix4(this.root.matrixWorld); + b['upperarm_' + s2].getWorldPosition(_lhP); _lhP.add(_lhD.set(s2 === 'r' ? -0.35 : 0.35, -1, 0.1).applyQuaternion(rq)); + ikPole(b['upperarm_' + s2], b['lowerarm_' + s2], b['hand_' + s2], _rlA, _lhP, hw2); + } + } + // strikes: pull the striking limb onto its contact point through the hit window + for (i = 0; i < this.moves.length; i++) { + var mv = this.moves[i], rc = mv.def.reach; if (!rc || mv.done) continue; + var tt = mv.t, rw = tt < rc.t[1] ? M.smooth(M.clamp((tt - rc.t[0]) / (rc.t[1] - rc.t[0]), 0, 1)) : 1 - M.smooth(M.clamp((tt - rc.t[1]) / (rc.t[2] - rc.t[1]), 0, 1)); + rw *= mv.w; if (rw < 0.01) continue; + var sd = rc.limb.slice(-1), flip = mv.side < 0; if (flip) sd = sd === 'r' ? 'l' : 'r'; + var hs = this.height / 1.8; + _rlA.set(rc.p[0] * (flip ? -1 : 1), rc.p[1] * hs, rc.p[2] * hs).applyMatrix4(this.root.matrixWorld); + if (this.strikeAt && rc.limb !== 'leg_r' || this.strikeAt && mv.name === 'kick') { + // a victim in reach: go for the point on them (kept within arm's length of the authored contact point) + _rlB.copy(this.strikeAt); if (mv.name === 'kick') _rlB.y -= 0.45 * hs; if (mv.name === 'stab') _rlB.y -= 0.25 * hs; + if (_rlB.distanceTo(_rlA) < 0.55) _rlA.copy(_rlB); + } + if (rc.limb.charAt(0) === 'a') { + b['upperarm_' + sd].getWorldPosition(_lhP); _lhP.add(_lhD.set(sd === 'r' ? -0.5 : 0.5, -0.8, -0.2).applyQuaternion(rq)); + ikPole(b['upperarm_' + sd], b['lowerarm_' + sd], b['hand_' + sd], _rlA, _lhP, rw); + } else { + b['thigh_' + sd].getWorldPosition(_lhP); _lhP.add(_lhD.set(0, 0.6, 1).applyQuaternion(rq)); + ikPole(b['thigh_' + sd], b['calf_' + sd], b['foot_' + sd], _rlA, _lhP, rw); + } + } + this.moves = this.moves.filter(function (m) { return !m.done; }); + this.model.position.y = rootLift; + if (rootPitch) { + // spin about the hips (roll): pivot at pelvis height + var pv = 0.55; + this.model.position.y += pv - pv * Math.cos(rootPitch) ; this.model.position.z = Math.sin(rootPitch) * pv * 0.4; + this.model.rotation.x = rootPitch; + } + if (rootLift || rootPitch) this.model.updateMatrixWorld(true); + // flinch + if (this._fl > 0) { + this._fl = Math.max(0, this._fl - dt * 5); + var k = Math.sin(this._fl * Math.PI) * 0.35, fl = this._flinch; + if (b.spine_02) { rotWorld(b.spine_02, _q.setFromAxisAngle(ax.x, -fl.z * k)); rotWorld(b.spine_02, _q.setFromAxisAngle(ax.z, fl.x * k)); } + if (b.Head) rotWorld(b.Head, _q.setFromAxisAngle(ax.x, -fl.z * k * 0.8)); + } + // aim offset + var kk = 1 - Math.exp(-dt * 16); + this.aimP += (this.aimPT - this.aimP) * kk; this.aimY += (this.aimYT - this.aimY) * kk; + var aw = this.aimW * (1 - F * 0.85); + if (aw > 0.01 && (Math.abs(this.aimP) > 1e-3 || Math.abs(this.aimY) > 1e-3)) { + var AY = [['spine_01', 0.18], ['spine_02', 0.22], ['spine_03', 0.3], ['neck_01', 0.12], ['Head', 0.18]]; + var AP2 = [['spine_01', 0.15], ['spine_02', 0.2], ['spine_03', 0.35], ['neck_01', 0.12], ['Head', 0.18]]; + for (i = 0; i < AY.length; i++) { var bb = b[AY[i][0]]; if (bb) rotWorld(bb, _q.setFromAxisAngle(ax.y, this.aimY * AY[i][1] * aw)); } + var l2 = ax.x.clone().applyAxisAngle(ax.y, this.aimY * 0.7 * aw); + for (i = 0; i < AP2.length; i++) { bb = b[AP2[i][0]]; if (bb) rotWorld(bb, _q.setFromAxisAngle(l2, -this.aimP * AP2[i][1] * aw)); } + } + // the held weapon: grip at the right hand, pointing along the aim (lowered when carried); melee weapons and + // throwables follow the forearm so swings carry them round + if (this.held) this._placeWeapon(dt); + // left hand onto the weapon's fore-grip (long guns whenever they are held up; pistols two-handed when aimed) + var held = this.held, want = 0, up = this._upperName || ''; + if (held && !held.userData.oneHandMelee) { + var aimingPose = /aim|fire|Cover|crouchAim/i.test(up) || /aim|fire/i.test(this.fullName || ''); + if (!held.userData.oneHand) want = /hold|aim|fire|Cover|crouchAim/i.test(up) || aimingPose ? 1 : 0; + else want = aimingPose ? 1 : 0; + if (this.lhWant != null) want = this.lhWant; + if (this.moves.length) want *= 0.25; + } + this.lhW = this._snap ? want : M.approach(this.lhW, want, 7, dt); + // reloading: the gun tips up and rolls a little in the right hand, and the left hand works the magazine by IK: + // to the magazine well, down to the belt with the old one (it drops), back up with a fresh one, home to the grip + var ru = this.reloadU == null ? -1 : this.reloadU, mag = held && held.userData.mag; + if (mag && (ru < 0 || !held)) { if (mag.userData.out) { mag.position.set(0, 0, 0); mag.visible = true; mag.userData.out = false; } } + if (ru >= 0 && held && !held.userData.oneHandMelee && b.upperarm_l) { + var bell = Math.sin(Math.min(1, ru / 0.9) * Math.PI); + rotWorld(b.hand_r, _q.setFromAxisAngle(_lhD.set(0, 0, 1).applyQuaternion(held.getWorldQuaternion(_wq)), -0.45 * bell)); + rotWorld(b.lowerarm_r, _q.setFromAxisAngle(ax.x, -0.3 * bell)); + held.updateMatrixWorld(true); + // points: the well (on the gun), the belt (on the body), home (fore-grip or pistol support) + var well = _rlA, belt = _rlB, home = _rlC, pist = held.userData.oneHand; + if (mag) { if (!mag.userData.c) { mag.userData.c = new T.Box3().setFromObject(mag).getCenter(new T.Vector3()); held.worldToLocal(mag.userData.c); mag.userData.c.y -= 0.03; } well.copy(mag.userData.c); } + else well.set(0, pist ? 0.03 : 0.02, pist ? 0.02 : 0.1); + well.applyMatrix4(held.matrixWorld); + belt.set(0.2, this.height * 0.56, 0.1).applyMatrix4(this.root.matrixWorld); + if (held.userData.gripL) held.userData.gripL.getWorldPosition(home); else home.set(0.034, -0.045, -0.01).applyMatrix4(held.matrixWorld); + var tp2 = _lhT, s1 = M.smooth(M.clamp(ru / 0.2, 0, 1)), s2 = M.smooth(M.clamp((ru - 0.22) / 0.2, 0, 1)), s3 = M.smooth(M.clamp((ru - 0.44) / 0.18, 0, 1)), s4 = M.smooth(M.clamp((ru - 0.7) / 0.25, 0, 1)); + tp2.copy(home).lerp(well, s1).lerp(belt, s2 * (1 - s3)).lerp(home, s4); + b.upperarm_l.getWorldPosition(_lhP); _lhP.add(_lhD.set(0.45, -0.9, -0.15).applyQuaternion(this.root.quaternion)); + ikPole(b.upperarm_l, b.lowerarm_l, b.hand_l, tp2, _lhP, 1); + this.lhW = 1; + if (mag) { + var inHand = ru > 0.2 && ru < 0.62; + if (inHand) { + if (!mag.userData.out) { mag.userData.out = true; if (RP.Items && RP.Items.debris && this.lodLevel === 0) RP.Items.debris(mag, well); } + mag.visible = ru > 0.42; // the fresh magazine appears at the belt + if (mag.visible) { _rlA.copy(tp2); held.worldToLocal(_rlA); mag.position.copy(_rlA).sub(mag.userData.c); } + } else if (mag.userData.out) { mag.userData.out = false; mag.visible = true; mag.position.set(0, 0, 0); } + } + } else + if (this.lhW > 0.02 && held && b.upperarm_l) { + held.updateMatrixWorld(true); + var tp = _lhT; + if (held.userData.gripL) held.userData.gripL.getWorldPosition(tp); + else tp.set(0.034, -0.045, -0.01).applyMatrix4(held.matrixWorld); // pistols: the support hand wraps the grip + // elbow pole: down and out to the left of the character, a little behind the hand + var rq2 = this.root.quaternion; + b.upperarm_l.getWorldPosition(_lhP); + _lhP.add(_lhD.set(0.45, -0.9, -0.15).applyQuaternion(rq2)); + ikPole(b.upperarm_l, b.lowerarm_l, b.hand_l, tp, _lhP, this.lhW); + } + this._feet(dt, F); + }; + // Feet on the real ground: each foot is dropped or raised to the surface under it (stairs, kerbs, slopes), the hips + // come down so the lower foot can reach, and each leg is re-solved with the knee kept pointing forward. Only for + // people near the camera who are standing or moving on the ground (not rolling, vaulting, falling or ragdolled). + var _fp = new T.Vector3(), _ft = new T.Vector3(), _fk = new T.Vector3(), _fg = {}; + AP._feet = function (dt, F) { + var b = this.bones; + if (!RP.W || !b.foot_l || this.noFootIK || this.lodLevel > 0 || F > 0.4 || this.airborne) { this._pelOff = 0; this._fd = null; return; } + for (var i = 0; i < this.moves.length; i++) if (this.moves[i].def.spinRoot || this.moves[i].name === 'climb') return; + var fd = this._fd || (this._fd = { l: 0, r: 0 }), ry = this.root.position.y, sides = ['l', 'r'], k = this._snap ? 1 : Math.min(1, dt * 16); + for (i = 0; i < 2; i++) { + var s = sides[i]; b['foot_' + s].getWorldPosition(_fp); + var g = RP.W.ground(_fp.x, _fp.z, ry + 0.55, 0.05, _fg).y; + var d = M.clamp(g - ry, -0.5, 0.5); + if (_fp.y - ry > 0.25) d *= 0.4; // a foot swinging high through the air mostly keeps its arc + fd[s] += (d - fd[s]) * k; + } + var po = Math.min(fd.l, fd.r, 0); + this._pelOff = po; + if (Math.abs(fd.l) < 0.004 && Math.abs(fd.r) < 0.004) return; + this.model.position.y += po; this.model.updateMatrixWorld(true); + for (i = 0; i < 2; i++) { + s = sides[i]; var lift = fd[s] - po; if (lift < 0.004) continue; + var foot = b['foot_' + s]; foot.getWorldPosition(_ft); foot.getWorldQuaternion(_wq); + _ft.y += lift; + b['thigh_' + s].getWorldPosition(_fk); _fk.add(_lhD.set(0, -0.3, 1).applyQuaternion(this.root.quaternion)); + ikPole(b['thigh_' + s], b['calf_' + s], foot, _ft, _fk, 1); + // keep the foot's own tilt + foot.parent.getWorldQuaternion(_rq); foot.quaternion.copy(_rq.invert().multiply(_wq)); foot.updateMatrixWorld(true); + } + }; + var _rq = new T.Quaternion(); + var _lhT = new T.Vector3(), _lhP = new T.Vector3(), _lhD = new T.Vector3(), _rlA = new T.Vector3(), _rlB = new T.Vector3(), _rlC = new T.Vector3(); + // Two-bone IK with a pole: the elbow (knee) is placed in the plane through the root, the target and the pole point, + // then the upper and lower bones are swung onto it (their twist is kept from the animation). + var _ia = new T.Vector3(), _ib = new T.Vector3(), _ic = new T.Vector3(), _it = new T.Vector3(), _ie = new T.Vector3(), _iu = new T.Vector3(), _iv = new T.Vector3(), _iq = new T.Quaternion(), _iq0 = new T.Quaternion(), _iq1 = new T.Quaternion(); + function ikPole(A, Bn, Cn, target, pole, w) { + if (w <= 0) return; + _iq0.copy(A.quaternion); _iq1.copy(Bn.quaternion); + worldPos(A, _ia); worldPos(Bn, _ib); worldPos(Cn, _ic); + var la = _ia.distanceTo(_ib), lb = _ib.distanceTo(_ic); + _it.subVectors(target, _ia); var d = _it.length(); if (d < 1e-4) return; + d = Math.min(d, (la + lb) * 0.999); _it.normalize(); + var x = (la * la - lb * lb + d * d) / (2 * d), h = Math.sqrt(Math.max(0, la * la - x * x)); + _iu.subVectors(pole, _ia); _iu.addScaledVector(_it, -_iu.dot(_it)); + if (_iu.lengthSq() < 1e-8) _iu.set(0, -1, 0); _iu.normalize(); + _ie.copy(_ia).addScaledVector(_it, x).addScaledVector(_iu, h); // wanted elbow + // swing the upper bone so its end lands on the elbow + _iv.subVectors(_ib, _ia).normalize(); _iu.subVectors(_ie, _ia).normalize(); + rotWorld(A, _iq.setFromUnitVectors(_iv, _iu)); + // swing the lower bone so the hand lands on the target + worldPos(Bn, _ib); worldPos(Cn, _ic); + _iv.subVectors(_ic, _ib).normalize(); _iu.subVectors(_ia.copy(_it).multiplyScalar(d).add(worldPos(A, _ie)), _ib).normalize(); + rotWorld(Bn, _iq.setFromUnitVectors(_iv, _iu)); + if (w < 1) { A.quaternion.copy(_iq0.slerp(A.quaternion, w)); Bn.quaternion.copy(_iq1.slerp(Bn.quaternion, w)); A.updateMatrixWorld(true); } + } + C.ikPole = ikPole; + // weapon_r's own frame (measured on the aim clips): X to the character's right, Y down, Z forward and raised by the + // grip's rake. A gun model (X its left, Y up, Z barrel) sits in it turned half round its X axis and tipped back by + // the rake: about 33 degrees for the long guns' clips, 21 for the pistol clips. + var _pv = new T.Vector3(), _hv = new T.Vector3(), _wv = new T.Vector3(), _pq = new T.Quaternion(); + var _qI = new T.Quaternion(), _wq = new T.Quaternion(), _wm = new T.Matrix4(), _wf = new T.Vector3(), _wu = new T.Vector3(), _wr = new T.Vector3(), _wh = new T.Vector3(), _we = new T.Vector3(); + var _gq = {}; + function gripQuat(deg) { + if (_gq[deg]) return _gq[deg]; + var a = deg * Math.PI / 180, s = Math.sin(a), c = Math.cos(a); + var m = new T.Matrix4().makeBasis(new T.Vector3(-1, 0, 0), new T.Vector3(0, -c, s), new T.Vector3(0, s, c)); + return (_gq[deg] = new T.Quaternion().setFromRotationMatrix(m)); + } + AP._placeWeapon = function (dt) { + var w = this.held, b = this.bones, rq = this.root.quaternion; + if (b.weapon_r && !w.userData.oneHandMelee) { + // guns ride the clips' weapon_r prop bone (barrel +Z, up +Y, origin at the right-hand grip), so the + // authored hold, aim, fire and reload poses carry them exactly as they were made + if (w.parent !== b.weapon_r) { b.weapon_r.add(w); w.position.set(0, 0, 0); w.quaternion.copy(gripQuat(w.userData.oneHand ? 21 : 33)); } + w.updateMatrixWorld(true); + // aimed: the wrist turns so the barrel lies exactly on the aim line (as in GTA, the gun points where the + // crosshair is), up to 50 degrees; clips that hold the gun a little off-line are corrected this way + this._wAim = this._snap ? (this.weaponAim || 0) : M.approach(this._wAim || 0, this.weaponAim || 0, 7, dt); + if (this._wAim > 0.01) { + var yaw = this.root.rotation.y + this.aimY, pitch = this.weaponPitch != null ? this.weaponPitch : this.aimP; + _wf.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)); + w.getWorldQuaternion(_wq); _wu.set(0, 0, 1).applyQuaternion(_wq); + var ang = _wu.angleTo(_wf); + if (ang > 1e-3) { + _wq.setFromUnitVectors(_wu, _wf); + var k = Math.min(1, 0.87 / ang) * this._wAim; + if (k < 1) _wq.slerp(_qI, 1 - k); + rotWorld(b.hand_r, _wq); + w.updateMatrixWorld(true); + } + } + return; + } + b.hand_r.getWorldPosition(_wh); + if (w.userData.oneHand && (w.userData.id === 'knife' || w.userData.id === 'bat' || w.userData.id === 'crowbar' || w.userData.id === 'hammer' || w.userData.id === 'club' || w.userData.id === 'machete' || w.userData.id === 'frag' || w.userData.id === 'sticky' || w.userData.id === 'smoke')) { + b.lowerarm_r.getWorldPosition(_we); + _wf.subVectors(_wh, _we).normalize(); + _wu.set(0, 1, 0); + _wf.addScaledVector(_wu, 0.9).normalize(); + } else { + this._wAim = M.approach(this._wAim || 0, this.weaponAim || 0, 6, dt); + var yaw = this.root.rotation.y + this.aimY * 0.6; + var pitch = M.lerp(w.userData.oneHand ? -1.1 : -0.55, (this.weaponPitch || 0), this._wAim); + _wf.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)); + if (!w.userData.oneHand) _wf.x += Math.cos(yaw) * 0.12 * (1 - this._wAim), _wf.z -= Math.sin(yaw) * 0.12 * (1 - this._wAim); // carried across the body + _wf.normalize(); + } + _wr.crossVectors(_wf, new T.Vector3(0, 1, 0)).normalize(); _wu.crossVectors(_wr, _wf).normalize(); + _wm.makeBasis(_wr.negate(), _wu, _wf); // +X = weapon left, +Y up, +Z barrel + _wq.setFromRotationMatrix(_wm); + w.quaternion.copy(rq).invert().multiply(_wq); + w.position.copy(this.root.worldToLocal(_wh.clone())); + w.updateMatrixWorld(true); + }; + function mirror(n) { return n.replace(/_r$/, '_X').replace(/_l$/, '_r').replace(/_X$/, '_l'); } + + // world-space points for gameplay + AP.head = function (out) { return worldPos(this.bones.Head, out || new T.Vector3()); }; + AP.chest = function (out) { return worldPos(this.bones.spine_03, out || new T.Vector3()); }; + AP.pelvis = function (out) { return worldPos(this.bones.pelvis, out || new T.Vector3()); }; + AP.dispose = function () { this.mixer.stopAllAction(); if (this.root.parent) this.root.parent.remove(this.root); }; + + // ------------------------------------------------------------------ headwear made in code (replaces the removed military hats) + var HWG = null; + function hwGeos() { + if (HWG) return HWG; + HWG = {}; + // short hair: a skull cap that follows the head (front hairline lifted) + var hair = new T.SphereGeometry(1, 20, 12, 0, Math.PI * 2, 0, Math.PI * 0.5); + var p = hair.attributes.position; + for (var i = 0; i < p.count; i++) { var x = p.getX(i), y = p.getY(i), z = p.getZ(i); if (z > 0.3) p.setY(i, y + (z - 0.3) * 0.35); } + hair.scale(0.096, 0.085, 0.108); hair.computeVertexNormals(); HWG.hair = hair; + var beanie = new T.SphereGeometry(1, 20, 12, 0, Math.PI * 2, 0, Math.PI * 0.55); beanie.scale(0.112, 0.125, 0.122); HWG.beanie = beanie; + var cap = new T.SphereGeometry(1, 20, 12, 0, Math.PI * 2, 0, Math.PI * 0.52); cap.scale(0.11, 0.1, 0.12); + var brim = new T.CylinderGeometry(0.09, 0.09, 0.008, 16, 1, false, -Math.PI / 2, Math.PI); brim.scale(1, 1, 0.9); brim.translate(0, 0.005, 0.07); + HWG.cap = B2([cap, brim]); + var crown = new T.CylinderGeometry(0.095, 0.11, 0.1, 18); crown.translate(0, 0.07, 0); + var fb = new T.CylinderGeometry(0.19, 0.19, 0.008, 22); fb.translate(0, 0.02, 0); + HWG.fedora = B2([crown, fb]); + var gl = new T.BoxGeometry(0.13, 0.035, 0.01); gl.translate(0, 0, 0); HWG.glasses = gl; + return HWG; + } + function B2(list) { return RP.B && RP.B.mergeGeos ? RP.B.mergeGeos(list.map(function (g) { return g.index ? g : g; })) : list[0]; } + var HW_MAT = {}; + function hwMat(hex, rough) { var k = hex + rough; return HW_MAT[k] || (HW_MAT[k] = new T.MeshStandardMaterial({ color: RP.col(hex), roughness: rough })); } + function addHeadwear(a, def, opts) { + var hb = a.bones.Head; if (!hb) return; + var G = hwGeos(), kind = opts.hw || (def.hw && def.hw[0]), hex = opts.hwCol || (def.hw && def.hw[1]); + // place in the idle pose: level with the character's root, offset in the root's frame, then parented to the head + a.root.updateMatrixWorld(true); + var hq = hb.getWorldQuaternion(new T.Quaternion()), rq = a.root.getWorldQuaternion(new T.Quaternion()), hpw = hb.getWorldPosition(new T.Vector3()); + var iq = hq.clone().invert(); + function put(geo, mat, off) { + var m = new T.Mesh(geo, mat); m.castShadow = true; + m.quaternion.copy(iq).multiply(rq); + var wpos = new T.Vector3(off[0], off[1], off[2]).applyQuaternion(rq).add(hpw); + m.position.copy(hb.worldToLocal(wpos)); + hb.add(m); return m; + } + var y = kind === 'fedora' ? 0.13 : kind === 'beanie' ? 0.045 : 0.05; + if (def.real) y += 0.035; + if (kind && !(def.real && kind === 'hair')) a.hat = put(G[kind] || G.hair, hwMat(hex, kind === 'hair' ? 0.75 : 0.85), [0, y, -0.012]); + if (def.glasses || opts.glasses) put(G.glasses, hwMat('#0b0b0c', 0.15), def.real ? [0, 0.075, 0.105] : [0, 0.045, 0.118]); + } + + C.spawn = function (kind, opts) { + opts = opts || {}; + if (kind === 'guest') { + kind = ['civm1', 'civm2', 'civf1', 'civf2'][Math.floor(Math.random() * 4)]; + if (/civm/.test(kind) && Math.random() < 0.25) { opts.hw = 'fedora'; opts.hwCol = ['#d8c79a', '#efe6d0', '#3b3b3b'][Math.floor(Math.random() * 3)]; } + opts.glasses = Math.random() < 0.3; + } + if (!TEMPLATES[kind]) kind = 'sentry'; + var a = new Actor(kind, opts); + addHeadwear(a, KINDS[kind], opts); + return a; + }; + C.KINDS = KINDS; C._gltf = gltf; +})(); diff --git a/e63334287a3deaa3/blacktie/js/combat.js b/e63334287a3deaa3/blacktie/js/combat.js new file mode 100644 index 00000000..a472ec2f --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/combat.js @@ -0,0 +1,233 @@ +/* + * Combat (RP.Combat): shared by the player and the guards. + * - Entities (player, guards, guests) register in RP.G.ents: { actor, pos (feet), team ('player'|'guard'|'civ'), + * alive, radius, takeDamage(amount, info) }. Hit tests use capsules built from the skeleton each shot: + * head (x3 damage), torso (x1), arms and legs (x0.65). Guests can't be hurt (they flee instead). + * - Bullets are hit-scan with a tracer; damage falls off with range per weapon. Shotguns fire pellets. + * - Grenades, rockets, launcher grenades and sticky charges are simple projectiles stepped in the fixed update. + * - Every shot, explosion and fight makes a noise event the AI can hear (RP.Combat.noises). + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W; + var C = RP.Combat = { noises: [], projs: [] }; + var D2R = Math.PI / 180; + + // ------------------------------------------------------------------ hit capsules + var SEGS = [ // region, bone a, bone b, radius, damage multiplier + ['head', 'Head', null, 0.13, 3], ['torso', 'pelvis', 'spine_03', 0.2, 1], ['torso', 'spine_03', 'neck_01', 0.17, 1], + ['arm', 'upperarm_l', 'lowerarm_l', 0.065, 0.65], ['arm', 'lowerarm_l', 'hand_l', 0.055, 0.65], ['arm', 'upperarm_r', 'lowerarm_r', 0.065, 0.65], ['arm', 'lowerarm_r', 'hand_r', 0.055, 0.65], + ['leg', 'thigh_l', 'calf_l', 0.095, 0.65], ['leg', 'calf_l', 'foot_l', 0.075, 0.65], ['leg', 'thigh_r', 'calf_r', 0.095, 0.65], ['leg', 'calf_r', 'foot_r', 0.075, 0.65] + ]; + var _a = new T.Vector3(), _b = new T.Vector3(), _o = new T.Vector3(), _d = new T.Vector3(); + // ray vs capsule (segment a-b, radius r): returns t or -1 + function rayCapsule(o, d, a, b, r) { + var ba = b.clone().sub(a), oa = o.clone().sub(a); + var baba = ba.dot(ba), bard = ba.dot(d), baoa = ba.dot(oa), rdoa = d.dot(oa), oaoa = oa.dot(oa); + var A = baba - bard * bard, B = baba * rdoa - baoa * bard, Cc = baba * oaoa - baoa * baoa - r * r * baba, h = B * B - A * Cc; + if (h >= 0 && A > 1e-9) { + var t = (-B - Math.sqrt(h)) / A, y = baoa + t * bard; + if (y > 0 && y < baba && t > 0) return t; + var oc = y <= 0 ? oa : o.clone().sub(b); + B = d.dot(oc); Cc = oc.dot(oc) - r * r; h = B * B - Cc; + if (h > 0) { t = -B - Math.sqrt(h); if (t > 0) return t; } + } + return -1; + } + function raySphere(o, d, c, r) { + var oc = o.clone().sub(c), b = oc.dot(d), cc = oc.dot(oc) - r * r, h = b * b - cc; + if (h < 0) return -1; var t = -b - Math.sqrt(h); return t > 0 ? t : -1; + } + // nearest entity hit along a ray + C.hitEnts = function (o, d, maxT, ignore) { + var best = null, bt = maxT, ents = RP.G.ents; + for (var i = 0; i < ents.length; i++) { + var e = ents[i]; if (e === ignore || e.ghost) continue; + if (e.hitSphere) { // big simple targets (the helicopter) + if (!e.alive) continue; + var ts = raySphere(o, d, e.hitSphere.c, e.hitSphere.r); if (ts > 0 && ts < bt) { bt = ts; best = { ent: e, t: ts, region: 'body', mult: 1 }; } + continue; + } + if (!e.actor) continue; + // broad phase: distance from the ray to the body's centre + _o.copy(e.pos); _o.y += 1; + var t0 = _o.clone().sub(o).dot(d); if (t0 < -1 || t0 > bt + 1.5) continue; + var perp = o.clone().addScaledVector(d, t0).distanceTo(_o); if (perp > 1.4) continue; + var bn = e.actor.bones; + for (var s = 0; s < SEGS.length; s++) { + var S = SEGS[s], A = bn[S[1]]; if (!A) continue; + A.getWorldPosition(_a); + var t; + if (!S[2]) { _a.addScaledVector(new T.Vector3(0, 1, 0), 0.09); t = raySphere(o, d, _a, S[3]); } + else { bn[S[2]].getWorldPosition(_b); t = rayCapsule(o, d, _a.clone(), _b.clone(), S[3]); } + if (t > 0 && t < bt) { bt = t; best = { ent: e, t: t, region: S[0], mult: S[4] }; } + } + } + if (best) best.point = o.clone().addScaledVector(d, best.t); + return best; + }; + + // ------------------------------------------------------------------ bullets + // C.fire(shooter, origin, dir (unit), def, opts) -> {point, ent?} ; opts.aimPoint: where the shooter's sight says + C.fire = function (shooter, origin, dir, def, opts) { + opts = opts || {}; + var pellets = def.pellets || 1, last = null; + for (var p = 0; p < pellets; p++) { + var d = dir.clone(); + if (pellets > 1 || opts.spread) { + var sp = (opts.spread || 0) * D2R, a = Math.random() * 6.283, r = Math.sqrt(Math.random()) * Math.tan(sp); + var up = Math.abs(d.y) < 0.95 ? new T.Vector3(0, 1, 0) : new T.Vector3(1, 0, 0); + var u = new T.Vector3().crossVectors(d, up).normalize(), v = new T.Vector3().crossVectors(u, d); + d.addScaledVector(u, Math.cos(a) * r).addScaledVector(v, Math.sin(a) * r).normalize(); + } + var maxT = def.range ? def.range[1] * 2.2 : 300; + var wh = W.ray(origin.x, origin.y, origin.z, d.x, d.y, d.z, maxT); + var eh = C.hitEnts(origin, d, wh ? wh.t : maxT, shooter); + var end; + if (eh) { + end = eh.point; + var dist = eh.t, fall = def.range ? M.clamp((dist - def.range[0]) / Math.max(1, def.range[1] - def.range[0]), 0, 1) : 0; + var dmg = def.dmg * (1 - fall * (1 - (def.minFrac || 0.5))) * eh.mult * (opts.dmgMul || 1); + eh.ent.takeDamage(dmg, { from: shooter, dir: d, point: end, region: eh.region, weapon: def, bullet: true, force: (def.pellets ? 1.4 : def.dmg > 80 ? 4 : 1.8) }); + RP.FX.impact({ x: end.x, y: end.y, z: end.z, nx: -d.x, ny: -d.y, nz: -d.z, mat: eh.ent.hitMat || 'flesh' }, d.x, d.y, d.z); + last = { point: end, ent: eh.ent }; + } else if (wh) { + end = new T.Vector3(wh.x, wh.y, wh.z); + RP.FX.impact(wh, d.x, d.y, d.z, { heavy: def.dmg > 50 }); + if (wh.box && wh.box.onHit) wh.box.onHit(wh, d, def); + last = { point: end }; + } else { + end = origin.clone().addScaledVector(d, Math.min(maxT, 220)); + last = { point: end }; + } + if (p === 0 || Math.random() < 0.3) RP.FX.tracer(origin, end); + // near-miss: a crack past the player's head + var pl = RP.G.player; + if (pl && shooter !== pl && pl.alive && !(eh && eh.ent === pl)) { + var hp = pl.pos.clone(); hp.y += 1.6; + var tt = hp.clone().sub(origin).dot(d); + if (tt > 0 && tt < (end.distanceTo(origin))) { var miss = origin.clone().addScaledVector(d, tt).distanceTo(hp); if (miss < 1.5) { RP.Audio.whiz(origin.clone().addScaledVector(d, tt)); if (pl.suppress) pl.suppress(1 - miss / 1.5); } } + } + } + var loud = def.snd === 'sniper' || def.cat === 'heavy' ? 120 : def.cat === 'shotgun' ? 95 : 80; + if (opts.suppressed) loud = 18; + C.noise(origin, loud, 'shot', shooter); + return last; + }; + + // ------------------------------------------------------------------ noise (for guard hearing) + C.noise = function (pos, radius, kind, src) { + C.noises.push({ p: pos.clone(), r: radius, kind: kind, src: src, t: RP.G.time }); + if (C.noises.length > 40) C.noises.shift(); + }; + + // ------------------------------------------------------------------ melee: hit the best target in a cone in front + C.melee = function (attacker, reach, coneDeg, dmg, opts) { + opts = opts || {}; + var fwd = new T.Vector3(Math.sin(attacker.yaw), 0, Math.cos(attacker.yaw)), best = null, bs = -1; + RP.G.ents.forEach(function (e) { + if (e === attacker || !e.alive || e.team === attacker.team && !opts.any) return; + if (e.team === 'civ') return; + var to = e.pos.clone().sub(attacker.pos); var dy = to.y; to.y = 0; + var d = to.length(); if (d > reach + e.radius || Math.abs(dy) > 1.2) return; + var ang = Math.acos(M.clamp(to.normalize().dot(fwd), -1, 1)) / D2R; + if (ang > coneDeg / 2 && d > 0.6) return; + var sc = 1 - ang / 180 - d * 0.2; + if (sc > bs) { bs = sc; best = e; } + }); + if (best) { + var dir = best.pos.clone().sub(attacker.pos).setY(0).normalize(); + var p = best.pos.clone(); p.y += 1.3; + best.takeDamage(dmg, { from: attacker, dir: dir, point: p, region: 'torso', melee: true, force: opts.knock || 1, weapon: opts.weapon }); + RP.Audio.punch(p, opts.blade ? 0.7 : 1); + RP.FX.dust(p.x, p.y, p.z, dir.x, 0.2, dir.z, '#d9d1c2', 3, 0.1, 1); + C.noise(attacker.pos, opts.quiet ? 4 : 10, 'fight', attacker); + } + return best; + }; + + // ------------------------------------------------------------------ explosions + C.explode = function (pos, radius, dmg, owner) { + RP.FX.explosion(pos, radius); + C.noise(pos, 160, 'explosion', owner); + RP.G.ents.forEach(function (e) { + if (!e.alive && !(e.actor && e.actor.rag)) return; + var c = e.pos.clone(); c.y += 1; var d = c.distanceTo(pos); + if (d > radius) return; + // walls shield + if (!W.los(pos.x, pos.y + 0.4, pos.z, c.x, c.y, c.z)) return; + var k = 1 - d / radius; + var dir = c.clone().sub(pos).normalize(); + if (e.team !== 'civ') e.takeDamage(dmg * k * k + 5, { from: owner, dir: dir, point: c, region: 'torso', explosion: true, force: 6 + 10 * k }); + else if (e.scare) e.scare(pos, 3); + }); + if (RP.Cam) RP.Cam.shake(Math.max(0, 1 - pos.distanceTo(RP.R.camera.position) / (radius * 6)) * 1.4); + // glass and parked cars nearby react (cars get scorched in phase 2) + }; + + // ------------------------------------------------------------------ projectiles: frag, sticky, smoke, launcher grenade, rocket + var projGeo = null, projMat = {}; + C.throwProj = function (kind, owner, pos, vel, def) { + if (!projGeo) { + projGeo = { frag: new T.SphereGeometry(0.045, 8, 6), sticky: new T.BoxGeometry(0.08, 0.05, 0.06), smoke: new T.CylinderGeometry(0.03, 0.03, 0.12, 8), grenade: new T.SphereGeometry(0.03, 8, 6), rocket: new T.CylinderGeometry(0.035, 0.035, 0.6, 8).rotateX(Math.PI / 2) }; + projMat.frag = new T.MeshStandardMaterial({ color: RP.col('#3f4a36'), roughness: 0.6 }); projMat.sticky = new T.MeshStandardMaterial({ color: RP.col('#b59a3a') }); + projMat.smoke = new T.MeshStandardMaterial({ color: RP.col('#9aa0a6'), metalness: 0.8, roughness: 0.4 }); projMat.grenade = projMat.frag; projMat.rocket = new T.MeshStandardMaterial({ color: RP.col('#3f4a36') }); + } + var m = new T.Mesh(projGeo[kind], projMat[kind]); m.castShadow = true; m.position.copy(pos); RP.R.scene.add(m); + var p = { kind: kind, owner: owner, p: pos.clone(), v: vel.clone(), m: m, t: 0, def: def, fuse: def.fuse || 0, stuck: false, bounces: 0 }; + C.projs.push(p); + if (kind === 'rocket') p.trail = 0; + return p; + }; + C.detonateSticky = function (owner) { + var any = false; + C.projs.forEach(function (p) { if (p.kind === 'sticky' && p.owner === owner && !p.dead) { p.boom = true; any = true; } }); + return any; + }; + C.step = function (dt) { + for (var i = C.projs.length - 1; i >= 0; i--) { + var p = C.projs[i]; p.t += dt; + if (!p.stuck) { + var grav = p.kind === 'rocket' ? 0.4 : 9.8; + p.v.y -= grav * dt; + var step = p.v.clone().multiplyScalar(dt), L = step.length(); + if (L > 0) { + var d = step.clone().divideScalar(L); + var h = W.ray(p.p.x, p.p.y, p.p.z, d.x, d.y, d.z, L + 0.05); + var eh = (p.kind === 'rocket' || p.kind === 'grenade' || p.kind === 'sticky') ? C.hitEnts(p.p, d, h ? h.t : L + 0.05, p.owner) : null; + if (eh) { if (p.kind === 'sticky') { p.stuck = true; p.stuckEnt = eh.ent; p.off = eh.point.clone().sub(eh.ent.pos); } else p.boom = true; p.p.copy(eh.point); } + else if (h) { + p.p.set(h.x, h.y, h.z); + if (p.kind === 'rocket' || p.kind === 'grenade') p.boom = true; + else if (p.kind === 'sticky') { p.stuck = true; p.p.x += h.nx * 0.03; p.p.y += h.ny * 0.03; p.p.z += h.nz * 0.03; } + else { + // bounce + var n = new T.Vector3(h.nx, h.ny, h.nz), vn = p.v.dot(n); + p.v.addScaledVector(n, -1.45 * vn).multiplyScalar(0.55); + p.p.addScaledVector(n, 0.04); + if (p.bounces++ < 4 && Math.abs(vn) > 1.5) RP.Audio.impact(h.mat === 'water' ? 'water' : 'metal', p.p.clone(), 0.4); + if (h.water) { p.v.multiplyScalar(0.2); } + } + } else p.p.add(step); + } + if (p.kind === 'rocket') { + RP.FX.dust(p.p.x, p.p.y, p.p.z, -p.v.x * 0.02, 0.1, -p.v.z * 0.02, '#cfcac2', 1, 0.25, 0.3); + RP.FX.light(p.p, 2, 0.05); + if (p.t > 6) p.boom = true; + } + } else if (p.stuckEnt) p.p.copy(p.stuckEnt.pos).add(p.off); + p.m.position.copy(p.p); + if (p.kind === 'rocket') p.m.lookAt(p.p.clone().add(p.v)); + else if (!p.stuck) { p.m.rotation.x += dt * 8; p.m.rotation.z += dt * 5; } + if (p.fuse && p.t >= p.fuse) p.boom = true; + if (p.boom || p.t > 30) { + if (p.kind === 'smoke') { RP.FX.smokeCloud(p.p, p.def.radius, 20); RP.Audio.impact('dirt', p.p, 1); C.noise(p.p, 14, 'smoke', p.owner); } + else C.explode(p.p.clone().add(new T.Vector3(0, 0.15, 0)), p.def.radius || 5, p.def.dmg || 100, p.owner); + RP.R.scene.remove(p.m); C.projs.splice(i, 1); + } + } + // forget old noises + var now = RP.G.time; + C.noises = C.noises.filter(function (n) { return now - n.t < 1.2; }); + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/core.js b/e63334287a3deaa3/blacktie/js/core.js new file mode 100644 index 00000000..d6de7057 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/core.js @@ -0,0 +1,170 @@ +/* + * Black Tie: core namespace (window.RP), tuning numbers, settings, save data, small maths helpers and the + * registries for maps and missions. Every other file adds itself to RP. + * + * Load order (index.html): three r187 global build, ../autores.js, three-addons, then core, audio, input, render, + * world, maps/*, chars, ragdoll, fx, weapons, combat, player, camera, ai, hud, missions/*, main. + * + * Units: metres, seconds, radians unless a comment says otherwise. +Y up. The map's +Z points south (out to sea). + * A character's facing angle `yaw` is measured so that yaw 0 faces +Z and positive yaw turns toward +X. + */ +(function () { + 'use strict'; + var RP = window.RP = {}; + RP.GAME_NAME = 'Black Tie'; + RP.VERSION = '1'; + RP.SLUG = 'blacktie'; + + // ------------------------------------------------------------------ tuning (all feel numbers live here) + RP.TUNING = { + step: 1 / 60, // s, fixed simulation step + // locomotion speeds, m/s + walk: 1.55, jog: 3.9, sprint: 6.6, stealthWalk: 1.25, stealthJog: 2.3, aimWalk: 1.45, aimJog: 2.6, + accel: 9, // m/s^2 ground acceleration toward the wanted speed (jog) + sprintAccel: 6, // m/s^2 when building up to a sprint (weight) + decel: 12, // m/s^2 when stopping from walk/jog + sprintDecel: 7.5, // m/s^2 when stopping from a sprint (short slide/stop) + turnRate: 9, // rad/s facing turn while jogging + sprintTurnRate: 4.2, // rad/s while sprinting (momentum on sharp turns) + sharpTurnSlow: 0.55, // fraction of speed kept when a sprint turns more than ~100 degrees + stamina: 7, // s of sprint from full + staminaRegen: 0.55, // stamina per second as a fraction of drain rate while not sprinting + radius: 0.32, // m, character collision radius + stepUp: 0.42, // m, highest step walked up without a vault + gravity: 22, // m/s^2 (a little more than real so jumps feel snappy) + jumpV: 5.6, // m/s initial jump speed + vaultMax: 1.25, // m, obstacles up to this height (above feet) are vaulted + climbMax: 2.35, // m, ledges up to this are climbed; higher is blocked + fallStagger: 3.2, // m, landings from higher than this stagger + fallRagdoll: 6.5, // m, landings from higher than this ragdoll and hurt + fallLethal: 16, // m, falls this high are fatal + rollTime: 0.62, rollSpeed: 5.6, rollCooldown: 0.9, + dodgeTime: 0.38, dodgeSpeed: 5.2, dodgeCooldown: 0.55, + // health + maxHealth: 100, maxArmour: 100, + regenTo: 0.5, // regenerates up to half health only + regenDelay: 5, // s after the last hit + regenRate: 6, // hp/s + // camera + camDist: 3.1, camHeight: 1.62, camShoulder: 0.62, camFov: 62, + aimDist: 1.85, aimShoulder: 0.62, aimFov: 46, aimHeight: 1.6, + sprintDist: 3.5, sprintFov: 68, + coverDist: 2.7, + sens: 0.0023, // rad per mouse pixel + // stealth + noiseWalk: 6, noiseJog: 14, noiseSprint: 22, noiseStealth: 2.5, // m, hearing radius of footsteps + // alert + alertCool: [0, 18, 24, 30, 38, 46], // s out of sight to lose each tier + }; + + // ------------------------------------------------------------------ settings (local to this browser) + var SKEY = 'blacktie:settings'; + RP.settings = { + quality: null, // 'low' | 'medium' | 'high' (null: picked on first run) + targeting: null, // 'assistFull' | 'assistPartial' | 'freeAssist' | 'free' + sens: 1, invertY: false, fov: 0, volume: 0.8, music: 0.4, + blood: false, // content toggle: off by default (hits show dust instead) + camShake: true, subtitles: true, firstPerson: false, + difficulty: 'normal' // 'easy' | 'normal' | 'hard' + }; + try { + var s = JSON.parse(localStorage.getItem(SKEY) || 'null'); + if (s && typeof s === 'object') for (var k in s) if (k in RP.settings) RP.settings[k] = s[k]; + } catch (e) {} + RP.touch = !!(window.matchMedia && matchMedia('(pointer:coarse)').matches); + if (!RP.settings.targeting) RP.settings.targeting = RP.touch ? 'assistPartial' : 'free'; + RP.saveSettings = function () { try { localStorage.setItem(SKEY, JSON.stringify(RP.settings)); } catch (e) {} }; + + // ------------------------------------------------------------------ save data: {v:1, done:{missionId:{best, stealth}}, ...} + var GKEY = 'blacktie:save'; + RP.save = { v: 1, done: {} }; + try { + var g = JSON.parse(localStorage.getItem(GKEY) || 'null'); + if (g && g.v === 1) RP.save = g; + } catch (e) {} + RP.writeSave = function () { try { localStorage.setItem(GKEY, JSON.stringify(RP.save)); } catch (e) {} }; + + // ------------------------------------------------------------------ difficulty + RP.DIFF = { + easy: { react: 1.5, acc: 0.6, aggr: 0.7, hp: 0.8, aware: 0.75, dmgTaken: 0.6 }, + normal: { react: 1.0, acc: 1.0, aggr: 1.0, hp: 1.0, aware: 1.0, dmgTaken: 1.0 }, + hard: { react: 0.7, acc: 1.3, aggr: 1.3, hp: 1.2, aware: 1.25, dmgTaken: 1.35 } + }; + RP.diff = function () { return RP.DIFF[RP.settings.difficulty] || RP.DIFF.normal; }; + + // ------------------------------------------------------------------ maths + var M = RP.M = { + clamp: function (v, a, b) { return v < a ? a : v > b ? b : v; }, + lerp: function (a, b, t) { return a + (b - a) * t; }, + // frame-rate independent smoothing: move a fraction of the way each second + damp: function (a, b, rate, dt) { return a + (b - a) * (1 - Math.exp(-rate * dt)); }, + approach: function (v, t, rate, dt) { var d = t - v, m = rate * dt; return Math.abs(d) <= m ? t : v + Math.sign(d) * m; }, + wrap: function (a) { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; }, + angDiff: function (a, b) { return M.wrap(b - a); }, + dampAngle: function (a, b, rate, dt) { return a + M.wrap(b - a) * (1 - Math.exp(-rate * dt)); }, + approachAngle: function (a, b, rate, dt) { var d = M.wrap(b - a), m = rate * dt; return Math.abs(d) <= m ? b : a + Math.sign(d) * m; }, + smooth: function (x) { x = x < 0 ? 0 : x > 1 ? 1 : x; return x * x * (3 - 2 * x); }, + // seeded random (mulberry32), so maps build the same every time + rng: function (seed) { + var a = seed >>> 0; + return function () { a |= 0; a = a + 0x6D2B79F5 | 0; var t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; + }, + hash2: function (x, z) { var h = Math.sin(x * 127.1 + z * 311.7) * 43758.5453; return h - Math.floor(h); }, + // smooth value noise, 2D + noise2: function (x, z) { + var xi = Math.floor(x), zi = Math.floor(z), xf = x - xi, zf = z - zi; + var u = xf * xf * (3 - 2 * xf), v = zf * zf * (3 - 2 * zf); + var a = M.hash2(xi, zi), b = M.hash2(xi + 1, zi), c = M.hash2(xi, zi + 1), d = M.hash2(xi + 1, zi + 1); + return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v; + }, + fbm: function (x, z, oct) { var s = 0, amp = 0.5, f = 1; for (var i = 0; i < (oct || 4); i++) { s += amp * M.noise2(x * f, z * f); f *= 2.03; amp *= 0.5; } return s; }, + yawTo: function (dx, dz) { return Math.atan2(dx, dz); } + }; + + // sRGB hex authored colour -> linear THREE.Color (the r187 page runs with colour management off, like r128) + RP.col = function (hex) { return new THREE.Color(hex).convertSRGBToLinear(); }; + + // A one-draw-call stand-in for a model seen from a distance: every mesh under `root` (except skinned ones, meshes + // named 'far*' and any in `skip`) merged into one mesh in root's own space, coloured per vertex from its material + // (o.userData.farCol overrides, for textured parts). Hidden until the caller shows it; add it to root. + var FARMAT = null; + RP.farMat = function () { return FARMAT || (FARMAT = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.55, metalness: 0.3 })); }; + RP.farMesh = function (root, skip) { + var T = THREE, pos = [], nrm = [], col = [], inv = new T.Matrix4(), mx = new T.Matrix4(), nm = new T.Matrix3(); + var v = new T.Vector3(), n = new T.Vector3(); + root.updateMatrixWorld(true); inv.copy(root.matrixWorld).invert(); + root.traverse(function (o) { + if (!o.isMesh || o.isSkinnedMesh || /^far/.test(o.name) || (skip && skip.indexOf(o) >= 0) || !o.geometry.attributes.normal) return; + var c = o.userData.farCol || (o.material && o.material.userData && o.material.userData.farCol) || (o.material && o.material.color) || RP.col('#808080'); + mx.multiplyMatrices(inv, o.matrixWorld); nm.getNormalMatrix(mx); + var P = o.geometry.attributes.position, N = o.geometry.attributes.normal, idx = o.geometry.index, cnt = idx ? idx.count : P.count; + for (var i = 0; i < cnt; i++) { + var j = idx ? idx.getX(i) : i; + v.fromBufferAttribute(P, j).applyMatrix4(mx); n.fromBufferAttribute(N, j).applyMatrix3(nm).normalize(); + pos.push(v.x, v.y, v.z); nrm.push(n.x, n.y, n.z); col.push(c.r, c.g, c.b); + } + }); + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setAttribute('normal', new T.Float32BufferAttribute(nrm, 3)); g.setAttribute('color', new T.Float32BufferAttribute(col, 3)); + g.computeBoundingSphere(); + var m = new T.Mesh(g, RP.farMat()); m.name = 'far'; m.castShadow = false; m.visible = false; + return m; + }; + + // ------------------------------------------------------------------ registries + RP.maps = { list: {}, register: function (m) { this.list[m.id] = m; } }; + RP.missions = { list: {}, order: [], register: function (m) { this.list[m.id] = m; this.order.push(m.id); } }; + + // ------------------------------------------------------------------ tiny event bus + var subs = {}; + RP.on = function (n, f) { (subs[n] = subs[n] || []).push(f); }; + RP.emit = function (n, a, b, c) { var l = subs[n]; if (l) for (var i = 0; i < l.length; i++) l[i](a, b, c); }; + + // ------------------------------------------------------------------ the live game state (filled by main.js) + RP.G = { + time: 0, // s of simulation since the mission started + scale: 1, // time scale (the weapon wheel slows time) + player: null, actors: [], guards: [], civilians: [], mission: null, map: null, paused: true + }; + RP.test = /[?&]test\b/.test(location.search); +})(); diff --git a/e63334287a3deaa3/blacktie/js/fx.js b/e63334287a3deaa3/blacktie/js/fx.js new file mode 100644 index 00000000..03ce1692 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/fx.js @@ -0,0 +1,257 @@ +/* + * Effects (RP.FX): billboard particles (one additive pool for flashes, sparks and fire, one alpha pool for dust, + * smoke, splinters and water), pooled bullet-hole decals, tracers, ejected shells, muzzle flashes with a fixed pool + * of point lights (the count never changes at run time, so no shader recompiles), explosions, smoke clouds, and the + * lamp lights at dusk. Impact effects depend on the surface: concrete/stone dust, metal sparks, glass shards, + * wood splinters, dirt, water splashes. Blood is off by default (settings): hits on people show a puff of fabric dust. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M; + var F = RP.FX = {}; + var R = RP.R; + + function makePool(n, additive) { + var g = new T.InstancedBufferGeometry(); + g.setAttribute('position', new T.Float32BufferAttribute([-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0], 3)); + g.setAttribute('uv', new T.Float32BufferAttribute([0, 0, 1, 0, 1, 1, 0, 1], 2)); + g.setIndex([0, 1, 2, 0, 2, 3]); + var P = new Float32Array(n * 4), C = new Float32Array(n * 4), S = new Float32Array(n * 2); + g.setAttribute('iPos', new T.InstancedBufferAttribute(P, 4)); // xyz, size + g.setAttribute('iCol', new T.InstancedBufferAttribute(C, 4)); // rgb, alpha + g.setAttribute('iSt', new T.InstancedBufferAttribute(S, 2)); // rotation, stretch + g.instanceCount = 0; + var mat = new T.ShaderMaterial({ + uniforms: { tMap: { value: RP.tex.blob }, fogColor: { value: R.fog.color }, fogDensity: { value: R.fog.density } }, + transparent: true, depthWrite: false, blending: additive ? T.AdditiveBlending : T.NormalBlending, + vertexShader: [ + 'attribute vec4 iPos; attribute vec4 iCol; attribute vec2 iSt; varying vec2 vUv; varying vec4 vCol; varying float vFog;', + 'void main(){ vUv = uv; vCol = iCol;', + ' vec4 mv = viewMatrix * vec4(iPos.xyz, 1.0);', + ' float c = cos(iSt.x), s = sin(iSt.x); vec2 p = position.xy; p.y *= iSt.y; p = vec2(c*p.x - s*p.y, s*p.x + c*p.y);', + ' mv.xy += p * iPos.w; vFog = -mv.z; gl_Position = projectionMatrix * mv; }' + ].join('\n'), + fragmentShader: [ + 'uniform sampler2D tMap; uniform vec3 fogColor; uniform float fogDensity; varying vec2 vUv; varying vec4 vCol; varying float vFog;', + 'void main(){ float a = texture2D(tMap, vUv).a * vCol.a; if (a < 0.004) discard;', + ' float f = 1.0 - exp(-fogDensity*fogDensity*vFog*vFog);', + (additive ? ' gl_FragColor = vec4(vCol.rgb * a * (1.0 - f), 1.0);' : ' gl_FragColor = vec4(mix(vCol.rgb, fogColor, f), a);'), + '}' + ].join('\n') + }); + var mesh = new T.Mesh(g, mat); mesh.frustumCulled = false; mesh.renderOrder = additive ? 6 : 5; + R.scene.add(mesh); + return { g: g, P: P, C: C, S: S, n: n, list: [], mesh: mesh }; + } + // particle: {x,y,z, vx,vy,vz, life, max, size0, size1, r,g,b, a0, a1, drag, grav, rot, spin, stretch} + function emit(pool, o) { + if (pool.list.length >= pool.n) pool.list.shift(); + o.t = 0; o.rot = o.rot == null ? Math.random() * 6.28 : o.rot; o.spin = o.spin || 0; o.stretch = o.stretch || 1; + pool.list.push(o); return o; + } + function stepPool(pool, dt) { + var L = pool.list, k = 0, P = pool.P, C = pool.C, S = pool.S; + for (var i = 0; i < L.length; i++) { + var p = L[i]; p.t += dt; + if (p.t >= p.max) continue; + var d = Math.exp(-(p.drag || 0) * dt); + p.vx *= d; p.vy = p.vy * d - (p.grav || 0) * dt; p.vz *= d; + p.x += p.vx * dt; p.y += p.vy * dt; p.z += p.vz * dt; + if (p.floor != null && p.y < p.floor) { p.y = p.floor; p.vy *= -0.3; p.vx *= 0.5; p.vz *= 0.5; } + p.rot += p.spin * dt; + var u = p.t / p.max; + P[k * 4] = p.x; P[k * 4 + 1] = p.y; P[k * 4 + 2] = p.z; P[k * 4 + 3] = p.size0 + (p.size1 - p.size0) * u; + var fade = p.a0 + (p.a1 - p.a0) * u; if (p.fadeIn) fade *= Math.min(1, p.t / p.fadeIn); + C[k * 4] = p.r; C[k * 4 + 1] = p.g; C[k * 4 + 2] = p.b; C[k * 4 + 3] = fade; + S[k * 2] = p.rot; S[k * 2 + 1] = p.stretch; + L[k++] = p; + } + L.length = k; + pool.g.instanceCount = k; + pool.g.attributes.iPos.needsUpdate = true; pool.g.attributes.iCol.needsUpdate = true; pool.g.attributes.iSt.needsUpdate = true; + } + + F.init = function () { + var q = R.q; + F.add = makePool(Math.round(700 * q.particles), true); + F.alpha = makePool(Math.round(1200 * q.particles), false); + // decals + F.decals = []; F.decalMax = q.decals; F.decalI = 0; + var dg = new T.PlaneGeometry(1, 1); + F.decalMat = new T.MeshStandardMaterial({ map: RP.tex.hole, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, roughness: 1 }); + F.decalGeo = dg; + // tracers + F.tracers = []; + var tg = new T.BoxGeometry(0.018, 0.018, 1); tg.translate(0, 0, 0.5); + F.tracerMat = new T.MeshBasicMaterial({ color: new T.Color(5, 3.6, 1.6), transparent: true, opacity: 0.9, blending: T.AdditiveBlending, depthWrite: false }); + for (var i = 0; i < 24; i++) { var m = new T.Mesh(tg, F.tracerMat); m.visible = false; m.frustumCulled = false; R.scene.add(m); F.tracers.push({ m: m, t: 1 }); } + // shells + var sg = new T.CylinderGeometry(0.005, 0.005, 0.022, 6); sg.rotateZ(Math.PI / 2); + F.shellMesh = new T.InstancedMesh(sg, new T.MeshStandardMaterial({ color: RP.col('#c9a040'), metalness: 1, roughness: 0.3 }), 60); + F.shellMesh.count = 0; F.shellMesh.frustumCulled = false; R.scene.add(F.shellMesh); F.shells = []; + // point lights: muzzle flashes and explosions; lamps at dusk (fixed counts per quality) + F.flashLights = []; + var nf = R.qname === 'low' ? 1 : 2; + for (i = 0; i < nf; i++) { var l = new T.PointLight(0xffc27a, 0, 14, 2); R.scene.add(l); F.flashLights.push({ l: l, t: 0, max: 0.06, i0: 0 }); } + F.lampLights = []; + var nl = R.qname === 'low' ? 0 : R.qname === 'medium' ? 3 : 5; + for (i = 0; i < nl; i++) { var ll = new T.PointLight(0xffb36b, 0, 16, 2); R.scene.add(ll); F.lampLights.push(ll); } + // explosion fireball sphere pool + F.balls = []; + var bm = new T.MeshBasicMaterial({ color: new T.Color(8, 4, 1.2), transparent: true, blending: T.AdditiveBlending, depthWrite: false }); + for (i = 0; i < 4; i++) { var b = new T.Mesh(new T.SphereGeometry(1, 16, 10), bm.clone()); b.visible = false; R.scene.add(b); F.balls.push({ m: b, t: 9 }); } + F.smokes = []; + }; + + // ------------------------------------------------------------------ building blocks + function rnd(a, b) { return a + Math.random() * (b - a); } + F.dust = function (x, y, z, nx, ny, nz, colHex, n, size, speed) { + var c = RP.col(colHex || '#b9ab95'); n = Math.round((n || 6) * R.q.particles); + for (var i = 0; i < n; i++) emit(F.alpha, { x: x, y: y, z: z, vx: nx * speed * rnd(0.3, 1) + rnd(-1, 1) * speed * 0.4, vy: ny * speed * rnd(0.3, 1) + rnd(0, 0.6), vz: nz * speed * rnd(0.3, 1) + rnd(-1, 1) * speed * 0.4, + max: rnd(0.6, 1.4), size0: size * 0.4, size1: size * rnd(1.4, 2.4), r: c.r, g: c.g, b: c.b, a0: 0.55, a1: 0, drag: 3, grav: -0.15 }); + }; + F.sparks = function (x, y, z, nx, ny, nz, n) { + n = Math.round((n || 10) * R.q.particles); + for (var i = 0; i < n; i++) { + var sp = rnd(3, 9); + emit(F.add, { x: x, y: y, z: z, vx: nx * sp + rnd(-3, 3), vy: ny * sp + rnd(-1, 4), vz: nz * sp + rnd(-3, 3), max: rnd(0.12, 0.35), size0: 0.035, size1: 0.01, r: 6, g: 3.6, b: 1.2, a0: 1, a1: 0.3, grav: 9.8, drag: 1, stretch: 3 }); + } + }; + F.chunks = function (x, y, z, nx, ny, nz, colHex, n) { + var c = RP.col(colHex); n = Math.round((n || 6) * R.q.particles); + for (var i = 0; i < n; i++) emit(F.alpha, { x: x, y: y, z: z, vx: nx * rnd(1, 4) + rnd(-1.5, 1.5), vy: ny * rnd(1, 3) + rnd(0.5, 3), vz: nz * rnd(1, 4) + rnd(-1.5, 1.5), + max: rnd(0.5, 1), size0: rnd(0.03, 0.06), size1: 0.03, r: c.r, g: c.g, b: c.b, a0: 1, a1: 1, grav: 9.8, drag: 0.5, spin: rnd(-10, 10), floor: RP.W.terrainH(x, z) }); + }; + F.splash = function (x, y, z, k) { + k = k || 1; + for (var i = 0; i < 14 * R.q.particles * k; i++) emit(F.alpha, { x: x, y: y, z: z, vx: rnd(-1, 1) * k, vy: rnd(2, 5) * k, vz: rnd(-1, 1) * k, max: rnd(0.4, 0.8), size0: 0.08 * k, size1: 0.25 * k, r: 0.85, g: 0.92, b: 0.95, a0: 0.8, a1: 0, grav: 9.8, drag: 0.5 }); + emit(F.alpha, { x: x, y: y + 0.05, z: z, vx: 0, vy: 0, vz: 0, max: 0.9, size0: 0.3 * k, size1: 1.6 * k, r: 0.9, g: 0.95, b: 0.97, a0: 0.5, a1: 0, rot: 0 }); + }; + F.glassBurst = function (x, y, z, nx, nz) { + for (var i = 0; i < 20 * R.q.particles; i++) emit(F.add, { x: x, y: y, z: z, vx: nx * rnd(0.5, 3) + rnd(-1, 1), vy: rnd(-0.5, 2.5), vz: nz * rnd(0.5, 3) + rnd(-1, 1), max: rnd(0.5, 1.1), size0: rnd(0.02, 0.05), size1: 0.02, r: 1.2, g: 1.4, b: 1.5, a0: 0.9, a1: 0.4, grav: 9.8, spin: rnd(-12, 12), floor: RP.W.terrainH(x, z) }); + }; + // the surface reaction to a bullet: by material + F.impact = function (h, dx, dy, dz, opts) { + var x = h.x, y = h.y, z = h.z, nx = h.nx || 0, ny = h.ny || 1, nz = h.nz || 0, mat = h.mat || 'stone'; + var heavy = opts && opts.heavy ? 1.6 : 1; + switch (mat) { + case 'metal': case 'car': F.sparks(x, y, z, nx, ny, nz, 12 * heavy); F.dust(x, y, z, nx, ny, nz, '#6f6a66', 2, 0.15, 1); break; + case 'glass': F.glassBurst(x, y, z, -dx, -dz); break; + case 'wood': F.chunks(x, y, z, nx, ny, nz, '#8a6a48', 7 * heavy); F.dust(x, y, z, nx, ny, nz, '#a08466', 3, 0.15, 1.2); break; + case 'water': F.splash(x, y, z, 0.6 * heavy); break; + case 'dirt': case 'sand': F.dust(x, y, z, nx, ny, nz, mat === 'sand' ? '#d4c29a' : '#8a7a5e', 7 * heavy, 0.22, 2.2); F.chunks(x, y, z, nx, ny, nz, '#6d5f48', 3); break; + case 'cloth': F.dust(x, y, z, nx, ny, nz, '#e8e2d6', 4, 0.12, 1); break; + case 'flesh': + if (RP.settings.blood) F.dust(x, y, z, -dx, 0.3, -dz, '#7a1010', 5, 0.1, 1.5); + else F.dust(x, y, z, -dx, 0.3, -dz, '#8b8478', 4, 0.12, 1.2); + return; + default: F.dust(x, y, z, nx, ny, nz, mat === 'plaster' ? '#e8dfcf' : '#c9bfae', 8 * heavy, 0.2, 2.6); F.chunks(x, y, z, nx, ny, nz, '#bfb5a4', 3); + } + if (mat !== 'water' && mat !== 'cloth' && !(opts && opts.noDecal)) F.decal(x, y, z, nx, ny, nz, mat === 'glass' ? 0.12 : 0.09); + RP.Audio.impact(mat, new T.Vector3(x, y, z)); + }; + F.decal = function (x, y, z, nx, ny, nz, size) { + if (!F.decalMax) return; + var d; + if (F.decals.length < F.decalMax) { d = new T.Mesh(F.decalGeo, F.decalMat); d.renderOrder = 1; R.scene.add(d); F.decals.push(d); } + else { d = F.decals[F.decalI]; F.decalI = (F.decalI + 1) % F.decalMax; } + d.position.set(x + nx * 0.01, y + ny * 0.01, z + nz * 0.01); + d.lookAt(x + nx, y + ny, z + nz); d.rotateZ(Math.random() * 6.28); + d.scale.setScalar(size * rnd(0.8, 1.2)); + }; + F.tracer = function (a, b, hot) { + var t = null; + for (var i = 0; i < F.tracers.length; i++) if (F.tracers[i].t >= 1) { t = F.tracers[i]; break; } + if (!t) t = F.tracers[0]; + var L = a.distanceTo(b); if (L < 1) return; + t.a = a.clone(); t.b = b.clone(); t.L = L; t.t = 0; t.speed = 900 / L; + t.m.visible = true; t.m.position.copy(a); t.m.lookAt(b); + }; + F.muzzle = function (pos, dir, big) { + var s = big ? 0.55 : 0.32; + emit(F.add, { x: pos.x + dir.x * 0.05, y: pos.y + dir.y * 0.05, z: pos.z + dir.z * 0.05, vx: dir.x * 2, vy: dir.y * 2, vz: dir.z * 2, max: 0.05, size0: s, size1: s * 1.2, r: 7, g: 4.2, b: 1.6, a0: 1, a1: 0 }); + emit(F.add, { x: pos.x + dir.x * 0.18, y: pos.y + dir.y * 0.18, z: pos.z + dir.z * 0.18, vx: dir.x * 4, vy: dir.y * 4, vz: dir.z * 4, max: 0.04, size0: s * 0.7, size1: s * 0.4, r: 6, g: 3, b: 1, a0: 0.9, a1: 0, stretch: 2.2 }); + emit(F.alpha, { x: pos.x + dir.x * 0.25, y: pos.y + dir.y * 0.25, z: pos.z + dir.z * 0.25, vx: dir.x * 1.2, vy: 0.4, vz: dir.z * 1.2, max: 0.7, size0: 0.08, size1: 0.5, r: 0.7, g: 0.7, b: 0.7, a0: 0.25, a1: 0, drag: 2 }); + F.light(pos, big ? 5 : 3, 0.05); + }; + F.light = function (pos, intensity, dur, colHex) { + var best = F.flashLights[0]; + for (var i = 0; i < F.flashLights.length; i++) if (F.flashLights[i].t >= F.flashLights[i].max) { best = F.flashLights[i]; break; } + if (!best) return; + best.l.position.copy(pos); best.t = 0; best.max = dur; best.i0 = intensity; best.l.intensity = intensity; + best.l.color.copy(colHex ? RP.col(colHex) : RP.col('#ffc27a')); + }; + F.shell = function (pos, dir, side) { + if (F.shells.length >= 60) F.shells.shift(); + F.shells.push({ p: pos.clone(), v: new T.Vector3(side.x * 2.2 + dir.x * 0.3, 2.2 + Math.random(), side.z * 2.2 + dir.z * 0.3), r: new T.Euler(Math.random() * 3, Math.random() * 3, 0), w: rnd(10, 25), t: 0, floor: RP.W.ground(pos.x, pos.z, pos.y).y, bounced: 0 }); + }; + F.explosion = function (pos, radius) { + var k = radius / 6; + // fireball + var b = F.balls[0]; for (var i = 0; i < F.balls.length; i++) if (F.balls[i].t > 0.6) { b = F.balls[i]; break; } + b.t = 0; b.r = radius * 0.55; b.m.position.copy(pos); b.m.visible = true; + for (i = 0; i < 26 * R.q.particles * k; i++) emit(F.add, { x: pos.x, y: pos.y + 0.3, z: pos.z, vx: rnd(-6, 6) * k, vy: rnd(1, 8) * k, vz: rnd(-6, 6) * k, max: rnd(0.25, 0.6), size0: rnd(0.8, 1.6) * k, size1: rnd(2, 3) * k, r: 6, g: 2.8, b: 0.8, a0: 0.9, a1: 0, drag: 4 }); + for (i = 0; i < 40 * R.q.particles * k; i++) F.sparks(pos.x, pos.y + 0.5, pos.z, rnd(-1, 1), rnd(0.2, 1.4), rnd(-1, 1), 1); + for (i = 0; i < 22 * R.q.particles * k; i++) emit(F.alpha, { x: pos.x + rnd(-1, 1), y: pos.y + rnd(0, 1.5), z: pos.z + rnd(-1, 1), vx: rnd(-2.5, 2.5) * k, vy: rnd(1, 4) * k, vz: rnd(-2.5, 2.5) * k, max: rnd(2.5, 5), size0: rnd(1, 2) * k, size1: rnd(4, 7) * k, r: 0.16, g: 0.15, b: 0.14, a0: 0.75, a1: 0, drag: 1.2, grav: -0.25, fadeIn: 0.15 }); + F.chunks(pos.x, pos.y + 0.3, pos.z, 0, 1, 0, '#5e5850', 14 * k); + F.light(pos, 40 * k, 0.35, '#ffb066'); + F.decal(pos.x, RP.W.ground(pos.x, pos.z, pos.y + 1).y + 0.02, pos.z, 0, 1, 0, radius * 0.8); + R.flash.set(0.6, 0.35, 0.12).multiplyScalar(Math.max(0, 1 - pos.distanceTo(R.camera.position) / 60)); + RP.Audio.explosion(pos, k); + }; + F.smokeCloud = function (pos, radius, dur) { + var s = { p: pos.clone(), r: radius, t: 0, dur: dur || 18, acc: 0 }; F.smokes.push(s); return s; + }; + F.inSmoke = function (p) { for (var i = 0; i < F.smokes.length; i++) { var s = F.smokes[i], k = Math.min(1, s.t / 1.5) * (s.t > s.dur - 3 ? (s.dur - s.t) / 3 : 1); if (k > 0.3 && p.distanceTo(s.p) < s.r * k) return true; } return false; }; + + // ------------------------------------------------------------------ per frame + var _e = new T.Matrix4(), _q = new T.Quaternion(); + F.update = function (dt) { + stepPool(F.add, dt); stepPool(F.alpha, dt); + for (var i = 0; i < F.tracers.length; i++) { + var t = F.tracers[i]; if (t.t >= 1) continue; + t.t += dt * t.speed; + if (t.t >= 1) { t.m.visible = false; continue; } + var head = Math.min(1, t.t + 0.12 * Math.min(1, 40 / t.L) * 3), tail = t.t; + t.m.position.copy(t.a).lerp(t.b, tail); t.m.scale.set(1, 1, t.L * (head - tail)); + } + for (i = 0; i < F.flashLights.length; i++) { var f = F.flashLights[i]; if (f.t < f.max) { f.t += dt; f.l.intensity = f.i0 * Math.max(0, 1 - f.t / f.max); } else f.l.intensity = 0; } + // shells + var n = 0; + for (i = 0; i < F.shells.length; i++) { + var s = F.shells[i]; s.t += dt; if (s.t > 4) continue; + if (s.bounced < 3) { + s.v.y -= 9.8 * dt; s.p.addScaledVector(s.v, dt); s.r.x += s.w * dt; s.r.y += s.w * 0.6 * dt; + if (s.p.y < s.floor + 0.004) { s.p.y = s.floor + 0.004; s.v.y *= -0.35; s.v.x *= 0.5; s.v.z *= 0.5; s.w *= 0.5; s.bounced++; if (s.bounced === 1 && Math.random() < 0.5) RP.Audio.mech('brass', s.p); } + } + _q.setFromEuler(s.r); _e.compose(s.p, _q, new T.Vector3(1, 1, 1)); F.shellMesh.setMatrixAt(n++, _e); + } + F.shellMesh.count = n; F.shellMesh.instanceMatrix.needsUpdate = true; + // fireballs + for (i = 0; i < F.balls.length; i++) { + var b = F.balls[i]; if (b.t > 0.6) { b.m.visible = false; continue; } + b.t += dt; var u = b.t / 0.6; + b.m.scale.setScalar(b.r * (0.4 + Math.sqrt(u) * 0.9)); b.m.material.opacity = Math.max(0, 1 - u * 1.4); + } + // smoke clouds: keep emitting big slow puffs + for (i = F.smokes.length - 1; i >= 0; i--) { + var c = F.smokes[i]; c.t += dt; if (c.t > c.dur) { F.smokes.splice(i, 1); continue; } + c.acc += dt; + while (c.acc > 0.08 && c.t < c.dur - 3) { + c.acc -= 0.08; + var a = Math.random() * 6.28, rr = Math.random() * c.r * Math.min(1, c.t / 2) * 0.8; + emit(F.alpha, { x: c.p.x + Math.cos(a) * rr, y: c.p.y + rnd(0.2, 1.5), z: c.p.z + Math.sin(a) * rr, vx: rnd(-0.3, 0.3), vy: rnd(0.1, 0.4), vz: rnd(-0.3, 0.3), max: rnd(3, 5), size0: 1.5, size1: rnd(3.5, 5), r: 0.82, g: 0.83, b: 0.84, a0: 0.55, a1: 0, fadeIn: 0.6, drag: 0.6 }); + } + } + // lamp lights at dusk: the nearest lamps to the camera + if (F.lampLights.length && RP.map && RP.map.lamps && RP.G.night) { + var cam = R.camera.position, L = RP.map.lamps, best = []; + for (i = 0; i < L.length; i++) { var d = L[i].distanceToSquared(cam); if (d < 3600) best.push([d, L[i]]); } + best.sort(function (a, b) { return a[0] - b[0]; }); + for (i = 0; i < F.lampLights.length; i++) { + var ll = F.lampLights[i]; + if (best[i]) { ll.position.copy(best[i][1]); ll.position.y -= 0.3; ll.intensity = 1.6; } else ll.intensity = 0; + } + } else F.lampLights.forEach(function (l) { l.intensity = 0; }); + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/gunmodels.js b/e63334287a3deaa3/blacktie/js/gunmodels.js new file mode 100644 index 00000000..997ef0d0 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/gunmodels.js @@ -0,0 +1,344 @@ +/* + * Gun and melee models (RP.GunModels.build(id)), made in code: side profiles drawn as 2D outlines and extruded with a + * bevel (slides, frames, receivers, raked grips, stocks, magazines), turned parts (barrels, cylinders, optics, + * suppressors), and small details (sights, rails, serrations, trigger guards, ejection ports, sling swivels). + * Every design is generic and invented; no real maker's shapes, markings or logos. + * + * Contract (same as before): barrel along +Z, up +Y, origin in the middle of the right-hand grip (where weapon_r + * holds it); userData.muzzle, userData.gripL (left hand, long guns), userData.eject, userData.mag (the magazine mesh + * group, for reloads) and userData.oneHand. Parts are merged by material: 2-4 draw calls a gun. + */ +(function () { + 'use strict'; + var T = THREE, D = Math.PI / 180; + var GM = RP.GunModels = {}; + + // ------------------------------------------------------------------ materials (shared) + var MATS = null; + function noiseTex(seed, scale) { + var c = document.createElement('canvas'); c.width = c.height = 128; var x = c.getContext('2d'), im = x.createImageData(128, 128); + var s = seed; + for (var i = 0; i < 128 * 128; i++) { s = (s * 16807) % 2147483647; var v = 150 + ((s % 1000) / 1000 - 0.5) * scale; im.data[i * 4] = im.data[i * 4 + 1] = im.data[i * 4 + 2] = v; im.data[i * 4 + 3] = 255; } + x.putImageData(im, 0, 0); + var t = new T.CanvasTexture(c); t.wrapS = t.wrapT = T.RepeatWrapping; t.repeat.set(6, 6); return t; + } + function woodTex() { + var c = document.createElement('canvas'); c.width = 64; c.height = 256; var x = c.getContext('2d'); + for (var y = 0; y < 256; y++) { + var g = 0.5 + 0.5 * Math.sin(y * 0.35 + Math.sin(y * 0.05) * 4) * Math.sin(y * 0.11); + x.fillStyle = 'rgb(' + Math.round(62 + 26 * g) + ',' + Math.round(36 + 14 * g) + ',' + Math.round(22 + 8 * g) + ')'; x.fillRect(0, y, 64, 1); + } + var t = new T.CanvasTexture(c); t.wrapS = t.wrapT = T.RepeatWrapping; t.repeat.set(1, 3); if (T.SRGBColorSpace) t.colorSpace = T.SRGBColorSpace; return t; + } + function mats() { + if (MATS) return MATS; + var rn = noiseTex(7, 70); + function std(hex, r, m, o) { var mm = new T.MeshStandardMaterial(Object.assign({ color: RP.col(hex), roughness: r, metalness: m }, o || {})); mm.name = 'gun-' + hex; return mm; } + MATS = { + blued: std('#24272b', 0.42, 0.8, { roughnessMap: rn }), steel: std('#3a3d41', 0.36, 0.85, { roughnessMap: rn }), + poly: std('#1b1c1e', 0.72, 0.04, { roughnessMap: rn }), tan: std('#6e6049', 0.78, 0.04, { roughnessMap: rn }), + green: std('#3b4334', 0.66, 0.08, { roughnessMap: rn }), wood: new T.MeshStandardMaterial({ map: woodTex(), roughness: 0.48, metalness: 0 }), + glass: std('#10151c', 0.05, 0.2, { emissive: RP.col('#0c1a14') }), red: std('#7d2219', 0.5, 0.1), alu: std('#a6abb0', 0.32, 0.9), + blade: std('#c3c7cb', 0.2, 1), rubber: std('#151515', 0.9, 0), grip: std('#2d2017', 0.8, 0), yellow: std('#b59a3a', 0.5, 0.2), brass: std('#b08a3e', 0.3, 0.9) + }; + MATS.wood.name = 'gun-wood'; + return MATS; + } + + // ------------------------------------------------------------------ geometry helpers + // side profile: points [z, y] in metres (z forward, y up), extruded across x with a bevel, centred on x = 0 + function prof(pts, width, bevel, curveSegs) { + var sh = new T.Shape(); sh.moveTo(pts[0][0], pts[0][1]); + for (var i = 1; i < pts.length; i++) { + var p = pts[i]; + if (p.length === 4) sh.quadraticCurveTo(p[0], p[1], p[2], p[3]); else sh.lineTo(p[0], p[1]); + } + var b = bevel == null ? Math.min(0.004, width * 0.2) : bevel; + var g = new T.ExtrudeGeometry(sh, { depth: Math.max(0.001, width - 2 * b), bevelEnabled: b > 0, bevelThickness: b, bevelSize: b, bevelSegments: 2, curveSegments: curveSegs || 6 }); + g.rotateY(-Math.PI / 2); g.translate((width - 2 * b) / 2, 0, 0); + return g; + } + function tube(r, len, z0, y, seg, r2) { var g = new T.CylinderGeometry(r2 == null ? r : r2, r, len, seg || 14, 1); g.rotateX(Math.PI / 2); g.translate(0, y || 0, z0 + len / 2); return g; } + function tubeX(r, len, x0, y, z, seg) { var g = new T.CylinderGeometry(r, r, len, seg || 10); g.rotateZ(Math.PI / 2); g.translate(x0, y, z); return g; } + function box(w, h, d, x, y, z) { var g = new T.BoxGeometry(w, h, d); g.translate(x || 0, y || 0, z || 0); return g; } + function lathe(profile, z0, y, seg) { // profile [[r, z]] along +Z + var g = new T.LatheGeometry(profile.map(function (p) { return new T.Vector2(p[0], p[1]); }), seg || 16); + g.rotateX(Math.PI / 2); g.translate(0, y || 0, z0 || 0); return g; + } + function ring(R, r, arc, rotY) { var g = new T.TorusGeometry(R, r, 6, 14, arc); return g; } + function rail(len, z0, y, w) { // picatinny-style rail: a base strip with cross slots + var out = [box(w || 0.021, 0.006, len, 0, y + 0.003, z0 + len / 2)]; + for (var z = z0 + 0.006; z < z0 + len - 0.004; z += 0.01) out.push(box((w || 0.021) + 0.002, 0.004, 0.005, 0, y + 0.008, z)); + return out; + } + function serrations(n, z0, step, y, h, w) { var out = []; for (var i = 0; i < n; i++) out.push(box(w, h, 0.0018, 0, y, z0 + i * step)); return out; } + function rot(g, ax, a, pivot) { pivot = pivot || [0, 0, 0]; g.translate(-pivot[0], -pivot[1], -pivot[2]); if (ax === 'x') g.rotateX(a); else if (ax === 'y') g.rotateY(a); else g.rotateZ(a); g.translate(pivot[0], pivot[1], pivot[2]); return g; } + // merge any mix of indexed and non-indexed parts, keeping each part's own normals (crisp edges stay crisp) + function merge(list) { + var pos = [], nrm = [], uv = []; + list.forEach(function (g0) { + var g = g0.index ? g0.toNonIndexed() : g0; + if (!g.attributes.normal) g.computeVertexNormals(); + var P = g.attributes.position, N = g.attributes.normal, U = g.attributes.uv; + for (var i = 0; i < P.count; i++) { pos.push(P.getX(i), P.getY(i), P.getZ(i)); nrm.push(N.getX(i), N.getY(i), N.getZ(i)); uv.push(U ? U.getX(i) : 0, U ? U.getY(i) : 0); } + }); + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setAttribute('normal', new T.Float32BufferAttribute(nrm, 3)); g.setAttribute('uv', new T.Float32BufferAttribute(uv, 2)); + return g; + } + + // the farthest gun: an axis-aligned box per part bigger than 3.5 cm (barrel, receiver, grip, stock, magazine), + // coloured from the part's material; pins, serrations and screws are left out + var _bb = new T.Box3(), _bs = new T.Vector3(), _bc = new T.Vector3(); + function farBoxes(parts, mag, M) { + var unit = new T.BoxGeometry(1, 1, 1).toNonIndexed(), UP = unit.attributes.position, UN = unit.attributes.normal, pos = [], nrm = [], col = []; + [parts, mag || {}].forEach(function (set) { + Object.keys(set).forEach(function (k) { + var c = M[k].map ? RP.col('#5a3a22') : M[k].color; + set[k].forEach(function (geo) { + if (!geo.boundingBox) geo.computeBoundingBox(); + _bb.copy(geo.boundingBox); _bb.getSize(_bs); if (Math.max(_bs.x, _bs.y, _bs.z) < 0.035) return; + _bb.getCenter(_bc); + for (var i = 0; i < UP.count; i++) { + pos.push(_bc.x + UP.getX(i) * _bs.x, _bc.y + UP.getY(i) * _bs.y, _bc.z + UP.getZ(i) * _bs.z); + nrm.push(UN.getX(i), UN.getY(i), UN.getZ(i)); col.push(c.r, c.g, c.b); + } + }); + }); + }); + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setAttribute('normal', new T.Float32BufferAttribute(nrm, 3)); g.setAttribute('color', new T.Float32BufferAttribute(col, 3)); + g.computeBoundingSphere(); + var m = new T.Mesh(g, RP.farMat()); m.name = 'far2'; m.castShadow = false; m.visible = false; return m; + } + + // build a model: parts = {matName: [geos]}, opts = points + function make(parts, opts) { + var M = mats(), g = new T.Group(); + Object.keys(parts).forEach(function (k) { + if (!parts[k].length) return; + var geo = merge(parts[k]); + var m = new T.Mesh(geo, M[k]); m.castShadow = true; m.receiveShadow = false; g.add(m); + }); + if (opts.mag) { + var mg = new T.Group(); mg.name = 'mag'; + Object.keys(opts.mag).forEach(function (k) { var geo = merge(opts.mag[k]); var m = new T.Mesh(geo, M[k]); m.castShadow = true; mg.add(m); }); + g.add(mg); g.userData.mag = mg; + } + function pt(name, p) { var o = new T.Object3D(); o.position.set(p[0], p[1], p[2]); o.name = name; g.add(o); return o; } + g.userData.muzzle = pt('muzzle', opts.muzzle); + if (opts.gripL) g.userData.gripL = pt('gripL', opts.gripL); + g.userData.eject = pt('eject', opts.eject || [0.02, 0.05, 0.05]); + if (opts.oneHand) g.userData.oneHand = true; + g.userData.len = opts.len || 0.5; + // the far versions, one draw call each: every part merged and coloured per vertex (level 1), and one box per + // part (level 2, a few hundred triangles instead of about a thousand) + g.traverse(function (o) { if (o.isMesh && o.material.map) o.userData.farCol = RP.col('#5a3a22'); }); + g.position.set(0, 0, 0); g.rotation.set(0, 0, 0); g.scale.set(1, 1, 1); + var far = RP.farMesh(g), far2 = farBoxes(parts, opts.mag, M); + g.add(far); g.add(far2); g.userData.far = far; g.userData.far2 = far2; + return g; + } + // show the full model (0), the merged mesh (1 or true) or the boxes (2) + GM.setFar = function (g, lvl) { + lvl = lvl === true ? 1 : lvl === false ? 0 : lvl; + if (!g.userData.far || g.userData._far === lvl) return; + g.userData._far = lvl; + var f1 = g.userData.far, f2 = g.userData.far2; + g.children.forEach(function (c) { + if (c === f1) c.visible = lvl === 1; else if (c === f2) c.visible = lvl === 2; + else if (c.isMesh) c.visible = lvl === 0; else if (c.name === 'mag') c.visible = lvl === 0; + }); + }; + + // the raked pistol grip shared by most long guns (origin at its middle) + function pistolGrip(top, rake) { + rake = rake || 0.3; + return prof([[-0.022, top], [0.024, top], [0.022 - rake * 0.05, -0.05], [0.017 - rake * 0.1, -0.075], [-0.026 - rake * 0.1, -0.078], [-0.03 - rake * 0.05, -0.04], [-0.026, top]], 0.03, 0.005); + } + function triggerGuard(z0, z1, y0, depth) { + var out = [box(0.008, 0.005, z1 - z0, 0, y0 - depth, (z0 + z1) / 2), box(0.008, depth, 0.005, 0, y0 - depth / 2, z1)]; + var tr = new T.TorusGeometry(0.008, 0.0022, 5, 8, Math.PI * 0.8); tr.rotateY(Math.PI / 2); tr.translate(0, y0 - 0.011, z0 + 0.016); out.push(tr); + return out; + } + function ironSights(zf, zr, y, h) { return [box(0.004, h, 0.006, 0, y + h / 2, zf), box(0.016, h * 0.8, 0.006, 0, y + h * 0.4, zr)]; } + function redDot(z0, y) { + return [lathe([[0.0, 0], [0.016, 0.0], [0.017, 0.008], [0.017, 0.05], [0.016, 0.058], [0, 0.058]], z0, y + 0.03, 16), box(0.016, 0.02, 0.04, 0, y + 0.012, z0 + 0.03)]; + } + function scope(z0, len, y, r) { + r = r || 0.017; + return [lathe([[0, 0], [r * 1.45, 0], [r * 1.5, 0.01], [r * 1.45, 0.06], [r, 0.09], [r, len - 0.12], [r * 1.25, len - 0.07], [r * 1.35, len - 0.01], [0, len]], z0, y, 18), + tube(r * 1.15, 0.03, z0 + len * 0.42, y, 12), box(0.018, 0.022, 0.03, 0, y - r - 0.006, z0 + 0.12), box(0.018, 0.022, 0.03, 0, y - r - 0.006, z0 + len - 0.17), + tubeX(0.008, 0.035, 0.024, y, z0 + len * 0.45, 10), (function () { var g = tube(0.008, 0.02, z0 + len * 0.45, y + r + 0.004, 10); return rot(g, 'x', Math.PI / 2, [0, y + r + 0.004, z0 + len * 0.45 + 0.01]); })()]; + } + function curvedMag(top, zc, len, depth, curve, w) { + // a box magazine curving forward as it goes down + var pts = [[zc - depth / 2, top], [zc + depth / 2, top], [zc + depth / 2 + curve, top - len], [zc - depth / 2 + curve * 0.7, top - len - 0.004], [zc - depth / 2, top]]; + return [prof([pts[0], pts[1], [zc + depth / 2 + curve * 0.4, top - len * 0.5, zc + depth / 2 + curve, top - len], pts[3], [zc - depth / 2 + curve * 0.25, top - len * 0.5, zc - depth / 2, top]], w || 0.022, 0.003, 8)]; + } + + // ------------------------------------------------------------------ designs + var B = {}; + // compact striker pistol: polymer frame with a raked grip and accessory rail, steel slide with rear serrations + B.corsa = function () { + var s = [], p = []; + s.push(prof([[-0.035, 0.028], [0.15, 0.028], [0.157, 0.036], [0.155, 0.058], [-0.03, 0.058], [-0.037, 0.05]], 0.027, 0.003)); + s.push.apply(s, serrations(6, -0.026, 0.0055, 0.043, 0.022, 0.029)); + s.push(box(0.012, 0.004, 0.035, 0, 0.059, 0.03)); // ejection port lip + s.push(tube(0.0062, 0.012, 0.15, 0.044, 10)); // barrel crown + s.push.apply(s, ironSights(0.145, -0.025, 0.058, 0.006)); + p.push(prof([[-0.04, 0.03], [0.14, 0.03], [0.145, 0.016], [0.08, 0.012], [0.04, 0.008], [0.026, -0.002], [0.012, -0.06], [0.006, -0.085], [-0.034, -0.088], [-0.03, -0.04], [-0.045, 0.018]], 0.025, 0.003)); + p.push.apply(p, triggerGuard(0.005, 0.05, 0.014, 0.022)); + for (var i = 0; i < 4; i++) p.push(box(0.0266, 0.003, 0.006, 0, 0.0115, 0.075 + i * 0.014)); // accessory rail ribs + for (i = 0; i < 4; i++) p.push(box(0.0262, 0.004, 0.006, 0, -0.03 - i * 0.012, 0.012 - i * 0.004)); // grip texture ribs + var mag = { steel: [box(0.02, 0.006, 0.03, 0, -0.088, -0.014)] }; + return make({ blued: s, poly: p }, { muzzle: [0, 0.044, 0.16], eject: [0.016, 0.06, 0.03], oneHand: true, mag: mag, len: 0.2 }); + }; + // big-frame revolver: fluted cylinder, full-lug barrel, wooden grip + B.bastion = function () { + var s = [], w = []; + s.push(prof([[-0.035, 0.018], [0.03, 0.018], [0.034, 0.028], [0.036, 0.062], [-0.02, 0.066], [-0.04, 0.05]], 0.028, 0.003)); + // fluted cylinder: a six-lobed cross-section extruded along the bore + var cs = new T.Shape(), n = 12; + for (var i = 0; i <= n * 4; i++) { var a = i / (n * 4) * Math.PI * 2, r = 0.021 - 0.003 * Math.pow(Math.max(0, Math.cos(a * 6)), 6); if (i === 0) cs.moveTo(Math.cos(a) * r, Math.sin(a) * r); else cs.lineTo(Math.cos(a) * r, Math.sin(a) * r); } + var cyl = new T.ExtrudeGeometry(cs, { depth: 0.042, bevelEnabled: true, bevelThickness: 0.002, bevelSize: 0.002, bevelSegments: 1 }); cyl.translate(0, 0, -0.012); cyl.translate(0, 0.04, 0); + s.push(cyl); + s.push(tube(0.0095, 0.16, 0.034, 0.05, 14), box(0.016, 0.014, 0.15, 0, 0.037, 0.11), box(0.006, 0.01, 0.14, 0, 0.062, 0.1)); + s.push(box(0.004, 0.012, 0.012, 0, 0.066, 0.186), box(0.007, 0.016, 0.012, 0, 0.068, -0.035)); // front sight, hammer + s.push.apply(s, triggerGuard(0.0, 0.04, 0.018, 0.02)); + w.push(prof([[-0.03, 0.02], [0.012, 0.02], [0.006, -0.06], [-0.002, -0.085], [-0.042, -0.08], [-0.046, -0.03], [-0.042, 0.01]], 0.032, 0.006)); + return make({ steel: s, wood: w }, { muzzle: [0, 0.05, 0.2], eject: [0.02, 0.05, 0.01], oneHand: true, len: 0.24 }); + }; + // compact SMG: round receiver, curved magazine, folding wire stock, short handguard + B.vespa = function () { + var s = [], p = []; + s.push(tube(0.022, 0.26, -0.06, 0.04, 16), tube(0.009, 0.06, 0.2, 0.045, 12), lathe([[0.012, 0], [0.013, 0.015], [0.011, 0.03], [0, 0.03]], 0.26, 0.045, 12)); + s.push(box(0.012, 0.012, 0.05, 0, 0.065, 0.02), box(0.004, 0.012, 0.006, 0, 0.066, 0.17), box(0.012, 0.014, 0.008, 0, 0.066, -0.04)); + s.push(tubeX(0.004, 0.05, 0.03, 0.05, 0.11, 8)); // cocking tube handle + s.push(box(0.006, 0.006, 0.2, 0.018, 0.02, -0.2), box(0.006, 0.006, 0.2, -0.018, 0.02, -0.2), box(0.042, 0.04, 0.008, 0, 0.0, -0.3)); // folding stock + p.push(pistolGrip(0.02, 0.25), prof([[0.09, 0.03], [0.2, 0.03], [0.2, 0.0], [0.09, 0.005]], 0.05, 0.005)); + p.push.apply(p, triggerGuard(0.02, 0.07, 0.02, 0.022)); + var mag = { steel: curvedMag(0.02, 0.1, 0.16, 0.03, 0.03, 0.02) }; + return make({ blued: s, poly: p }, { muzzle: [0, 0.045, 0.29], gripL: [0, 0.005, 0.15], eject: [0.025, 0.06, 0.05], mag: mag, len: 0.6 }); + }; + // carbine: flat-top receiver with a rail and a red dot, free-float slotted handguard, adjustable stock + B.tern = function () { + var s = [], p = [], g = []; + s.push(prof([[-0.1, 0.012], [0.16, 0.012], [0.165, 0.03], [0.16, 0.062], [-0.09, 0.062], [-0.105, 0.05]], 0.034, 0.003)); + s.push.apply(s, rail(0.24, -0.09, 0.062)); + s.push(tube(0.0075, 0.3, 0.16, 0.042, 12), lathe([[0.011, 0], [0.012, 0.01], [0.012, 0.045], [0.009, 0.05], [0, 0.05]], 0.46, 0.042, 12)); // barrel and flash hider + s.push(box(0.03, 0.012, 0.02, 0.0, 0.07, -0.08)); // charging handle + s.push(box(0.012, 0.016, 0.04, 0.02, 0.04, 0.02)); // ejection port cover + // handguard: slotted tube + p.push(tube(0.021, 0.27, 0.165, 0.043, 12)); + for (var z = 0.19; z < 0.42; z += 0.04) p.push(box(0.044, 0.008, 0.018, 0, 0.043, z)); + p.push.apply(p, rail(0.27, 0.165, 0.064)); + p.push(pistolGrip(0.012, 0.35)); + p.push.apply(p, triggerGuard(0.02, 0.08, 0.012, 0.02)); + // stock: buffer tube and an adjustable butt + s.push(tube(0.014, 0.2, -0.29, 0.042, 12)); + p.push(prof([[-0.33, 0.07], [-0.22, 0.062], [-0.2, 0.03], [-0.23, 0.002], [-0.33, -0.04], [-0.345, -0.035], [-0.345, 0.07]], 0.04, 0.006)); + g.push.apply(g, redDot(-0.03, 0.066)); + var mag = { poly: curvedMag(0.012, 0.045, 0.17, 0.034, 0.035, 0.024) }; + return make({ blued: s, poly: p, glass: g }, { muzzle: [0, 0.042, 0.51], gripL: [0, 0.018, 0.3], eject: [0.025, 0.045, 0.03], mag: mag, len: 0.86 }); + }; + // battle rifle: longer barrel, tan furniture, a low-power scope, muzzle brake + B.gale = function () { + var s = [], p = [], g = []; + s.push(prof([[-0.11, 0.008], [0.18, 0.008], [0.185, 0.03], [0.18, 0.066], [-0.1, 0.066], [-0.115, 0.05]], 0.038, 0.003)); + s.push.apply(s, rail(0.26, -0.1, 0.066)); + s.push(tube(0.0085, 0.36, 0.18, 0.042, 12), lathe([[0.012, 0], [0.014, 0.005], [0.014, 0.055], [0.01, 0.06], [0, 0.06]], 0.54, 0.042, 8)); + p.push(prof([[0.18, 0.068], [0.45, 0.064], [0.46, 0.04], [0.45, 0.012], [0.18, 0.008]], 0.05, 0.008)); + p.push(pistolGrip(0.008, 0.35)); + p.push.apply(p, triggerGuard(0.02, 0.085, 0.008, 0.022)); + p.push(prof([[-0.11, 0.066], [-0.4, 0.058], [-0.42, 0.06], [-0.42, -0.05], [-0.38, -0.05], [-0.2, -0.005], [-0.11, 0.01]], 0.042, 0.008)); + g.push.apply(g, scope(-0.1, 0.3, 0.11, 0.015)); + var mag = { tan: curvedMag(0.008, 0.05, 0.15, 0.04, 0.02, 0.026) }; + return make({ steel: s, tan: p, blued: g.slice(1), glass: g.slice(0, 1) }, { muzzle: [0, 0.042, 0.6], gripL: [0, 0.03, 0.32], eject: [0.025, 0.05, 0.03], mag: mag, len: 1.0 }); + }; + // pump shotgun: receiver, magazine tube, ribbed pump, wooden stock + B.breaker = function () { + var s = [], w = [], p = []; + s.push(prof([[-0.06, 0.012], [0.14, 0.012], [0.14, 0.066], [-0.04, 0.066], [-0.065, 0.05]], 0.036, 0.004)); + s.push(tube(0.011, 0.5, 0.14, 0.05, 14), tube(0.01, 0.42, 0.14, 0.022, 14), box(0.006, 0.004, 0.5, 0, 0.062, 0.39), box(0.006, 0.008, 0.008, 0, 0.066, 0.63)); + w.push(prof([[-0.05, 0.05], [-0.4, 0.035], [-0.41, 0.04], [-0.41, -0.07], [-0.37, -0.07], [-0.12, -0.03], [-0.06, 0.0], [-0.04, 0.015]], 0.04, 0.008)); + var pump = tube(0.021, 0.16, 0.22, 0.026, 14); w.push(pump); + for (var z = 0.23; z < 0.37; z += 0.02) p.push(tube(0.0225, 0.006, z, 0.026, 14)); + s.push.apply(s, triggerGuard(0.0, 0.06, 0.012, 0.022)); + return make({ blued: s, wood: w, rubber: p }, { muzzle: [0, 0.05, 0.64], gripL: [0, 0.008, 0.29], eject: [0.025, 0.05, 0.05], len: 1.05 }); + }; + // side-by-side shotgun + B.twinbore = function () { + var s = [], w = []; + s.push(prof([[-0.04, 0.015], [0.08, 0.015], [0.08, 0.07], [-0.03, 0.07], [-0.045, 0.05]], 0.05, 0.006)); + s.push(tube(0.013, 0.56, 0.08, 0.05, 14), tube(0.013, 0.56, 0.08, 0.05, 14), box(0.006, 0.006, 0.56, 0, 0.066, 0.36)); + s[1].translate(0.013, 0, 0); s[2].translate(-0.013, 0, 0); + w.push(prof([[-0.035, 0.05], [-0.4, 0.035], [-0.41, 0.04], [-0.41, -0.07], [-0.37, -0.07], [-0.12, -0.03], [-0.04, 0.0]], 0.042, 0.008)); + w.push(prof([[0.09, 0.04], [0.3, 0.04], [0.31, 0.025], [0.3, 0.015], [0.09, 0.015]], 0.042, 0.006)); + s.push.apply(s, triggerGuard(-0.01, 0.05, 0.015, 0.022)); + return make({ blued: s, wood: w }, { muzzle: [0, 0.05, 0.64], gripL: [0, 0.01, 0.2], eject: [0, 0.06, 0.07], len: 1.05 }); + }; + // bolt-action precision rifle: heavy barrel, high scope, bolt handle, folded bipod, thumbhole stock + B.longreach = function () { + var s = [], p = [], g = []; + s.push(tube(0.016, 0.2, -0.06, 0.045, 16), tube(0.0105, 0.56, 0.14, 0.045, 14), lathe([[0.014, 0], [0.016, 0.005], [0.016, 0.06], [0, 0.06]], 0.7, 0.045, 8)); + s.push(tubeX(0.005, 0.05, 0.03, 0.045, -0.02, 8), new T.SphereGeometry(0.009, 8, 6).translate(0.058, 0.04, -0.02)); // bolt handle and knob + s.push(box(0.006, 0.006, 0.16, 0.012, 0.0, 0.3), box(0.006, 0.006, 0.16, -0.012, 0.0, 0.3)); // bipod legs folded + p.push(prof([[-0.06, 0.035], [0.4, 0.03], [0.41, 0.012], [0.3, -0.005], [0.06, -0.01], [0.03, -0.03], [0.01, -0.085], [-0.035, -0.09], [-0.04, -0.03], [-0.07, -0.02], [-0.42, -0.05], [-0.44, -0.07], [-0.44, 0.06], [-0.4, 0.07], [-0.06, 0.06]], 0.05, 0.008)); + p.push.apply(p, triggerGuard(0.0, 0.05, -0.005, 0.02)); + g.push.apply(g, scope(-0.14, 0.38, 0.105, 0.019)); + var mag = { poly: [box(0.03, 0.04, 0.07, 0, -0.025, 0.07)] }; + return make({ steel: s, green: p, blued: g.slice(1), glass: g.slice(0, 1) }, { muzzle: [0, 0.045, 0.76], gripL: [0, 0.0, 0.3], eject: [0.025, 0.05, 0.0], mag: mag, len: 1.2 }); + }; + // light machine gun: heavy receiver, carry handle, box magazine, bipod, finned barrel + B.mauler = function () { + var s = [], p = [], g = []; + s.push(prof([[-0.12, 0.0], [0.2, 0.0], [0.21, 0.03], [0.2, 0.085], [-0.1, 0.085], [-0.125, 0.06]], 0.06, 0.004)); + s.push(tube(0.012, 0.45, 0.2, 0.045, 14)); + for (var z = 0.24; z < 0.4; z += 0.016) s.push(tube(0.017, 0.006, z, 0.045, 12)); + s.push(box(0.012, 0.03, 0.12, 0, 0.105, 0.05), box(0.04, 0.012, 0.12, 0, 0.12, 0.05)); + s.push(box(0.006, 0.006, 0.22, 0.016, 0.02, 0.48).rotateX(0), box(0.006, 0.006, 0.22, -0.016, 0.02, 0.48)); + p.push(pistolGrip(0.0, 0.3), prof([[-0.12, 0.08], [-0.42, 0.06], [-0.43, 0.06], [-0.43, -0.06], [-0.38, -0.06], [-0.18, -0.01], [-0.12, 0.0]], 0.05, 0.008)); + p.push.apply(p, triggerGuard(0.02, 0.085, 0.0, 0.022)); + var mag = { green: [box(0.09, 0.11, 0.12, 0.02, -0.05, 0.08)], brass: [box(0.004, 0.012, 0.09, 0.065, 0.03, 0.08)] }; + return make({ blued: s, poly: p }, { muzzle: [0, 0.045, 0.66], gripL: [0, 0.07, 0.1], eject: [-0.03, 0.03, 0.05], mag: mag, len: 1.1 }); + }; + // break-open grenade launcher + B.thumper = function () { + var s = [], p = []; + s.push(lathe([[0.0, 0], [0.034, 0], [0.036, 0.01], [0.036, 0.3], [0.03, 0.31], [0, 0.31]], 0.03, 0.06, 18), prof([[-0.06, 0.02], [0.06, 0.02], [0.06, 0.07], [-0.06, 0.07]], 0.05, 0.005)); + s.push.apply(s, ironSights(0.32, 0.0, 0.098, 0.016)); + p.push(pistolGrip(0.02, 0.3), prof([[-0.06, 0.06], [-0.35, 0.04], [-0.36, -0.06], [-0.3, -0.06], [-0.1, 0.0], [-0.06, 0.02]], 0.05, 0.008), tube(0.03, 0.1, 0.17, 0.015, 12)); + p.push.apply(p, triggerGuard(0.02, 0.07, 0.02, 0.022)); + return make({ steel: s, tan: p }, { muzzle: [0, 0.06, 0.34], gripL: [0, 0.0, 0.22], len: 0.7 }); + }; + // shoulder-fired rocket launcher: tube, sight box, two grips + B.hornet = function () { + var s = [], p = []; + s.push(lathe([[0.0, 0], [0.05, 0], [0.056, 0.03], [0.048, 0.07], [0.048, 0.86], [0.055, 0.9], [0.055, 0.96], [0, 0.96]], -0.42, 0.085, 18)); + p.push(pistolGrip(0.04, 0.2), box(0.03, 0.09, 0.035, 0, -0.005, 0.26), box(0.045, 0.06, 0.09, -0.06, 0.14, 0.05), box(0.12, 0.05, 0.03, 0, 0.12, -0.2)); + return make({ green: s, poly: p }, { muzzle: [0, 0.085, 0.54], gripL: [0, 0.0, 0.26], len: 1.0 }); + }; + // melee + B.knife = function () { + var bl = [prof([[0, 0.006], [0.1, 0.01], [0.13, 0.0], [0.1, -0.012], [0, -0.01]], 0.004, 0.0008)]; + var h = [prof([[-0.11, 0.012], [0.005, 0.012], [0.008, -0.013], [-0.11, -0.014], [-0.115, 0]], 0.016, 0.003)]; + return make({ blade: bl, poly: h }, { muzzle: [0, 0, 0.13], oneHand: true, len: 0.25 }); + }; + B.bat = function () { return make({ wood: [lathe([[0.0, -0.06], [0.026, -0.06], [0.016, -0.05], [0.014, 0.18], [0.03, 0.5], [0.034, 0.7], [0.03, 0.75], [0, 0.755]], 0, 0, 16)], rubber: [tube(0.0165, 0.2, -0.04, 0, 12)] }, { muzzle: [0, 0, 0.72], oneHand: true, len: 0.8 }); }; + B.crowbar = function () { + var g = tube(0.011, 0.62, -0.05, 0, 8); var hk = new T.TorusGeometry(0.04, 0.011, 6, 10, Math.PI); hk.rotateY(Math.PI / 2); hk.translate(0, 0.04, 0.57); + return make({ red: [g, hk] }, { muzzle: [0, 0.04, 0.6], oneHand: true, len: 0.68 }); + }; + B.hammer = function () { return make({ wood: [tube(0.014, 0.33, -0.05, 0, 10)], steel: [box(0.025, 0.1, 0.03, 0, 0.012, 0.29), tube(0.013, 0.04, 0.29, 0.06, 10).rotateX(0)] }, { muzzle: [0, 0.03, 0.3], oneHand: true, len: 0.35 }); }; + B.club = function () { return make({ alu: [tube(0.006, 0.82, 0.02, 0, 8), box(0.022, 0.045, 0.08, 0, -0.018, 0.86)], rubber: [tube(0.012, 0.24, -0.06, 0, 10)] }, { muzzle: [0, 0, 0.88], oneHand: true, len: 0.95 }); }; + B.machete = function () { + return make({ blade: [prof([[0.04, 0.012], [0.4, 0.024], [0.46, 0.01], [0.44, -0.02], [0.04, -0.015]], 0.004, 0.001)], grip: [prof([[-0.08, 0.014], [0.045, 0.016], [0.045, -0.016], [-0.08, -0.014], [-0.09, 0]], 0.024, 0.006)] }, { muzzle: [0, 0, 0.45], oneHand: true, len: 0.55 }); + }; + B.frag = function () { return make({ green: [new T.SphereGeometry(0.032, 12, 10).scale(1, 1.15, 1).translate(0, 0, 0.02)], steel: [box(0.012, 0.03, 0.014, 0, 0.042, 0.02), new T.TorusGeometry(0.01, 0.002, 4, 10).translate(0.012, 0.05, 0.02)] }, { muzzle: [0, 0, 0.04], oneHand: true, len: 0.08 }); }; + B.sticky = function () { return make({ yellow: [prof([[-0.03, 0.025], [0.06, 0.025], [0.06, -0.025], [-0.03, -0.025]], 0.06, 0.005)], poly: [box(0.03, 0.012, 0.03, 0, 0.03, 0.02)], red: [box(0.006, 0.006, 0.006, 0.01, 0.038, 0.02)] }, { muzzle: [0, 0, 0.06], oneHand: true, len: 0.1 }); }; + B.smoke = function () { return make({ alu: [tube(0.03, 0.12, -0.02, 0, 14)], steel: [box(0.01, 0.035, 0.012, 0, 0.035, 0.0)] }, { muzzle: [0, 0, 0.1], oneHand: true, len: 0.13 }); }; + + GM.build = function (id) { var f = B[id]; if (!f) return null; var g = f(); g.userData.id = id; g.userData.long = !g.userData.oneHand; return g; }; + GM.ids = Object.keys(B); +})(); diff --git a/e63334287a3deaa3/blacktie/js/heli.js b/e63334287a3deaa3/blacktie/js/heli.js new file mode 100644 index 00000000..356ef17f --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/heli.js @@ -0,0 +1,154 @@ +/* + * The alert helicopter (RP.Heli). At alert level 4 and above Halcyon sends a helicopter: it comes in from the sea, + * circles the player about 35 m out and 25 m up with a searchlight, and its door gunner fires bursts (a half-second + * tell first: the light snaps onto you). It only fires with a clear line to you, and misses more while you move. + * It can be shot down (it smokes when badly hit, then spins in and explodes); it leaves when the alert falls below 3. + * One helicopter at a time. Model made in code; no markings. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W; + var H = RP.Heli = { h: null, wait: 0 }; + var GUN = { name: 'Door gun', dmg: 9, range: [90, 220], minFrac: 0.6, snd: 'mg', cat: 'rifle' }; + + function build() { + var g = new T.Group(), std = function (hex, r, m) { return new T.MeshStandardMaterial({ color: RP.col(hex), roughness: r, metalness: m || 0 }); }; + var hull = std('#20252c', 0.45, 0.5), dark = std('#111214', 0.6, 0.3), glass = new T.MeshPhysicalMaterial({ color: RP.col('#0e1a22'), roughness: 0.05, transparent: true, opacity: 0.7 }); + function add(geo, mat, x, y, z) { var m = new T.Mesh(geo, mat); m.position.set(x || 0, y || 0, z || 0); m.castShadow = true; g.add(m); return m; } + add(new T.SphereGeometry(1, 18, 12).scale(1.05, 1.15, 2.5), hull, 0, 0, 0); // cabin + add(new T.SphereGeometry(1, 16, 10, 0, Math.PI * 2, 0, Math.PI * 0.5).scale(0.98, 1.0, 1.5).rotateX(Math.PI / 2), glass, 0, 0.12, 1.25); // nose glazing + var boom = new T.CylinderGeometry(0.16, 0.42, 5.2, 10); boom.rotateX(Math.PI / 2); add(boom, hull, 0, 0.35, -4.4); + add(new T.BoxGeometry(0.08, 1.5, 0.9), hull, 0, 1.0, -6.7); // fin + add(new T.BoxGeometry(1.8, 0.06, 0.5), hull, 0, 0.4, -6.2); // tailplane + add(new T.CylinderGeometry(0.5, 0.6, 0.5, 10), hull, 0, 1.25, -0.2); // engine cowl + add(new T.CylinderGeometry(0.06, 0.06, 0.5, 6), dark, 0, 1.7, -0.2); + add(new T.BoxGeometry(0.02, 1.2, 1.3), dark, 1.06, -0.1, -0.2); // open door (dark) + [-1, 1].forEach(function (s) { + var sk = new T.CylinderGeometry(0.05, 0.05, 4.2, 6); sk.rotateX(Math.PI / 2); add(sk, dark, s * 1.05, -1.55, 0.1); + add(new T.CylinderGeometry(0.035, 0.035, 0.75, 5), dark, s * 0.9, -1.2, 0.9).rotation.z = s * 0.4; add(new T.CylinderGeometry(0.035, 0.035, 0.75, 5), dark, s * 0.9, -1.2, -0.8).rotation.z = s * 0.4; + }); + var rotor = new T.Group(); rotor.position.set(0, 1.95, -0.2); + for (var i = 0; i < 4; i++) { var b = new T.Mesh(new T.BoxGeometry(0.22, 0.03, 5.6), dark); b.position.set(Math.sin(i * Math.PI / 2) * 2.8, 0, Math.cos(i * Math.PI / 2) * 2.8); b.rotation.y = i * Math.PI / 2; rotor.add(b); } + var disc = new T.Mesh(new T.CircleGeometry(5.6, 24), new T.MeshBasicMaterial({ color: 0x101214, transparent: true, opacity: 0.13, side: T.DoubleSide, depthWrite: false })); disc.rotation.x = -Math.PI / 2; rotor.add(disc); + g.add(rotor); g.userData.rotor = rotor; + var tr = new T.Mesh(new T.BoxGeometry(0.03, 1.5, 0.12), dark); tr.position.set(0.12, 1.2, -6.75); g.add(tr); g.userData.tail = tr; + // searchlight: a lamp and a faint cone + var lamp = new T.Mesh(new T.SphereGeometry(0.18, 8, 6), new T.MeshBasicMaterial({ color: RP.col('#fff6da').multiplyScalar(4) })); lamp.position.set(0, -1.0, 1.4); g.add(lamp); + var cone = new T.Mesh(new T.ConeGeometry(1, 1, 16, 1, true), new T.MeshBasicMaterial({ color: RP.col('#fff1c4'), transparent: true, opacity: 0.07, side: T.DoubleSide, depthWrite: false, blending: T.AdditiveBlending })); + cone.geometry.translate(0, -0.5, 0); cone.geometry.rotateX(-Math.PI / 2); g.userData.cone = cone; g.userData.lamp = lamp; + return g; + } + + H.clear = function () { var h = H.h; if (h) { if (h.g.parent) h.g.parent.remove(h.g); if (h.cone.parent) h.cone.parent.remove(h.cone); var i = RP.G.ents.indexOf(h.ent); if (i >= 0) RP.G.ents.splice(i, 1); } H.h = null; H.wait = 0; stopSound(); }; + + function spawn(p) { + var g = build(), cone = g.userData.cone; + var a0 = Math.random() * 6.28, pos = new T.Vector3(p.pos.x + 40, p.pos.y + 60, p.pos.z + 220); // from over the sea + g.position.copy(pos); RP.R.scene.add(g); RP.R.scene.add(cone); + var h = H.h = { g: g, cone: cone, pos: pos, vel: new T.Vector3(), yaw: Math.PI, ang: a0, dirn: Math.random() < 0.5 ? 1 : -1, hp: 520, maxHp: 520, state: 'in', t: 0, fireT: 4, burst: 0, tell: 0, flipT: 6, smokeT: 0, light: 0 }; + h.ent = { heli: true, pos: pos, team: 'guard', alive: true, radius: 3, actor: null, hitMat: 'metal', hitSphere: { c: pos, r: 2.4 }, + takeDamage: function (amt, info) { if (!h.ent.alive) return; h.hp -= amt * (info && info.weapon && info.weapon.cat === 'heavy' ? 2.5 : 1); if (info && info.point) RP.FX.sparks(info.point.x, info.point.y, info.point.z, 0, -1, 0, 5); if (h.hp <= 0) down(h); } }; + RP.G.ents.push(h.ent); + RP.emit('sub', 'Radio: Air unit inbound. Keep him pinned.', 3); + startSound(); + } + function down(h) { + h.ent.alive = false; h.state = 'down'; h.t = 0; h.spin = (Math.random() < 0.5 ? 1 : -1) * 3.5; + RP.emit('sub', 'Radio: We have lost the air unit!', 3); RP.emit('hitmark', 'kill'); + if (RP.G.player) RP.G.player.kills++; + } + + var _to = new T.Vector3(), _mz = new T.Vector3(), _d = new T.Vector3(), _q = new T.Quaternion(); + H.update = function (dt) { + var p = RP.G.player, AL = RP.Alert, h = H.h; + if (!p) return; + if (!h) { + if (AL.enabled && AL.level >= 4 && p.alive) { H.wait += dt; if (H.wait > 7) spawn(p); } else H.wait = 0; + return; + } + h.t += dt; + var g = h.g; + if (h.state === 'down') { + // spin in, trailing smoke, and blow up where it lands + h.vel.y -= 9 * dt; h.vel.x *= 0.99; h.vel.z *= 0.99; h.pos.addScaledVector(h.vel, dt); h.yaw += h.spin * dt; + h.smokeT -= dt; if (h.smokeT <= 0) { h.smokeT = 0.05; RP.FX.dust(h.pos.x, h.pos.y + 1, h.pos.z, 0, 1, 0, '#2a2a2a', 2, 1.6, 1.5); } + var gy = Math.max(W.ground(h.pos.x, h.pos.z, h.pos.y + 2).y, W.water); + if (h.pos.y - 1.5 <= gy || h.t > 9) { RP.Combat.explode(h.pos.clone().setY(gy + 0.5), 9, 160, null); RP.Cam.shake(0.8); H.clear(); H.wait = -45; return; } // the next one takes a while + } else { + var leaving = h.state === 'out' || !AL.enabled || AL.level < 3 || !p.alive; + if (leaving && h.state !== 'out') { h.state = 'out'; h.t = 0; RP.emit('sub', 'Radio: Air unit breaking off.', 3); } + if (h.state === 'out') { _to.set(h.pos.x + 30, h.pos.y + 25, h.pos.z + 200); if (h.t > 14) { H.clear(); return; } } + else { + // orbit: a point on a circle round the player, well above the ground under the helicopter + h.flipT -= dt; if (h.flipT <= 0) { h.flipT = 7 + Math.random() * 8; h.dirn *= -1; } + h.ang += h.dirn * 0.24 * dt; + // (round where the player will be in a second: a car is paced alongside rather than left behind) + var R = 34, lead = p.vehicle ? 1.1 : 0.4, tx = p.pos.x + (p.vel ? p.vel.x * lead : 0) + Math.cos(h.ang) * R, tz = p.pos.z + (p.vel ? p.vel.z * lead : 0) + Math.sin(h.ang) * R; + var floor = Math.max(W.ground(h.pos.x, h.pos.z, 500).y, W.ground(tx, tz, 500).y, p.pos.y); + _to.set(tx, Math.max(p.pos.y + 24, floor + 14), tz); + if (h.state === 'in' && h.pos.distanceTo(_to) < 25) h.state = 'orbit'; + } + // fly: accelerate toward the target point, with drag (a heavy machine) + _d.subVectors(_to, h.pos); var dist = _d.length(); _d.normalize(); + var want = Math.min(h.state === 'orbit' && dist < 30 ? 12 : 30, dist * 0.9); // slow round its circle, fast to catch up + h.vel.x += (_d.x * want - h.vel.x) * Math.min(1, dt * 0.9); h.vel.y += (_d.y * want - h.vel.y) * Math.min(1, dt * 1.2); h.vel.z += (_d.z * want - h.vel.z) * Math.min(1, dt * 0.9); + h.pos.addScaledVector(h.vel, dt); + // nose: along the flight when travelling, broadside to the player when orbiting (the gunner's door is on its left) + var wy = h.state === 'orbit' ? Math.atan2(p.pos.x - h.pos.x, p.pos.z - h.pos.z) - Math.PI / 2 : Math.atan2(h.vel.x, h.vel.z); + h.yaw = M.dampAngle(h.yaw, wy, 1.6, dt); + if (h.hp < h.maxHp * 0.35) { h.smokeT -= dt; if (h.smokeT <= 0) { h.smokeT = 0.12; RP.FX.dust(h.pos.x, h.pos.y + 1.2, h.pos.z - 0.5, 0, 1, 0, '#3a3a3a', 1, 1.2, 1); } } + if (h.state === 'orbit') gunner(h, p, dt); + } + var sp = Math.hypot(h.vel.x, h.vel.z); + g.position.copy(h.pos); g.rotation.set(Math.min(0.3, sp * 0.012), h.yaw, h.state === 'down' ? Math.sin(h.t * 3) * 0.5 : M.clamp(-h.dirn * sp * 0.012, -0.25, 0.25), 'YXZ'); + g.userData.rotor.rotation.y += dt * 38; g.userData.tail.rotation.x += dt * 60; + // searchlight cone from the lamp to the player + var cone = h.cone, lit = h.state === 'orbit' || h.state === 'in'; + cone.visible = lit && RP.G.night !== false; + if (cone.visible) { + g.updateMatrixWorld(true); g.userData.lamp.getWorldPosition(_mz); + _d.set(p.pos.x, p.pos.y + 1, p.pos.z).sub(_mz); var L = _d.length(); + cone.position.copy(_mz); cone.quaternion.setFromUnitVectors(new T.Vector3(0, 0, 1), _d.normalize()); + var wdt = h.tell > 0 ? 2.2 : 4.5; cone.scale.set(wdt, wdt, L); cone.material.opacity = h.tell > 0 ? 0.16 : 0.06; + } + sound(h, p); + }; + function gunner(h, p, dt) { + h.fireT -= dt; + h.g.updateMatrixWorld(true); _mz.set(1.1, -0.2, -0.2).applyMatrix4(h.g.matrixWorld); + var tx = p.pos.x, ty = p.pos.y + 1.1, tz = p.pos.z; + var los = W.los(_mz.x, _mz.y, _mz.z, tx, ty, tz); + if (h.burst > 0) { + h.shotT -= dt; + if (h.shotT <= 0) { + h.shotT = 0.1; h.burst--; + _d.set(tx, ty, tz).sub(_mz).normalize(); + // misses more while you move, in cover, or when it has only just seen you + var spread = 1.6 + Math.min(5, p.speed * 0.55) + (p.state === 'cover' ? 2.5 : 0) + (p.vehicle ? Math.min(4, Math.abs(p.vehicle.v) * 0.2) : 0); + RP.Combat.fire(h.ent, _mz.clone(), _d.clone(), GUN, { spread: spread * ({ easy: 1.5, normal: 1, hard: 0.75 }[RP.settings.difficulty] || 1) }); + RP.FX.muzzle(_mz, _d, false); RP.Audio.shot('mg', _mz.clone()); + } + if (h.burst === 0) h.fireT = 2.6 + Math.random() * 1.8; + } else if (h.tell > 0) { + h.tell -= dt; if (h.tell <= 0) { if (los) { h.burst = 6 + Math.floor(Math.random() * 3); h.shotT = 0; } else h.fireT = 1; } + } else if (h.fireT <= 0 && los && p.alive) { h.tell = 0.55; RP.Audio.ui && RP.Audio.ui('tick'); if (RP.Alert.seen) RP.Alert.seen(p.pos); } + } + + // rotor sound: a low thudding tone whose loudness falls with distance + var snd = null; + function startSound() { + var ctx = RP.Audio && RP.Audio.ctx; if (!ctx || snd) return; + try { + var o = ctx.createOscillator(), lfo = ctx.createOscillator(), lg = ctx.createGain(), lp = ctx.createBiquadFilter(), g = ctx.createGain(); + o.type = 'sawtooth'; o.frequency.value = 62; lfo.type = 'square'; lfo.frequency.value = 19; lg.gain.value = 0.5; lp.type = 'lowpass'; lp.frequency.value = 380; g.gain.value = 0; + var am = ctx.createGain(); am.gain.value = 0.5; lfo.connect(lg); lg.connect(am.gain); o.connect(am); am.connect(lp); lp.connect(g); g.connect(ctx.destination); o.start(); lfo.start(); + snd = { o: o, lfo: lfo, g: g }; + } catch (e) { snd = null; } + } + function stopSound() { if (!snd) return; try { snd.g.gain.setTargetAtTime(0, RP.Audio.ctx.currentTime, 0.3); var s = snd; setTimeout(function () { try { s.o.stop(); s.lfo.stop(); } catch (e) {} }, 1200); } catch (e) {} snd = null; } + function sound(h, p) { + if (!snd) return; + var d = h.pos.distanceTo(p.pos), vol = (RP.settings.volume == null ? 1 : RP.settings.volume) * M.clamp(1 - d / 260, 0, 1) * 0.16; + snd.g.gain.setTargetAtTime(vol, RP.Audio.ctx.currentTime, 0.2); + } +})(); diff --git a/e63334287a3deaa3/blacktie/js/hud.js b/e63334287a3deaa3/blacktie/js/hud.js new file mode 100644 index 00000000..71929f10 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/hud.js @@ -0,0 +1,233 @@ +/* + * HUD (RP.HUD): crosshair (spread, hit markers, red over a target), health and armour bars, the minimap (turns with + * the camera; guards that are alerted show red, the search circle when the alert level is up, objective marker), + * alert level pips, weapon and ammo, prompts, mission text, subtitles, damage direction arcs and the weapon wheel. + * Everything but the minimap and mission text fades when out of combat for a few seconds. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, WP = RP.Weapons; + var H = RP.HUD = { fade: 1, lastAction: 0, subs: [], toastT: 0 }; + var $ = function (id) { return document.getElementById(id); }; + + H.init = function () { + H.el = { hud: $('hud'), cross: $('cross'), hit: $('hitmark'), hp: $('hpFill'), ar: $('arFill'), alert: $('alert'), wname: $('wName'), ammo: $('wAmmo'), thr: $('wThrow'), + obj: $('objective'), prompt: $('prompt'), sub: $('subs'), toast: $('toast'), dmg: $('dmgDir'), wheel: $('wheel'), mm: $('minimap'), stam: $('stamina'), stealth: $('stealthTag'), aware: $('aware') }; + H.mmCtx = H.el.mm.getContext('2d'); + RP.on('hitmark', function (k) { H.el.hit.className = 'on ' + k; clearTimeout(H._hm); H._hm = setTimeout(function () { H.el.hit.className = ''; }, k === 'kill' ? 260 : 140); RP.Audio.ui(k === 'kill' ? 'kill' : 'hit'); H.lastAction = RP.G.time; }); + RP.on('sub', function (text, dur) { H.subs.push({ text: text, t: dur || 2.5 }); if (H.subs.length > 3) H.subs.shift(); renderSubs(); }); + RP.on('toast', function (text) { H.el.toast.textContent = text; H.el.toast.classList.add('on'); H.toastT = 2.2; }); + RP.on('hurt', function (p, info) { + H.lastAction = RP.G.time; + if (info && info.from && info.from.pos) { var a = Math.atan2(info.from.pos.x - p.pos.x, info.from.pos.z - p.pos.z) - RP.Cam.yaw; H.dmgArc(a); } + }); + RP.on('shot', function () { H.lastAction = RP.G.time; }); + RP.on('alert', function (l) { renderAlert(l); }); + H.buildWheel(); + }; + function renderSubs() { H.el.sub.innerHTML = H.subs.map(function (s) { return '
' + esc(s.text) + '
'; }).join(''); } + function esc(s) { return String(s).replace(/[&<>]/g, function (c) { return { '&': '&', '<': '<', '>': '>' }[c]; }); } + function renderAlert(l) { + var h = ''; + for (var i = 1; i <= 5; i++) h += ''; + H.el.alert.innerHTML = 'ALERT' + h; + H.el.alert.classList.toggle('hot', l > 0); + } + H.dmgArc = function (a) { + var d = document.createElement('div'); d.className = 'arc'; d.style.transform = 'rotate(' + (-a * 180 / Math.PI) + 'deg)'; + H.el.dmg.appendChild(d); setTimeout(function () { d.remove(); }, 900); + }; + H.objective = function (text, sub) { H.el.obj.innerHTML = text ? '' + esc(text) + '' + (sub ? '' + esc(sub) + '' : '') : ''; H.el.obj.classList.toggle('on', !!text); }; + + // ------------------------------------------------------------------ weapon wheel + H.buildWheel = function () { + var w = H.el.wheel, html = '
'; + WP.CATS.forEach(function (c, i) { + var a = (i / 8) * 360 - 90; + html += ''; + }); + html += ''; + w.innerHTML = html; + w.querySelector('#wDrop').addEventListener('click', function (e) { + e.stopPropagation(); var p = RP.G.player, id = H.wheelPick[H.wheelSel]; + if (p && id && H.wheelSel !== 'melee' || p && id && id !== 'fists') { H.closeWheel(false); RP.Items.playerDrop(p, id); } + }); + w.querySelectorAll('.wslot').forEach(function (b) { + b.addEventListener('click', function () { H.wheelSel = b.getAttribute('data-cat'); H.closeWheel(true); }); + b.addEventListener('mouseenter', function () { if (!RP.In.locked) H.wheelSel = b.getAttribute('data-cat'); }); + }); + H.wheelPick = {}; // remembered weapon per category + }; + H.openWheel = function (p) { + if (H.wheelOn) return; + H.wheelOn = true; p.wheelOpen = true; H.wheelVec = { x: 0, y: 0 }; + var cat = WP.DEFS[p.cur].cat; H.wheelSel = cat; H.wheelPick[cat] = p.cur; + H.el.wheel.classList.add('on'); RP.G.scale = 0.25; RP.Audio.ui('tick'); + H.renderWheel(p); + }; + H.closeWheel = function (apply) { + if (!H.wheelOn) return; + var p = RP.G.player; + H.wheelOn = false; p.wheelOpen = false; H.el.wheel.classList.remove('on'); RP.G.scale = 1; + if (apply && H.wheelSel) { + var id = H.wheelPick[H.wheelSel] || owned(p, H.wheelSel)[0]; + if (id) { if (H.wheelSel === 'throw') { p.throwId = id; RP.emit('toast', WP.DEFS[id].name + ' ready (G)'); } else RP.Player.equip(p, id); } + } + }; + function owned(p, cat) { return WP.byCat(cat).filter(function (id) { return p.inv[id] && (cat !== 'throw' || p.inv[id].reserve > 0 || true); }); } + H.stepWheel = function (p) { + var I = RP.In; + if (I.pressed('wheel')) { if (RP.touch && H.wheelOn) H.closeWheel(false); else H.openWheel(p); } + if (!H.wheelOn) return; + if (!RP.touch && I.released('wheel')) { H.closeWheel(true); return; } + // pick by pointer/stick direction + var v = H.wheelVec; + v.x += I.look.x * 18; v.y += I.look.y * 18; + if (Math.abs(I.move.x) + Math.abs(I.move.y) > 0.5 && I.pad) { v.x = I.move.x; v.y = -I.move.y; } + var L = Math.hypot(v.x, v.y); + if (L > 1) { v.x /= L; v.y /= L; } + if (L > 0.5) { + var a = Math.atan2(v.y, v.x) * 180 / Math.PI + 90; a = (a + 360 + 22.5) % 360; + var sel = WP.CATS[Math.floor(a / 45) % 8]; + if (sel !== H.wheelSel) { H.wheelSel = sel; RP.Audio.ui('tick'); } + } + // scroll cycles inside the category + if (I.wheel) { + var list = owned(p, H.wheelSel); if (list.length) { var i = list.indexOf(H.wheelPick[H.wheelSel]); H.wheelPick[H.wheelSel] = list[(i + (I.wheel > 0 ? 1 : -1) + list.length) % list.length]; RP.Audio.ui('tick'); } + } + H.renderWheel(p); + }; + H.renderWheel = function (p) { + H.el.wheel.querySelectorAll('.wslot').forEach(function (b) { + var cat = b.getAttribute('data-cat'), list = owned(p, cat); + if (!H.wheelPick[cat] || list.indexOf(H.wheelPick[cat]) < 0) H.wheelPick[cat] = cat === 'throw' ? p.throwId : list[0]; + var id = H.wheelPick[cat], d = id && WP.DEFS[id]; + b.classList.toggle('sel', cat === H.wheelSel); b.classList.toggle('empty', !list.length); + b.querySelector('.witem').textContent = d ? d.name + (list.length > 1 ? ' (' + (list.indexOf(id) + 1) + '/' + list.length + ')' : '') : '—'; + var inv = id && p.inv[id]; + b.querySelector('.wammo').textContent = !d ? '' : d.melee ? '' : d.cat === 'throw' ? 'x' + (inv ? inv.reserve : 0) : (inv ? inv.mag + ' / ' + inv.reserve : ''); + }); + var sel = H.wheelPick[H.wheelSel], d = sel && WP.DEFS[sel], c = $('wCenter'); + if (!d) { c.innerHTML = ''; return; } + var bars = d.melee ? [['Damage', d.dmg / 50], ['Reach', d.reach / 1.8], ['Speed', d.speed / 1.3]] : d.cat === 'throw' ? [['Damage', d.dmg / 160], ['Radius', d.radius / 7]] : + [['Damage', Math.min(1, d.dmg * (d.pellets || 1) / 120)], ['Fire rate', Math.min(1, d.rpm / 850)], ['Accuracy', 1 - Math.min(1, d.spread[1] / 5)], ['Range', Math.min(1, (d.range[1] || 120) / 250)]]; + c.innerHTML = '' + esc(d.name) + '' + bars.map(function (b) { return '
' + b[0] + '
'; }).join(''); + }; + + // ------------------------------------------------------------------ per frame + H.update = function (dt, p) { + var e = H.el, d = RP.Player.def(p), inv = p.inv[p.cur]; + // fade out of combat + var active = RP.G.time - H.lastAction < 6 || p.aiming || RP.Alert.level > 0 || p.hp < 60 || H.wheelOn; + H.fade = M.approach(H.fade, active ? 1 : 0.18, active ? 4 : 0.6, dt); + e.hud.style.setProperty('--fade', H.fade.toFixed(2)); + // crosshair: shown when aiming or firing; gap from the current spread + var showX = (p.aiming || p.hipT > 0.6 || (p.cover && p.cover.blind)) && !d.melee && !RP.Cam.scoped && p.alive; + var spread = d.spread ? M.lerp(d.spread[0], d.spread[1], p.aimW) + p.bloom + Math.min(1.5, p.speed * 0.35) * (1 - p.aimW * 0.6) : 1; + var gap = Math.max(3, spread / RP.Cam.fov * window.innerHeight * 0.9); + e.cross.style.setProperty('--gap', gap.toFixed(1) + 'px'); + e.cross.className = (showX ? 'on' : '') + (d.melee || !showX ? ' dot' : '') + (H.overEnemy ? ' enemy' : '') + (RP.Cam.lock ? ' lock' : '') + (H.blocked && showX ? ' blocked' : ''); + document.body.classList.toggle('scoped', !!RP.Cam.scoped); + // bars + e.hp.style.width = (p.hp / RP.TUNING.maxHealth * 100).toFixed(1) + '%'; + e.hp.parentNode.classList.toggle('low', p.hp < 35); + e.ar.style.width = (p.armour / RP.TUNING.maxArmour * 100).toFixed(1) + '%'; + e.stam.style.width = (p.stamina * 100).toFixed(0) + '%'; e.stam.parentNode.classList.toggle('on', p.stamina < 0.98); + // weapon + e.wname.textContent = d.name; + e.ammo.innerHTML = d.melee ? '' : '' + inv.mag + ' / ' + inv.reserve + (p.reload ? ' reloading' : ''); + var t = WP.DEFS[p.throwId], ti = p.inv[p.throwId]; + e.thr.textContent = t && ti ? t.name + ' x' + ti.reserve : ''; + e.stealth.classList.toggle('on', p.stealth); + // prompts + var pr = ''; + if (p.tdTarget) pr = keyName('fire') + ' Takedown'; + else if (H.interact) pr = keyName('interact') + ' ' + H.interact; + else if (p.state === 'cover') pr = keyName('cover') + ' Leave cover' + (p.cover && p.cover.low ? ' · ' + keyName('jump') + ' Vault' : ''); + e.prompt.textContent = pr; e.prompt.classList.toggle('on', !!pr); + // nearest suspicious guard: an awareness pointer + var aw = 0; RP.G.guards.forEach(function (g) { if (g.alive && g.state !== 'combat') aw = Math.max(aw, g.aware); }); + e.aware.style.opacity = aw > 0.05 && RP.Alert.level === 0 ? Math.min(1, aw * 1.4) : 0; + e.aware.style.setProperty('--k', Math.min(1, aw).toFixed(2)); + // subtitles + var ch = false; + for (var i = H.subs.length - 1; i >= 0; i--) { H.subs[i].t -= dt; if (H.subs[i].t <= 0) { H.subs.splice(i, 1); ch = true; } } + if (ch) renderSubs(); + if (H.toastT > 0) { H.toastT -= dt; if (H.toastT <= 0) e.toast.classList.remove('on'); } + // what's under the crosshair (for the red reticle) + H._xt = (H._xt || 0) + dt; + if (showX && H._xt > 0.1) { + H._xt = 0; var r = RP.Cam.aimRay(), hit = RP.Combat.hitEnts(r.o, r.dir, 150, p); + H.overEnemy = !!(hit && hit.ent.team === 'guard' && hit.ent.alive && RP.W.los(r.o.x, r.o.y, r.o.z, hit.point.x, hit.point.y, hit.point.z)); + // the gun can't see what the camera sees (a wall edge or the step in front of the muzzle): grey it out with an x, + // since the shot would hit that instead (bullets go from the muzzle to the point under the crosshair) + H.blocked = false; + if (p.model && p.model.userData.muzzle && !d.proj) { + var ap = RP.Cam.aimPoint(r, 300), mz = p.model.userData.muzzle.getWorldPosition(_mz), L = ap.distanceTo(mz); + if (L > 1.5) { var dv = _md.subVectors(ap, mz).divideScalar(L), wh = RP.W.ray(mz.x, mz.y, mz.z, dv.x, dv.y, dv.z, L - 0.6, { noWater: true }); H.blocked = !!(wh && wh.t < 40); } + } + } + drawMinimap(p); + }; + var _mz = new THREE.Vector3(), _md = new THREE.Vector3(); + function keyName(a) { + if (RP.In.lastDevice === 'touch') return ''; + if (RP.In.lastDevice === 'pad') return { fire: '[RT]', interact: '[Y]', cover: '[RB]', jump: '[A]' }[a] || ''; + return { fire: '[Click]', interact: '[E]', cover: '[Q]', jump: '[Space]' }[a] || ''; + } + + // ------------------------------------------------------------------ minimap + function drawMinimap(p) { + var c = H.mmCtx, cv = H.el.mm, S = cv.width, mm = RP.map.minimap; if (!mm) return; + var scale = S / 110; // 110 m across + c.save(); c.clearRect(0, 0, S, S); + c.beginPath(); c.arc(S / 2, S / 2, S / 2 - 1, 0, 6.283); c.clip(); + c.fillStyle = '#1f4a66'; c.fillRect(0, 0, S, S); + c.translate(S / 2, S / 2); + c.rotate(RP.Cam.yaw + Math.PI); // camera forward = up + var px = (p.pos.x - mm.x0) / mm.w * mm.canvas.width, pz = (p.pos.z - mm.z0) / mm.h * mm.canvas.height; + var k = scale * mm.w / mm.canvas.width; + c.scale(-k, k); + c.drawImage(mm.canvas, -px, -pz); + c.restore(); c.save(); + c.beginPath(); c.arc(S / 2, S / 2, S / 2 - 1, 0, 6.283); c.clip(); + function toMM(x, z) { + var dx = x - p.pos.x, dz = z - p.pos.z, cy = Math.cos(RP.Cam.yaw), sy = Math.sin(RP.Cam.yaw); + // camera forward (sin yaw, cos yaw) maps to up (-y); camera right maps to +x + var f = dx * sy + dz * cy, r = -(dx * cy) + dz * sy; + return [S / 2 + r * scale, S / 2 - f * scale]; + } + // search circle + if (RP.Alert.level > 0 && RP.Alert.searchCentre) { + var sc = toMM(RP.Alert.searchCentre.x, RP.Alert.searchCentre.z); + c.fillStyle = 'rgba(214,58,50,0.18)'; c.strokeStyle = 'rgba(232,80,70,0.7)'; c.lineWidth = 1.5; + c.beginPath(); c.arc(sc[0], sc[1], RP.Alert.searchR * scale, 0, 6.283); c.fill(); c.stroke(); + } + // objective + var ob = RP.G.objPos; + if (ob) { + var o = toMM(ob.x, ob.z), dx = o[0] - S / 2, dy = o[1] - S / 2, L = Math.hypot(dx, dy), R = S / 2 - 8; + if (L > R) { o[0] = S / 2 + dx / L * R; o[1] = S / 2 + dy / L * R; } + c.fillStyle = '#f2c14e'; c.strokeStyle = '#1c1a14'; c.lineWidth = 2; + c.beginPath(); c.moveTo(o[0], o[1] - 7); c.lineTo(o[0] + 6, o[1]); c.lineTo(o[0], o[1] + 7); c.lineTo(o[0] - 6, o[1]); c.closePath(); c.stroke(); c.fill(); + } + // hostiles: red when alerted, grey when calm (only when near or alerted), civilians faint + RP.G.guards.forEach(function (g) { + if (!g.alive) return; var q = toMM(g.pos.x, g.pos.z); + var calm = g.state !== 'combat'; + if (calm && g.pos.distanceTo(p.pos) > 45) return; + c.fillStyle = calm ? (g.state === 'suspicious' ? '#e8c547' : 'rgba(230,226,214,0.8)') : '#e04a3c'; + c.beginPath(); c.arc(q[0], q[1], 3.6, 0, 6.283); c.fill(); + if (calm) { c.strokeStyle = c.fillStyle; c.beginPath(); var vy = g.yaw - RP.Cam.yaw; c.moveTo(q[0], q[1]); c.lineTo(q[0] - Math.sin(vy) * 9, q[1] - Math.cos(vy) * 9); c.stroke(); } + }); + // the player arrow + c.translate(S / 2, S / 2); c.rotate(-(p.yaw - RP.Cam.yaw)); + c.fillStyle = '#ffffff'; c.strokeStyle = '#000'; c.lineWidth = 1.5; + c.beginPath(); c.moveTo(0, -7); c.lineTo(5, 6); c.lineTo(0, 3); c.lineTo(-5, 6); c.closePath(); c.stroke(); c.fill(); + c.restore(); + // north tick + var nA = RP.Cam.yaw + Math.PI; + c.fillStyle = '#e8e2d2'; c.font = '600 11px system-ui'; c.textAlign = 'center'; + c.fillText('N', S / 2 + Math.sin(nA) * (S / 2 - 9) * -1, S / 2 - Math.cos(nA) * (S / 2 - 9) + 4); + } +})(); diff --git a/e63334287a3deaa3/blacktie/js/input.js b/e63334287a3deaa3/blacktie/js/input.js new file mode 100644 index 00000000..29d656a7 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/input.js @@ -0,0 +1,141 @@ +/* + * Input (RP.In): keyboard + mouse (pointer lock), gamepad, and on-screen touch controls, all mapped onto the same + * actions. Game code reads RP.In.move (x right, y forward, length <= 1), RP.In.look (radians this frame), + * RP.In.down(a), RP.In.pressed(a) (went down this frame), RP.In.released(a), RP.In.wheelDelta. + * + * Actions: aim fire sprint jump stealth cover reload wheel camera throw interact prev pause melee + * Keys: WASD move, mouse look, Shift sprint, Space jump/vault/dodge (with aim + direction: roll), Left Ctrl stealth, + * RMB aim, LMB fire, Q cover, R reload (melee when there's nothing to reload), Tab weapon wheel, V camera, + * G throw, E interact, X previous weapon, Esc pause. F is kept for vehicles (phase 2). + */ +(function () { + 'use strict'; + var I = RP.In = { move: { x: 0, y: 0 }, look: { x: 0, y: 0 }, wheelDelta: 0, mouseDX: 0, mouseDY: 0, locked: false, pad: false, lastDevice: 'kbm' }; + var KEYS = { + KeyW: 'up', KeyS: 'down', KeyA: 'left', KeyD: 'right', ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right', + ShiftLeft: 'sprint', ShiftRight: 'sprint', Space: 'jump', ControlLeft: 'stealth', KeyC: 'stealth', KeyQ: 'cover', KeyR: 'reload', Tab: 'wheel', + KeyV: 'camera', KeyG: 'throw', KeyE: 'interact', KeyX: 'prev', Escape: 'pause', KeyP: 'pause', KeyF: 'enter', KeyB: 'drop', KeyT: 'melee', AltLeft: 'walk', KeyZ: 'walk' + }; + var state = {}, prev = {}, now = {}; + function set(a, v) { state[a] = v; } + I.down = function (a) { return !!now[a]; }; + // edges are latched until a simulation step has run (RP.In.clearEdges), so a quick tap on a frame with no step isn't lost + var edgeP = {}, edgeR = {}; + I.pressed = function (a) { return !!edgeP[a]; }; + I.released = function (a) { return !!edgeR[a]; }; + I.clearEdges = function () { edgeP = {}; edgeR = {}; }; + I.consume = function (a) { prev[a] = now[a]; }; + + I.init = function (canvas) { + I.canvas = canvas; + window.addEventListener('keydown', function (e) { + var a = KEYS[e.code]; if (!a) return; + if (RP.G.paused && a !== 'pause') return; + if (e.code === 'Tab' || e.code === 'Space' || /Arrow/.test(e.code) || e.code === 'ControlLeft') e.preventDefault(); + set(a, true); I.lastDevice = 'kbm'; + }); + window.addEventListener('keyup', function (e) { var a = KEYS[e.code]; if (a) set(a, false); }); + window.addEventListener('blur', function () { state = {}; }); + canvas.addEventListener('mousedown', function (e) { + if (RP.touch && e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents) return; + if (!I.locked && !RP.G.paused && !RP.test) { canvas.requestPointerLock && canvas.requestPointerLock(); } + if (e.button === 0) set('fire', true); if (e.button === 2) set('aim', true); if (e.button === 1) set('camera', true); + I.lastDevice = 'kbm'; + }); + window.addEventListener('mouseup', function (e) { if (e.button === 0) set('fire', false); if (e.button === 2) set('aim', false); if (e.button === 1) set('camera', false); }); + canvas.addEventListener('contextmenu', function (e) { e.preventDefault(); }); + window.addEventListener('mousemove', function (e) { if (I.locked || RP.test) { I.mouseDX += e.movementX || 0; I.mouseDY += e.movementY || 0; } }); + window.addEventListener('wheel', function (e) { I.wheelDelta += Math.sign(e.deltaY); }, { passive: true }); + document.addEventListener('pointerlockchange', function () { I.locked = document.pointerLockElement === canvas; if (!I.locked && !RP.G.paused && RP.G.running && !RP.test) RP.emit('wantPause'); }); + if (RP.touch) initTouch(); + }; + + // ------------------------------------------------------------------ touch: a move stick on the left, camera drag on the right, buttons + var touch = { stick: null, look: null, btn: {} }; + function initTouch() { + var tl = document.getElementById('touch'); if (!tl) return; + var stickEl = document.getElementById('tStick'), knob = document.getElementById('tKnob'); + tl.addEventListener('touchstart', function (e) { + for (var i = 0; i < e.changedTouches.length; i++) { + var t = e.changedTouches[i], el = t.target, b = el.closest && el.closest('[data-act]'); + if (b) { + var act = b.getAttribute('data-act'); + if (b.hasAttribute('data-toggle')) { touch.btn[act] = !touch.btn[act]; b.classList.toggle('on', !!touch.btn[act]); } + else { touch.btn[act] = t.identifier + 1; b.classList.add('on'); } + // the fire button also looks: drag while firing + if (act === 'fire' || act === 'aimfire') touch.look = { id: t.identifier, x: t.clientX, y: t.clientY }; + continue; + } + if (t.clientX < window.innerWidth * 0.42 && !touch.stick) { + touch.stick = { id: t.identifier, x0: t.clientX, y0: t.clientY, x: t.clientX, y: t.clientY }; + stickEl.style.left = (t.clientX - 60) + 'px'; stickEl.style.top = (t.clientY - 60) + 'px'; stickEl.classList.add('on'); + } else if (!touch.look) touch.look = { id: t.identifier, x: t.clientX, y: t.clientY }; + } + e.preventDefault(); + }, { passive: false }); + tl.addEventListener('touchmove', function (e) { + for (var i = 0; i < e.changedTouches.length; i++) { + var t = e.changedTouches[i]; + if (touch.stick && t.identifier === touch.stick.id) { + touch.stick.x = t.clientX; touch.stick.y = t.clientY; + var dx = t.clientX - touch.stick.x0, dy = t.clientY - touch.stick.y0, L = Math.hypot(dx, dy), m = Math.min(L, 55); + knob.style.transform = 'translate(' + (L ? dx / L * m : 0) + 'px,' + (L ? dy / L * m : 0) + 'px)'; + } + if (touch.look && t.identifier === touch.look.id) { + I.mouseDX += (t.clientX - touch.look.x) * 2.2; I.mouseDY += (t.clientY - touch.look.y) * 2.2; + touch.look.x = t.clientX; touch.look.y = t.clientY; + } + } + e.preventDefault(); + }, { passive: false }); + function end(e) { + for (var i = 0; i < e.changedTouches.length; i++) { + var t = e.changedTouches[i]; + if (touch.stick && t.identifier === touch.stick.id) { touch.stick = null; stickEl.classList.remove('on'); knob.style.transform = ''; } + if (touch.look && t.identifier === touch.look.id) touch.look = null; + for (var a in touch.btn) if (touch.btn[a] === t.identifier + 1) { touch.btn[a] = false; var b = tl.querySelector('[data-act="' + a + '"]'); if (b) b.classList.remove('on'); } + } + } + tl.addEventListener('touchend', end); tl.addEventListener('touchcancel', end); + } + I.setTouchToggle = function (act, v) { touch.btn[act] = v; var b = document.querySelector('#touch [data-act="' + act + '"]'); if (b) b.classList.toggle('on', !!v); }; + + // ------------------------------------------------------------------ per frame + var PADB = { 0: 'jump', 1: 'melee', 2: 'reload', 3: 'interact', 4: 'wheel', 5: 'cover', 6: 'aim', 7: 'fire', 8: 'pause', 9: 'pause', 10: 'stealth', 11: 'camera', 13: 'throw', 12: 'prev', 14: 'drop' }; + I.update = function (dt) { + prev = now; + now = {}; + for (var k in state) now[k] = state[k]; + for (k in touch.btn) if (touch.btn[k]) now[k] = true; + I._now = now; + I._edges = function () { for (var k in now) if (now[k] && !prev[k]) edgeP[k] = true; for (k in prev) if (prev[k] && !now[k]) edgeR[k] = true; }; + if (now.aimfire) { now.aim = true; now.fire = true; } + var mx = (now.right ? 1 : 0) - (now.left ? 1 : 0), my = (now.up ? 1 : 0) - (now.down ? 1 : 0); + var L = Math.hypot(mx, my); if (L > 1) { mx /= L; my /= L; } + var sens = RP.TUNING.sens * RP.settings.sens; + var lx = I.mouseDX * sens, ly = I.mouseDY * sens * (RP.settings.invertY ? -1 : 1); + I.mouseDX = 0; I.mouseDY = 0; + if (touch.stick) { + var dx = touch.stick.x - touch.stick.x0, dy = touch.stick.y - touch.stick.y0, l2 = Math.hypot(dx, dy); + var m = Math.min(1, l2 / 55); mx = l2 ? dx / l2 * m : 0; my = l2 ? -dy / l2 * m : 0; + if (l2 > 75) now.sprint = true; // push past the ring to sprint + I.lastDevice = 'touch'; + } + // gamepad + var pads = navigator.getGamepads ? navigator.getGamepads() : [], gp = null; + for (var i = 0; i < pads.length; i++) if (pads[i] && pads[i].connected) { gp = pads[i]; break; } + if (gp) { + var dz = function (v) { return Math.abs(v) < 0.15 ? 0 : (v - Math.sign(v) * 0.15) / 0.85; }; + var gx = dz(gp.axes[0] || 0), gy = -dz(gp.axes[1] || 0); + if (gx || gy) { mx = gx; my = gy; I.lastDevice = 'pad'; } + var rx = dz(gp.axes[2] || 0), ry = dz(gp.axes[3] || 0); + if (rx || ry) { lx += rx * Math.abs(rx) * 3.2 * dt * RP.settings.sens; ly += ry * Math.abs(ry) * 2.4 * dt * RP.settings.sens * (RP.settings.invertY ? -1 : 1); I.lastDevice = 'pad'; } + for (var b in PADB) { var btn = gp.buttons[b]; if (btn && (btn.pressed || btn.value > 0.4)) { now[PADB[b]] = true; I.lastDevice = 'pad'; } } + if (gp.buttons[10] && gp.buttons[10].pressed) now.sprint = true; + } + I.pad = !!gp; + I.move.x = mx; I.move.y = my; I.look.x = lx; I.look.y = ly; + I.wheel = I.wheelDelta; I.wheelDelta = 0; + }; + I.assist = function () { return I.lastDevice !== 'kbm' || RP.settings.targeting !== 'free'; }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/items.js b/e63334287a3deaa3/blacktie/js/items.js new file mode 100644 index 00000000..cbdb5b9a --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/items.js @@ -0,0 +1,231 @@ +/* + * Items on the ground (RP.Items), GTA-style: + * - weapons lie where they fall as the real model (guards drop theirs when they go down; you can drop yours with B, + * or the Drop button in the weapon wheel on phones); each keeps the rounds that were in it + * - one weapon per slot (melee, pistol, SMG, rifle, shotgun, sniper, heavy; throwables stack by type; fists always) + * - walking over a weapon you already have takes its ammo; over one for an empty slot picks it up; over one for a + * slot you've filled shows "E: Swap for ", and swapping drops yours in its place + * - health, armour and ammo pickups (first-aid case, vest, ammo can) are taken on touch + * Picking a weapon up plays a crouch-and-grab; the gun goes into the slot and is drawn only if your hands were empty. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W, WP = RP.Weapons; + var IT = RP.Items = { list: [] }; + var TOUCH_R = 1.0, PROMPT_R = 1.6, GRAV = 9.8; + + IT.clear = function () { IT.list.forEach(function (it) { if (it.g.parent) it.g.parent.remove(it.g); if (it.hl && it.hl.parent) it.hl.parent.remove(it.hl); }); IT.list = []; (IT.debrisList || []).forEach(function (d) { d.g.parent && d.g.parent.remove(d.g); }); IT.debrisList = []; }; + + function ring(col) { + var m = new T.Mesh(new T.RingGeometry(0.36, 0.42, 28), new T.MeshBasicMaterial({ color: RP.col(col).multiplyScalar(1.6), transparent: true, opacity: 0.5, side: T.DoubleSide, depthWrite: false })); + m.rotation.x = -Math.PI / 2; m.position.y = 0.015; m.renderOrder = 4; return m; + } + function add(it) { RP.R.scene.add(it.g); IT.list.push(it); return it; } + + // a weapon on the ground: id, position, launch velocity, rounds {mag, reserve} + IT.dropWeapon = function (id, pos, vel, ammo, rotY) { + var d = WP.DEFS[id]; if (!d || d.unarmed) return null; + var g = new T.Group(), model = WP.model(id); + if (!model) return null; + model.position.set(0, 0, 0); g.add(model); + var hl = ring(d.cat === 'throw' ? '#e8c46a' : '#f2efe6'); hl.visible = false; RP.R.scene.add(hl); + g.position.copy(pos); + g.rotation.set(0, rotY || 0, 0); + var it = { kind: 'weapon', id: id, g: g, model: model, hl: hl, vel: (vel || new T.Vector3()).clone(), spin: new T.Vector3((Math.random() - 0.5) * 8, (Math.random() - 0.5) * 6, (Math.random() - 0.5) * 8), + rest: false, t: 0, ammo: ammo || { mag: d.mag || 0, reserve: 0 }, len: model.userData.len || 0.4 }; + return add(it); + }; + // health, armour and ammo: a small model, taken on touch + IT.pickup = function (kind, x, z, y) { + y = y == null ? W.ground(x, z, 200).y : y; + var g = new T.Group(), mats = RP.GunModels && RP.GunModels.mats ? null : null; + var std = function (hex, r, m) { return new T.MeshStandardMaterial({ color: RP.col(hex), roughness: r, metalness: m || 0 }); }; + if (/^mod:/.test(kind)) { + // a weapon mod in a small hard case with a coloured band + var mk = kind.slice(4), band = { suppressor: '#9aa0a6', extmag: '#c9a34a', scope: '#6aa7e8', grip: '#7fcf8a' }[mk] || '#ffffff'; + var cs = new T.Mesh(new T.BoxGeometry(0.3, 0.09, 0.2), std('#1b1c1e', 0.6, 0.2)); cs.position.y = 0.045; g.add(cs); + var bd = new T.Mesh(new T.BoxGeometry(0.305, 0.03, 0.06), std(band, 0.5)); bd.position.y = 0.07; g.add(bd); + g.traverse(function (o) { if (o.isMesh) o.castShadow = true; }); + g.add(ring(band)); g.position.set(x, y, z); g.rotation.y = Math.random() * 6.28; + return add({ kind: 'mod', mod: mk, g: g, rest: true, t: 0 }); + } + if (kind === 'health') { + var c = new T.Mesh(new T.BoxGeometry(0.34, 0.2, 0.12), std('#e9e5dc', 0.5)); c.position.y = 0.1; g.add(c); + var x1 = new T.Mesh(new T.BoxGeometry(0.12, 0.035, 0.125), std('#c8352a', 0.5)); x1.position.y = 0.11; g.add(x1); + var x2 = new T.Mesh(new T.BoxGeometry(0.035, 0.12, 0.125), std('#c8352a', 0.5)); x2.position.y = 0.11; g.add(x2); + var h = new T.Mesh(new T.BoxGeometry(0.12, 0.03, 0.03), std('#2a2a2a', 0.6)); h.position.y = 0.215; g.add(h); + } else if (kind === 'armour') { + var v = new T.Mesh(new T.BoxGeometry(0.4, 0.06, 0.46), std('#2b2c28', 0.85)); v.position.y = 0.03; g.add(v); + for (var i = 0; i < 3; i++) { var p = new T.Mesh(new T.BoxGeometry(0.08, 0.03, 0.12), std('#3a3b35', 0.8)); p.position.set(-0.12 + i * 0.12, 0.075, 0.1); g.add(p); } + } else { + var a = new T.Mesh(new T.BoxGeometry(0.3, 0.18, 0.14), std('#4b5340', 0.55, 0.3)); a.position.y = 0.09; g.add(a); + var l = new T.Mesh(new T.BoxGeometry(0.31, 0.03, 0.15), std('#3c4334', 0.5, 0.4)); l.position.y = 0.19; g.add(l); + var hd = new T.Mesh(new T.BoxGeometry(0.1, 0.025, 0.03), std('#202020', 0.5, 0.3)); hd.position.y = 0.215; g.add(hd); + } + g.traverse(function (o) { if (o.isMesh) o.castShadow = true; }); + if (RP.Vehicles && RP.Vehicles.mergeChildren) RP.Vehicles.mergeChildren(g); + g.add(ring({ health: '#d64b3c', armour: '#3c7bd6', ammo: '#c9a34a' }[kind])); + g.position.set(x, y, z); g.rotation.y = Math.random() * 6.28; + return add({ kind: kind, g: g, rest: true, t: 0 }); + }; + + // ---- inventory rules + IT.slotOf = function (p, cat) { + for (var id in p.inv) { var d = WP.DEFS[id]; if (d && d.cat === cat && !d.unarmed) return id; } + return null; + }; + // what touching / using this weapon would do: 'ammo', 'take', 'swap' (with the weapon it replaces) or null + IT.action = function (p, it) { + var d = WP.DEFS[it.id]; + if (p.inv[it.id]) return { what: (d.cat === 'throw' || it.ammo.mag + it.ammo.reserve > 0) ? 'ammo' : null }; + if (d.cat === 'throw') return { what: 'take' }; + var have = IT.slotOf(p, d.cat); + return have ? { what: 'swap', old: have } : { what: 'take' }; + }; + function rounds(it) { return (it.ammo.mag || 0) + (it.ammo.reserve || 0); } + function takeAmmo(p, it) { + var d = WP.DEFS[it.id], e = p.inv[it.id]; + if (d.cat === 'throw') { e.reserve = Math.min(d.reserve * 2, e.reserve + Math.max(1, rounds(it))); } + else e.reserve = Math.min((d.reserve || 0) * 2, e.reserve + rounds(it)); + RP.emit('toast', '+ ' + d.name + (d.cat === 'throw' ? '' : ' ammo')); RP.Audio.mech('magIn', p.pos); + remove(it); + } + function takeWeapon(p, it) { + var d = WP.DEFS[it.id]; + var e = p.inv[it.id] = { mag: d.cat === 'throw' ? 0 : Math.min(d.mag || 0, it.ammo.mag || 0), reserve: d.cat === 'throw' ? Math.max(1, rounds(it)) : (it.ammo.reserve || 0) }; + if (d.cat !== 'throw' && e.mag === 0 && e.reserve > 0) { var k = Math.min(d.mag, e.reserve); e.mag = k; e.reserve -= k; } + if (it.mods) e.mods = it.mods; + RP.emit('toast', 'Picked up ' + d.name); RP.Audio.mech('holster', p.pos); + remove(it); + // grab it from the ground + if (p.actor && p.state === 'move') { p.actor.move('pickup'); p.pickT = 0.55; } + if (p.cur === 'fists' && d.cat !== 'throw') RP.Player.equip(p, it.id); + if (d.cat === 'throw') p.throwId = it.id; + RP.emit('inventory', p); + } + // drop a weapon you carry (current one by default): it falls in front of you with its rounds + IT.playerDrop = function (p, id) { + id = id || p.cur; + var d = WP.DEFS[id]; if (!d || d.unarmed || !p.inv[id]) return false; + var e = p.inv[id], fwd = new T.Vector3(Math.sin(p.yaw), 0, Math.cos(p.yaw)); + var hand = p.actor.bones.hand_r ? p.actor.bones.hand_r.getWorldPosition(new T.Vector3()) : p.pos.clone().setY(p.pos.y + 1); + var dr = IT.dropWeapon(id, hand, fwd.multiplyScalar(1.6).setY(1.2).add(p.vel || new T.Vector3()), { mag: e.mag, reserve: e.reserve }, p.yaw); + if (dr) { dr.noAuto = true; dr.mods = e.mods || null; WP.dress(dr.model, dr.mods); } // something you dropped on purpose is only picked up again with E + delete p.inv[id]; + if (p.cur === id) { RP.Player.equip(p, 'fists', true); } + if (p.throwId === id) p.throwId = Object.keys(p.inv).filter(function (k) { return WP.DEFS[k].cat === 'throw'; })[0] || null; + p.actor.move('dropW'); + RP.emit('toast', 'Dropped ' + d.name); RP.emit('inventory', p); + return true; + }; + function remove(it) { it.gone = true; if (it.g.parent) it.g.parent.remove(it.g); if (it.hl && it.hl.parent) it.hl.parent.remove(it.hl); } + + // small things that fall and vanish (an empty magazine): a copy of the object, from a world position + IT.debrisList = []; + IT.debris = function (obj, worldPos) { + if (IT.debrisList.length > 12) { var o = IT.debrisList.shift(); o.g.parent && o.g.parent.remove(o.g); } + var g = obj.clone(true); obj.getWorldQuaternion(g.quaternion); g.position.copy(worldPos); g.visible = true; + RP.R.scene.add(g); + IT.debrisList.push({ g: g, vy: -0.4, t: 0, sx: (Math.random() - 0.5) * 6 }); + }; + function stepDebris(dt) { + for (var i = 0; i < IT.debrisList.length; i++) { + var d = IT.debrisList[i]; d.t += dt; + if (!d.rest) { + d.vy -= GRAV * dt; d.g.position.y += d.vy * dt; d.g.rotation.x += d.sx * dt; + var gy = W.ground(d.g.position.x, d.g.position.z, d.g.position.y + 0.4).y + 0.02; + if (d.g.position.y <= gy) { d.g.position.y = gy; d.rest = true; d.g.rotation.set(Math.PI / 2, d.g.rotation.y, 0); RP.Audio.mech && RP.Audio.mech('shell', d.g.position); } + } + if (d.t > 20) { d.g.parent && d.g.parent.remove(d.g); d.gone = true; } + } + IT.debrisList = IT.debrisList.filter(function (d) { return !d.gone; }); + } + // ---- per frame + var _q = new T.Quaternion(), _q2 = new T.Quaternion(), _e = new T.Euler(); + IT.near = null; + IT.update = function (dt) { + var p = RP.G.player, best = null, bd = 1e9, cam = RP.R.camera, qn = RP.R.qname; + var showD = qn === 'low' ? 40 : qn === 'high' ? 110 : 70, show2 = showD * showD; + stepDebris(dt); + for (var i = 0; i < IT.list.length; i++) { + var it = IT.list[i]; if (it.gone) continue; + it.t += dt; + // small things are not drawn from far off; a weapon on the ground uses the gun's cheaper versions with distance + var c2 = cam.position.distanceToSquared(it.g.position); + it.g.visible = c2 < show2; + if (it.model && it.model.userData.far && RP.GunModels) RP.GunModels.setFar(it.model, c2 < 196 ? 0 : c2 < 900 ? 1 : 2); + if (it.kind === 'weapon' && !it.rest) stepFall(it, dt); + if (it.kind !== 'weapon') { it.g.rotation.y += dt * 0.8; } + if (it.hl) { it.hl.position.set(it.g.position.x, it.gy != null ? it.gy + 0.015 : it.g.position.y, it.g.position.z); } + if (!p || !p.alive) continue; + var dx = p.pos.x - it.g.position.x, dz = p.pos.z - it.g.position.z, dy = Math.abs(p.pos.y + 0.3 - it.g.position.y), dist = Math.hypot(dx, dz); + if (dy > 1.6) continue; + if (it.kind !== 'weapon') { + if (dist < TOUCH_R) touchPickup(p, it); + continue; + } + var act = IT.action(p, it); + if (it.hl) it.hl.visible = dist < 8 && it.rest; + if (dist < TOUCH_R && act.what === 'ammo') { takeAmmo(p, it); continue; } + if (dist < TOUCH_R && act.what === 'take' && it.rest && !it.noAuto) { takeWeapon(p, it); continue; } + if ((act.what === 'swap' || act.what === 'take' && it.noAuto) && it.rest && dist < PROMPT_R && dist < bd) { best = it; bd = dist; } + } + IT.list = IT.list.filter(function (it) { return !it.gone; }); + IT.near = best; + if (best) { var a = IT.action(p, best); RP.HUD.interact = a.what === 'swap' ? 'Swap ' + WP.DEFS[a.old].name + ' for ' + WP.DEFS[best.id].name : 'Pick up ' + WP.DEFS[best.id].name; } + // keep the scene light: at most 24 weapons lying around (oldest go first) + var ws = IT.list.filter(function (it) { return it.kind === 'weapon'; }); + if (ws.length > 24) remove(ws[0]); + }; + // the swap, on E + IT.interact = function (p) { + var it = IT.near; if (!it || it.gone) return false; + var a = IT.action(p, it); + if (a.what === 'take') { takeWeapon(p, it); return true; } + if (a.what !== 'swap') return false; + var wasCur = p.cur === a.old; + IT.playerDrop(p, a.old); + takeWeapon(p, it); + if (wasCur) RP.Player.equip(p, it.id); + return true; + }; + function touchPickup(p, it) { + var TU = RP.TUNING; + if (it.kind === 'mod') { + var md = WP.MODS[it.mod], e = p.inv[p.cur]; + if (!WP.canFit(p.cur, it.mod) || (e.mods && e.mods[it.mod])) { + if ((it.sayT || 0) < RP.G.time) { it.sayT = RP.G.time + 4; RP.emit('toast', md.name + ': hold a weapon it fits'); } + return; + } + e.mods = Object.assign({}, e.mods); e.mods[it.mod] = true; + RP.Player.refit(p); RP.emit('toast', md.name + ' fitted to ' + WP.DEFS[p.cur].name); RP.Audio.mech('slide', p.pos); RP.emit('inventory', p); + remove(it); return; + } + if (it.kind === 'health') { if (p.hp >= TU.maxHealth) return; p.hp = Math.min(TU.maxHealth, p.hp + 50); RP.emit('toast', '+ Health'); } + if (it.kind === 'armour') { if (p.armour >= TU.maxArmour) return; p.armour = TU.maxArmour; RP.emit('toast', '+ Armour'); } + if (it.kind === 'ammo') { Object.keys(p.inv).forEach(function (id) { var d = WP.DEFS[id]; if (d.reserve && d.cat !== 'throw') p.inv[id].reserve = Math.min(d.reserve * 2, p.inv[id].reserve + Math.ceil(d.mag * 2)); }); RP.emit('toast', '+ Ammo'); } + RP.Audio.ui('ok'); remove(it); + } + // tumble, land, settle lying on its side + function stepFall(it, dt) { + var g = it.g, v = it.vel; + v.y -= GRAV * dt; + g.position.addScaledVector(v, dt); + g.rotation.x += it.spin.x * dt; g.rotation.y += it.spin.y * dt; g.rotation.z += it.spin.z * dt; + var gr = W.ground(g.position.x, g.position.z, g.position.y + 0.5); + var gy = gr ? gr.y : g.position.y - 10; + var lie = gy + 0.03; + if (g.position.y <= lie) { + g.position.y = lie; + if (Math.abs(v.y) > 1.2) { v.y = -v.y * 0.25; v.x *= 0.5; v.z *= 0.5; it.spin.multiplyScalar(0.4); RP.Audio.step && RP.Audio.step('metal', g.position, 0.5); } + else { + v.set(0, 0, 0); it.spin.set(0, 0, 0); + // lie on the side the gun is turned towards + _e.set(0, g.rotation.y, Math.PI / 2 * (Math.sin(g.rotation.z) >= 0 ? 1 : -1)); _q.setFromEuler(_e); + g.quaternion.slerp(_q, Math.min(1, dt * 14)); + if (g.quaternion.angleTo(_q) < 0.02) { g.quaternion.copy(_q); it.rest = true; it.gy = gy; } + } + } + if (it.t > 6 && !it.rest) { it.rest = true; it.gy = gy; } + } +})(); diff --git a/e63334287a3deaa3/blacktie/js/main.js b/e63334287a3deaa3/blacktie/js/main.js new file mode 100644 index 00000000..1479115a --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/main.js @@ -0,0 +1,321 @@ +/* + * Boot, the mission runner (RP.Run), menus and the main loop. + * Loop: a fixed 60 Hz simulation (at most 6 steps a frame; the rest is dropped so a stall never snowballs), then one + * render with animation, camera, effects and HUD. The weapon wheel slows time to a quarter; a melee hit freezes it + * for a few hundredths of a second (hit stop) so blows land. + * ?test exposes window.__RP__ for scripted tests: start(id), step(n), press(action, on), look(dx, dy), state(). + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W, TU = RP.TUNING; + var G = RP.G, R = RP.R; + var $ = function (id) { return document.getElementById(id); }; + G.ents = []; G.guards = []; G.civilians = []; + + // ------------------------------------------------------------------ the mission runner + var Run = RP.Run = { stats: { takedowns: 0 }, pickups: [], interact: null }; + Run.time = function () { var s = Math.round(G.time); return Math.floor(s / 60) + ':' + ('0' + s % 60).slice(-2); }; + Run.pickup = function (kind, x, z, y) { return RP.Items.pickup(kind, x, z, y); }; + Run._oldPickup = function (kind, x, z, y) { + y = y == null ? W.ground(x, z, 200).y : y; + var col = { health: '#d64b3c', armour: '#3c7bd6', ammo: '#c9a34a' }[kind]; + var g = new T.Group(); + var box = new T.Mesh(new T.BoxGeometry(0.42, 0.26, 0.3), new T.MeshStandardMaterial({ color: RP.col(kind === 'armour' ? '#26303c' : kind === 'health' ? '#f2efe6' : '#3f4a36'), roughness: 0.6 })); + box.position.y = 0.13; box.castShadow = true; g.add(box); + var mark = new T.Mesh(new T.BoxGeometry(0.2, 0.03, 0.2), new T.MeshBasicMaterial({ color: RP.col(col).multiplyScalar(3) })); mark.position.y = 0.28; g.add(mark); + var ring = new T.Mesh(new T.RingGeometry(0.42, 0.5, 24), new T.MeshBasicMaterial({ color: RP.col(col).multiplyScalar(2), transparent: true, opacity: 0.6, side: T.DoubleSide, depthWrite: false })); ring.rotation.x = -Math.PI / 2; ring.position.y = 0.03; g.add(ring); + g.position.set(x, y, z); R.scene.add(g); + Run.pickups.push({ kind: kind, g: g, p: new T.Vector3(x, y, z), taken: false }); + }; + Run.interactable = function (label, at, r, fn) { Run.interact = { label: label, p: new T.Vector3(at.x, at.y, at.z), r: r, fn: fn }; }; + function clearWorld() { + G.ents.forEach(function (e) { if (e.actor) e.actor.dispose(); }); + G.ents = []; G.guards = []; G.civilians = []; G.player = null; + Run.pickups.forEach(function (p) { R.scene.remove(p.g); }); Run.pickups = []; Run.interact = null; RP.Items.clear(); RP.Traffic.clear(); RP.Vehicles.clear(); RP.Heli.clear(); + RP.Combat.projs.forEach(function (p) { R.scene.remove(p.m); }); RP.Combat.projs = []; RP.Combat.noises = []; + RP.Rag.list = []; RP.FX.smokes = []; + } + Run.start = function (id, fromStep) { + var m = RP.missions.list[id]; if (!m) return; + clearWorld(); + G.mission = { def: m, id: id, step: fromStep || 0, reinforce: m.reinforce, spawns: m.spawns }; + var mm = G.mission; + for (var k in m) if (typeof m[k] !== 'function' && !(k in mm)) mm[k] = m[k]; + G.time = 0; G.scale = 1; G.night = !!m.night; G.hitstop = 0; G.over = false; + R.setAtmos(m.atmos); + Run.stats = { takedowns: 0 }; + var st = m.start; + if (fromStep && m.steps[fromStep] && m.steps[fromStep].at && m.checkpointSpot) st = m.checkpointSpot; + var p = RP.Player.create(st, m.loadout); + if (m.armour) p.armour = m.armour; + RP.Cam.reset(p); + RP.Alert.reset(m.alert); + m.setup(mm); + // cars and a launch to take (map data: RP.map.vehicles = [[type, x, z, yaw], ...]; a mission can add its own) + ((RP.map && RP.map.vehicles) || [['city', -16, 15.5, Math.PI / 2], ['spider', 30, 17.5, -Math.PI / 2], ['boat', 30, 52, Math.PI / 2]]).concat(m.vehicles || []).forEach(function (v) { RP.Vehicles.spawn(v[0], v[1], v[2], v[3], v[4]); }); + RP.Traffic.start(m); // bystanders' cars on the coast road (missions with traffic: true) + // skip to a checkpoint: run the earlier steps' enter() so the world matches, put the player where they were + if (fromStep) { + for (var i = 0; i < fromStep; i++) if (m.steps[i].enter) m.steps[i].enter(mm); + if (Run.cpPos) { p.pos.copy(Run.cpPos); p.yaw = Run.cpYaw; RP.Cam.reset(p); } + // guards spawned by earlier waves are gone at a checkpoint + if (mm.waveGuards) mm.waveGuards.forEach(function (list, wi) { if (wi < fromStep - 1) list.forEach(function (g) { g.hp = 0; g.alive = false; g.actor.root.visible = false; g.ghost = true; }); }); + } + enterStep(mm); + RP.emit('alert', RP.Alert.level); + R.warm(); + G.paused = false; G.running = true; + showScreen(null); + if (!RP.test) lockPointer(); + }; + function enterStep(mm) { + var s = mm.def.steps[mm.step]; if (!s) return; + RP.HUD.objective(s.text, s.sub); + G.objPos = s.at ? new T.Vector3(s.at.x, s.at.y || 0, s.at.z) : null; + if (s.checkpoint) { Run.cp = mm.step; Run.cpPos = G.player.pos.clone(); Run.cpYaw = G.player.yaw; if (mm.step > 0) RP.emit('toast', 'Checkpoint'); } + if (s.enter) s.enter(mm); + if (mm.step > 0) RP.Audio.ui('objective'); + } + function stepMission(dt) { + var mm = G.mission; if (!mm || G.over) return; + var s = mm.def.steps[mm.step]; + if (s && s.check(mm, dt)) { + mm.step++; + if (mm.step >= mm.def.steps.length) { finish(true); return; } + enterStep(mm); + } + var p = G.player; + // interactables (set first; a weapon swap prompt from RP.Items wins) + RP.HUD.interact = null; + if (Run.interact && p.alive && p.pos.distanceTo(Run.interact.p) < Run.interact.r) RP.HUD.interact = Run.interact.label; + RP.Items.update(dt); + RP.W.navWarm(1.5); + RP.Traffic.update(dt); + RP.Vehicles.update(dt); + RP.Heli.update(dt); + } + RP.on('interact', function (p) { + if (RP.Items.interact(p)) return; + if (p.state === 'move' && RP.Vehicles.interact(p)) return; + if (Run.interact && p.pos.distanceTo(Run.interact.p) < Run.interact.r) { var f = Run.interact.fn; Run.interact = null; f(); } + }); + RP.on('guardDown', function (g, info) { if (info && info.takedown) Run.stats.takedowns++; }); + RP.on('playerDead', function () { setTimeout(function () { finish(false); }, 2600); }); + function finish(won) { + if (G.over) return; + G.over = true; + var mm = G.mission, d = mm.def; + if (won && !d.free) { + var rec = RP.save.done[d.id] || {}; rec.done = true; rec.best = Math.min(rec.best || 1e9, Math.round(G.time)); + if (d.id === 'villa' && mm.unseen) rec.ghost = true; + RP.save.done[d.id] = rec; RP.writeSave(); + } + var rows = won && d.rate ? d.rate(mm) : []; + $('resTitle').textContent = won ? 'Mission complete' : 'Mission failed'; + $('resName').textContent = d.title; + $('resRows').innerHTML = rows.map(function (r) { return '
' + r[0] + '' + (r[1] === true ? 'Yes' : r[1] === false ? 'No' : r[1]) + '
'; }).join(''); + $('resRetry').textContent = won ? 'Play again' : (Run.cp ? 'Retry from checkpoint' : 'Retry'); + $('resRetry').onclick = function () { Run.start(mm.id, won ? 0 : (Run.cp || 0)); }; + $('resNext').hidden = !won || !nextMission(d.id); + $('resNext').onclick = function () { var n = nextMission(d.id); if (n) Run.start(n); }; + setTimeout(function () { G.paused = true; showScreen('results'); unlockPointer(); }, won ? 900 : 0); + } + function nextMission(id) { var o = RP.missions.order.filter(function (k) { return !RP.missions.list[k].free; }); var i = o.indexOf(id); return o[i + 1] || null; } + + // ------------------------------------------------------------------ screens + function showScreen(id) { + document.querySelectorAll('.screen').forEach(function (s) { s.hidden = s.id !== id; }); + document.body.classList.toggle('inmenu', !!id); + $('hud').hidden = !!id && id !== 'pause'; + if (RP.touch) $('touch').hidden = !!id; + } + RP.showScreen = showScreen; + function lockPointer() { if (!RP.touch && $('view').requestPointerLock) try { $('view').requestPointerLock(); } catch (e) {} } + function unlockPointer() { if (document.pointerLockElement) document.exitPointerLock(); } + function pause(on) { + if (!G.running || G.over) return; + G.paused = on; + if (RP.HUD.wheelOn) RP.HUD.closeWheel(false); + showScreen(on ? 'pause' : null); + if (on) unlockPointer(); else lockPointer(); + } + RP.on('wantPause', function () { pause(true); }); + + function buildMenus() { + // mission list + var list = $('missionList'), html = ''; + RP.missions.order.forEach(function (id) { + var m = RP.missions.list[id], rec = RP.save.done[id] || {}; + html += ''; + }); + list.innerHTML = html; + list.querySelectorAll('[data-m]').forEach(function (b) { b.onclick = function () { RP.Audio.init(); Run.start(b.getAttribute('data-m')); }; }); + $('btnPlay').onclick = function () { RP.Audio.init(); showScreen('missions'); }; + $('btnFree').onclick = function () { RP.Audio.init(); Run.start('free'); }; + $('btnSettings').onclick = function () { RP.Audio.init(); openSettings('title'); }; + $('btnControls').onclick = function () { showScreen('controls'); $('ctlBack').onclick = function () { showScreen('title'); }; }; + $('missionsBack').onclick = function () { showScreen('title'); }; + $('pResume').onclick = function () { pause(false); }; + $('pRestart').onclick = function () { Run.start(G.mission.id, Run.cp || 0); }; + $('pSettings').onclick = function () { openSettings('pause'); }; + $('pControls').onclick = function () { showScreen('controls'); $('ctlBack').onclick = function () { showScreen('pause'); }; }; + $('pQuit').onclick = function () { G.running = false; G.paused = true; clearWorld(); menuScene(); showScreen('title'); }; + $('resMenu').onclick = function () { G.running = false; clearWorld(); menuScene(); showScreen('title'); }; + $('noteOk').onclick = function () { try { localStorage.setItem('blacktie:note', '1'); } catch (e) {} showScreen('title'); }; + if (RP.touch) $('tPause').addEventListener('click', function () { pause(true); }); + $('setBack').onclick = function () { RP.saveSettings(); showScreen(setFrom); }; + } + var setFrom = 'title'; + function openSettings(from) { + setFrom = from; showScreen('settings'); + var S = RP.settings, f = $('setForm'); + f.quality.value = R.qname; f.targeting.value = S.targeting; f.difficulty.value = S.difficulty; + f.sens.value = S.sens; f.volume.value = S.volume; f.invertY.checked = S.invertY; f.blood.checked = S.blood; f.camShake.checked = S.camShake; f.fov.value = S.fov || 0; + f.onchange = function (e) { + var t = e.target; + if (t.name === 'quality') { if (confirm('Changing graphics quality reloads the page. Continue?')) R.setQuality(t.value); else t.value = R.qname; return; } + if (t.type === 'checkbox') S[t.name] = t.checked; else if (t.type === 'range') S[t.name] = parseFloat(t.value); else S[t.name] = t.value; + if (t.name === 'volume') RP.Audio.setVolume(S.volume); + RP.saveSettings(); + }; + } + + // the title screen shows a slow drift over the town + var menuT = 0; + function menuScene() { R.setAtmos('golden'); G.night = false; } + function menuCamera(dt) { + menuT += dt * 0.04; + var a = menuT, c = R.camera; + c.position.set(Math.sin(a) * 60 + 10, 34 + Math.sin(a * 0.7) * 6, 95 + Math.cos(a) * 20); + c.fov = 50; c.updateProjectionMatrix(); c.lookAt(0, 10, -20); + R.followSun(new T.Vector3(0, 8, -10)); + } + + // ------------------------------------------------------------------ loop + var acc = 0, last = 0, STEP = TU.step; + function frame(now) { + requestAnimationFrame(frame); + var dt = Math.min(0.1, (now - last) / 1000 || 0.016); last = now; + if (document.hidden || (RP.test && !RP.live)) return; + tick(dt); + } + function tick(dt) { + RP.In.update(dt); + RP.In._edges(); + var p = G.player; + if (G.running && p) { + if (RP.In.pressed('pause')) pause(!G.paused); + if (!G.paused) { + RP.HUD.stepWheel(p); + var sdt = dt * G.scale; + if (G.hitstop > 0) { G.hitstop -= dt; sdt *= 0.05; } + acc += sdt; var n = 0; + while (acc >= STEP && n < 6) { simStep(STEP); acc -= STEP; n++; } + if (n >= 6) acc = 0; + if (n > 0) RP.In.clearEdges(); + RP.Cam.update(dt, p); + RP.Player.frame(p, sdt); + RP.AI.frame(sdt); + RP.FX.update(sdt); + RP.HUD.update(dt, p); + RP.Audio.indoor = !!W.indoor(p.pos.x, p.pos.y + 1, p.pos.z); + RP.Audio.listen(R.camera); + RP.Audio.ambient(M.clamp(1 - (p.pos.y - 2) / 30, 0, 1) * M.clamp(1 - Math.abs(p.pos.z - 40) / 80, 0, 1), !G.night, RP.Alert.level > 0 ? 1 : 0); + } + R.followSun(p.pos); + } else if (!G.running) { menuCamera(dt); RP.FX.update(dt); } + if (!G.running || G.paused) RP.In.clearEdges(); + RP.windU.value += dt; + RP.Sea.update(G.time + (G.running ? 0 : performance.now() / 1000), R.camera); + if (!RP._noDraw) R.draw(dt); + perf(dt); + } + function simStep(dt) { + G.time += dt; + RP.Player.step(G.player, dt); + RP.AI.step(dt); + RP.AI.stepCivs(dt); + RP.Combat.step(dt); + RP.Rag.update(dt); + RP.Alert.step(dt); + stepMission(dt); + RP.In.consumeAll && RP.In.consumeAll(); + } + // frame-time readout (?fps) and the numbers the tests read + var pf = { n: 0, t: 0, worst: 0 }; + function perf(dt) { + pf.n++; pf.t += dt; pf.worst = Math.max(pf.worst, dt); + if (pf.t > 1) { RP.perf = { fps: pf.n / pf.t, worst: pf.worst * 1000, calls: R.stats.calls, tris: R.stats.tris }; if ($('fps')) $('fps').textContent = Math.round(RP.perf.fps) + ' fps · ' + R.stats.calls + ' calls · ' + Math.round(R.stats.tris / 1000) + 'k tris'; pf = { n: 0, t: 0, worst: 0 }; } + } + + // ------------------------------------------------------------------ boot + function boot() { + var canvas = $('view'); + try { + R.init(canvas); + } catch (e) { $('loadText').textContent = 'This device could not start 3D graphics (WebGL).'; return; } + RP.buildTextures(); RP.buildMaterials(); + RP.In.init(canvas); + RP.HUD.init(); + buildMenus(); + if (/[?&]fps\b/.test(location.search)) $('fps').hidden = false; + var bar = $('loadBar'); + $('loadText').textContent = 'Loading people and animation'; + RP.Chars.load(function (k) { bar.style.width = Math.round(k * 80) + '%'; }).then(function () { + $('loadText').textContent = 'Building the coast'; + bar.style.width = '85%'; + return new Promise(function (res) { setTimeout(res, 30); }); + }).then(function () { + var t0 = performance.now(); + var map = RP.maps.list.amalfi.build(); + RP.Sea.build(map.hf); + RP.FX.init(); + RP.buildMs = performance.now() - t0; + menuScene(); + bar.style.width = '100%'; + R.warm(); + $('loading').hidden = true; + var seen = false; try { seen = localStorage.getItem('blacktie:note') === '1'; } catch (e) {} + showScreen(seen || RP.test ? 'title' : 'note'); + requestAnimationFrame(frame); + window.__ready = true; + }).catch(function (e) { + console.error(e); + $('loadText').textContent = 'Something failed to load: ' + (e && e.message || e) + '. Try reloading the page.'; + }); + } + window.addEventListener('pointerdown', function () { RP.Audio.init(); }, { once: false }); + window.addEventListener('keydown', function () { RP.Audio.init(); }, { once: true }); + + // ------------------------------------------------------------------ test hook + if (RP.test) { + var held = {}; + window.__RP__ = { + start: function (id, step) { Run.start(id, step); return true; }, + step: function (n, dt) { dt = dt || 1 / 60; for (var i = 0; i < (n || 1); i++) { for (var k in held) RP._fake[k] = held[k]; tick(dt); } return this.state(); }, + sim: function (n) { RP._noDraw = true; try { this.step(n); } finally { RP._noDraw = false; } this.step(1); return this.state(); }, + press: function (a, on) { held[a] = on; RP._fake = RP._fake || {}; RP._fake[a] = on; }, + move: function (x, y) { RP._fakeMove = { x: x, y: y }; }, + look: function (dx, dy) { RP.In.mouseDX += dx; RP.In.mouseDY += dy; }, + state: function () { + var p = G.player; if (!p) return { running: false }; + return { state: p.state, pos: [+p.pos.x.toFixed(2), +p.pos.y.toFixed(2), +p.pos.z.toFixed(2)], yaw: +p.yaw.toFixed(2), speed: +p.speed.toFixed(2), hp: Math.round(p.hp), armour: Math.round(p.armour), + weapon: p.cur, mag: p.inv[p.cur].mag, reserve: p.inv[p.cur].reserve, aiming: p.aiming, stealth: p.stealth, cover: p.cover ? { low: p.cover.low, edge: p.cover.edge, peek: +p.cover.peek.toFixed(2) } : null, + alert: RP.Alert.level, guards: G.guards.filter(function (g) { return g.alive; }).length, guardStates: G.guards.map(function (g) { return g.state; }).join(','), step: G.mission && G.mission.step, over: G.over, time: +G.time.toFixed(2), + perf: RP.perf, calls: R.stats.calls, tris: R.stats.tris, kills: p.kills }; + }, + G: G, RP: RP + }; + // fake input injection for tests + var origUpdate = RP.In.update; + RP.In.update = function (dt) { + origUpdate(dt); + var f = RP._fake || {}; + // keep "pressed" edges working: merge into the action state + for (var k in f) if (f[k]) RP.In._now[k] = true; + if (RP._fakeMove) { RP.In.move.x = RP._fakeMove.x; RP.In.move.y = RP._fakeMove.y; } + }; + } + window.addEventListener('load', boot); +})(); diff --git a/e63334287a3deaa3/blacktie/js/mapkit.js b/e63334287a3deaa3/blacktie/js/mapkit.js new file mode 100644 index 00000000..f9964354 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/mapkit.js @@ -0,0 +1,1036 @@ +/* + * Map kit (RP.Kit): the reusable builders every map shares, so a new city is one data file that calls these and + * RP.maps.register (see maps/amalfi.js for the pattern): + * + * land K.makeLand: a heightfield from a base shape + flattened pads + road beds; K.occ*: a 2 m occupancy grid + * streets K.roads (ribbons, steps, parapets), K.stair, K.steps, K.tunnel, K.bridge + * buildings K.house (stucco house with painted bays, real windows near the camera, balconies, shops, signs, awnings, + * roofs: flat terrace, barrel vaults, dome, tiles), K.arcade, K.archOver, K.frontage, K.fillSlope + * walls K.wall, K.balustrade, K.parapet, K.railing + * props K.lamp, K.wallLamp, K.crate, K.car, K.scooter, K.boat, K.umbrella, K.lounger, K.cafeTable, K.planter, + * K.bollard, K.bin, K.bench, K.nets, K.laundry, K.pergola, K.rocks + * plants K.tree (pine, cypress, palm, lemon, olive, scrub), K.climbers + * + * Everything that can stop a person or a bullet also adds a box to RP.W; the drawn meshes are never collided with. + * Detail classes (see build.js): big shapes go in 'shell', small relief and props in 'detail', wall decals in 'flat', + * and each building adds one plain box to 'far'. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W, B = RP.B; + var col = RP.col; + var K = RP.Kit = {}; + var V3 = function (x, y, z) { return new T.Vector3(x, y, z); }; + var FH = K.FH = 3.2; // storey height + + K.reset = function (bounds) { + K.bounds = bounds; K.LAMPS = []; K.land = null; K.houses = 0; + K.occN = Math.ceil((bounds.x1 - bounds.x0) / OC) + 1; + K.occ = new Uint16Array(K.occN * (Math.ceil((bounds.z1 - bounds.z0) / OC) + 1)); K.occId = 3; + B.makeGeos(); + }; + var _colCache = {}; + function C(hex) { return _colCache[hex] || (_colCache[hex] = col(hex)); } // shared: never mutate the result + function Cv(hex, k) { return col(hex).multiplyScalar(k); } + K.C = C; + + // ------------------------------------------------------------------ the shape of the land + function segDist(px, pz, ax, az, bx, bz) { + var dx = bx - ax, dz = bz - az, L2 = dx * dx + dz * dz, t = L2 ? M.clamp(((px - ax) * dx + (pz - az) * dz) / L2, 0, 1) : 0; + var qx = ax + dx * t, qz = az + dz * t; return { d: Math.hypot(px - qx, pz - qz), t: t }; + } + K.segDist = segDist; + // def: { bounds, cell, base(x, z) -> height, pads: [...], roads: [...] } + // pad: { x0, z0, x1, z1, y, blend } | { cx, cz, r, y, blend } | { ..., cut: true } (only lowers) + // road: { w, mat, pts: [[x, z, y], ...], steps, blend (m of slope beside the bed, default 5), shoulder (m of level + // ground past the kerb, default 1.2), pave (extra paved width), bridge: [i0, i1] (segments that + // leave the ground alone), tunnels: [[i0, i1], ...] (segments cut as a narrow trench, roofed by K.tunnel) } + K.makeLand = function (def) { + var L = { def: def, pads: def.pads, roads: def.roads, bounds: def.bounds }; + def.roads.forEach(function (r) { + var m = (r.blend == null ? 5 : r.blend) + r.w / 2 + 1; + r.segs = []; + for (var k = 0; k < r.pts.length - 1; k++) { + var a = r.pts[k], b = r.pts[k + 1]; + r.segs.push({ a: a, b: b, x0: Math.min(a[0], b[0]) - m, x1: Math.max(a[0], b[0]) + m, z0: Math.min(a[1], b[1]) - m, z1: Math.max(a[1], b[1]) + m, + bridge: !!(r.bridge && k >= r.bridge[0] && k < r.bridge[1]), tunnel: (r.tunnels || []).some(function (t) { return k >= t[0] && k < t[1]; }) }); + } + }); + L.heightAt = function (x, z, noTunnel) { + var h = def.base(x, z), P = def.pads, R = def.roads, i, m; + for (i = 0; i < P.length; i++) { + var p = P[i]; + if (p.cut) { if (x >= p.x0 && x <= p.x1 && z >= p.z0 && z <= p.z1) h = Math.min(h, p.y); continue; } + if (p.r) { if (Math.abs(x - p.cx) > p.r + p.blend || Math.abs(z - p.cz) > p.r + p.blend) continue; var d = Math.hypot(x - p.cx, z - p.cz); m = M.smooth((p.r + p.blend - d) / p.blend); } + else { var ex = Math.max(p.x0 - x, 0, x - p.x1), ez = Math.max(p.z0 - z, 0, z - p.z1); if (ex > p.blend || ez > p.blend) continue; m = M.smooth((p.blend - Math.hypot(ex, ez)) / p.blend); } + if (m > 0) h = M.lerp(h, p.y, m); + } + for (i = 0; i < R.length; i++) { + var r = R[i], best = 1e9, by = 0, S = r.segs, tun = false, bl = r.blend == null ? 5 : r.blend; + for (var k = 0; k < S.length; k++) { + var sg = S[k]; if (x < sg.x0 || x > sg.x1 || z < sg.z0 || z > sg.z1 || sg.bridge) continue; + var s = segDist(x, z, sg.a[0], sg.a[1], sg.b[0], sg.b[1]); + if (s.d < best) { best = s.d; by = sg.a[2] + (sg.b[2] - sg.a[2]) * s.t; tun = sg.tunnel; } + } + if (best > 1e8) continue; + if (tun) { if (noTunnel) continue; bl = 1.6; } + var mm = M.smooth((r.w / 2 + (tun ? 2.3 : r.shoulder == null ? 1.2 : r.shoulder) + bl - best) / bl); // level a little past the kerb (a tunnel's trench wider still: its lining stands inside it) + if (mm > 0) h = tun ? (h > by ? M.lerp(h, by, mm) : h) : M.lerp(h, by, mm); + } + return h; + }; + L.onRoad = function (x, z, extra) { + var R = def.roads; extra = extra || 0; + for (var i = 0; i < R.length; i++) { + var r = R[i], S = r.segs, lim = r.w / 2 + extra; + for (var k = 0; k < S.length; k++) { + var sg = S[k]; if (x < sg.x0 || x > sg.x1 || z < sg.z0 || z > sg.z1) continue; + if (segDist(x, z, sg.a[0], sg.a[1], sg.b[0], sg.b[1]).d < lim) return r; + } + } + return null; + }; + // The coarser terrain meshes sample the ground every 4 to 16 m, which would let a cutting's slope spill over the + // road beside it. cap(x, z, margin) is the height such a vertex must stay under: the level of a road or pad that + // lies within `margin` of it (Infinity where there is none). + L.cap = function (x, z, margin) { + var R = def.roads, P = def.pads, best = Infinity, i; + for (i = 0; i < R.length; i++) { + var r = R[i], S = r.segs, lim = r.w / 2 + margin; + for (var k = 0; k < S.length; k++) { + var sg = S[k]; if (x < sg.x0 - margin || x > sg.x1 + margin || z < sg.z0 - margin || z > sg.z1 + margin || sg.bridge || sg.tunnel) continue; + var s = segDist(x, z, sg.a[0], sg.a[1], sg.b[0], sg.b[1]); + if (s.d < lim) { var y = sg.a[2] + (sg.b[2] - sg.a[2]) * s.t - 0.05; if (y < best) best = y; } + } + } + for (i = 0; i < P.length; i++) { + var p = P[i]; if (p.cut) continue; + var d = p.r ? Math.hypot(x - p.cx, z - p.cz) - p.r : Math.hypot(Math.max(p.x0 - x, 0, x - p.x1), Math.max(p.z0 - z, 0, z - p.z1)); + if (d < margin && p.y - 0.05 < best) best = p.y - 0.05; + } + return best; + }; + var Bd = def.bounds, cell = def.cell || 2, nx = Math.round((Bd.x1 - Bd.x0) / cell) + 1, nz = Math.round((Bd.z1 - Bd.z0) / cell) + 1; + var h = new Float32Array(nx * nz); + for (var j = 0; j < nz; j++) for (var i = 0; i < nx; i++) h[j * nx + i] = L.heightAt(Bd.x0 + i * cell, Bd.z0 + j * cell); + L.hf = { x0: Bd.x0, z0: Bd.z0, cell: cell, nx: nx, nz: nz, h: h }; + K.land = L; + return L; + }; + + // occupancy grid so houses don't overlap roads, squares or each other (2 m cells) + var OC = 2; + function occIdx(x, z) { var b = K.bounds; return Math.floor((M.clamp(z, b.z0, b.z1) - b.z0) / OC) * K.occN + Math.floor((M.clamp(x, b.x0, b.x1) - b.x0) / OC); } + K.occAt = function (x, z) { return K.occ[occIdx(x, z)]; }; + // val 1 (default): a building or a square; 2: a road's own margin, which street frontage may build up to; 3 and up: + // one row of a street's frontage (its houses stand wall to wall, so they must not block each other) + K.occMark = function (x, z, w, d, yaw, pad, val) { + var c = Math.cos(yaw || 0), s = Math.sin(yaw || 0), r = Math.hypot(w, d) / 2 + (pad || 0); + for (var zz = z - r; zz <= z + r; zz += OC / 2) for (var xx = x - r; xx <= x + r; xx += OC / 2) { + var dx = xx - x, dz = zz - z, lx = dx * c - dz * s, lz = dx * s + dz * c; + if (Math.abs(lx) <= w / 2 + (pad || 0) && Math.abs(lz) <= d / 2 + (pad || 0)) { var oi = occIdx(xx, zz); if (val !== 2 || !K.occ[oi]) K.occ[oi] = val || 1; } + } + }; + K.occFree = function (x, z, w, d, yaw, pad, roadPad, row) { + roadPad = roadPad == null ? 0.6 : roadPad; + var c = Math.cos(yaw), s = Math.sin(yaw), r = Math.hypot(w, d) / 2 + pad, b = K.bounds; + if (x - r < b.x0 + 2 || x + r > b.x1 - 2 || z - r < b.z0 + 2 || z + r > b.z1 - 2) return false; + for (var zz = z - r; zz <= z + r; zz += OC / 2) for (var xx = x - r; xx <= x + r; xx += OC / 2) { + var dx = xx - x, dz = zz - z, lx = dx * c - dz * s, lz = dx * s + dz * c; + if (Math.abs(lx) <= w / 2 + pad && Math.abs(lz) <= d / 2 + pad) { + if (K.land.onRoad(xx, zz, roadPad)) return false; + var o = K.occ[occIdx(xx, zz)]; + if (o && !(row && (o === 2 || o === row))) return false; + } + } + return true; + }; + + // ------------------------------------------------------------------ roads, steps, stairs + // Draws every road of the land: a ribbon over the flattened bed, steps where a stepped lane is steep, kerb lines and + // a seaward stone parapet on the asphalt ones. opts.parapet(road, k, a, b) -> false to leave a stretch open. + K.roads = function (L, opts) { + opts = opts || {}; + L.roads.forEach(function (r) { + var asph = r.mat === 'asphalt'; + var lift = asph ? 0.05 : r.mat === 'basalt' ? 0.07 : 0.09; + var all = r.pts.map(function (p, i) { var onB = (r.segs[i] && r.segs[i].bridge) || (i > 0 && r.segs[i - 1].bridge); return { x: p[0], z: p[1], y: onB ? p[2] - 0.03 : null }; }); + // the paved strip, in runs: a steep stepped stretch is a built stair with its own steps, so no strip under it + var isStair = function (k) { var a = r.pts[k], b = r.pts[k + 1]; return r.steps && !r.segs[k].bridge && Math.abs(b[2] - a[2]) / Math.hypot(b[0] - a[0], b[1] - a[1]) > 0.3; }; + var run = []; + for (var q = 0; q < r.pts.length; q++) { + run.push(all[q]); + if (q === r.pts.length - 1 || isStair(q)) { + if (run.length > 1) { + B.ribbon(r.mat, run, r.w + (r.pave || 0), { col: C(asph ? '#c9c0b2' : r.mat === 'basalt' ? '#d9cfc0' : '#d8d0c4'), uvs: asph ? 4 : r.mat === 'basalt' ? 2.4 : 3, cls: 'shell', lift: lift }); + if (asph && !r.noLine) B.ribbon('paint', run, 0.14, { col: C('#e8e4d8'), cls: 'detail', lift: lift + 0.025 }); + } + run = []; + } + } + for (var k = 0; k < r.pts.length - 1; k++) { + var a = r.pts[k], b = r.pts[k + 1], sg = r.segs[k]; + var grade = Math.abs(b[2] - a[2]) / Math.hypot(b[0] - a[0], b[1] - a[1]); + // steep stepped lanes are built stairs (their own ramp to walk on: the 2 m heightfield is too coarse for a + // narrow path across a steep slope); gentler ones are steps laid on the ground + if (r.steps && !sg.bridge && grade > 0.3) K.stair(a[0], a[1], a[2] + 0.06, b[0], b[1], b[2] + 0.06, r.w, { sideMat: 'rubble' }); + else if (r.steps && !sg.bridge && grade > 0.08) K.steps(a[0], a[1], W.terrainH(a[0], a[1]), b[0], b[1], W.terrainH(b[0], b[1]), r.w); + for (var t = 0; t <= 1; t += 0.2) K.occMark(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, r.w + 1, r.w + 1, 0, 0, 2); + if (asph && !sg.tunnel && !sg.bridge && (!opts.parapet || opts.parapet(r, k, a, b) !== false)) { + var dx = b[0] - a[0], dz = b[1] - a[1], Ln = Math.hypot(dx, dz), sx = -dz / Ln, sz = dx / Ln; + if (sz < 0) { sx = -sx; sz = -sz; } // the side toward the sea (+z) + var off = r.w / 2 + 0.35; + K.parapet(a[0] + sx * off, a[1] + sz * off, a[2], b[0] + sx * off, b[1] + sz * off, b[2]); + } + } + }); + }; + // a stone parapet between two points that may differ in height (coast road, viewpoints): rubble wall, flat cap + K.parapet = function (x0, z0, y0, x1, z1, y1, opts) { + opts = opts || {}; + var L = Math.hypot(x1 - x0, z1 - z0), n = Math.max(1, Math.round(L / 9)), yaw = Math.atan2(x1 - x0, z1 - z0) + Math.PI / 2, h = opts.h || 0.95; + for (var i = 0; i < n; i++) { + var ta = i / n, tb = (i + 1) / n, cx = x0 + (x1 - x0) * (ta + tb) / 2, cz = z0 + (z1 - z0) * (ta + tb) / 2, ya = y0 + (y1 - y0) * ta, yb = y0 + (y1 - y0) * tb; + var lo = Math.min(ya, yb, W.terrainH(cx, cz)) - (opts.deep || 1.6), top = (ya + yb) / 2 + h; + B.box(opts.mat || 'rubble', cx, lo, cz, L / n + 0.05, top - lo, 0.45, yaw, { col: C(opts.col || '#d6ccba'), uvs: 2, cls: 'shell', ao: 0.15, topMat: 'stone', topUvs: 1.5 }); + W.addBox({ x: cx, z: cz, y0: lo, y1: top, hx: L / n / 2, hz: 0.23, yaw: yaw, mat: 'stone', cover: true, kind: 'parapet' }); + } + }; + // stone steps drawn over a sloped path (collision stays the smooth terrain or a ramp box) + K.steps = function (x0, z0, y0, x1, z1, y1, width, opts) { + opts = opts || {}; + var L = Math.hypot(x1 - x0, z1 - z0), rise = y1 - y0, n = Math.max(1, Math.round(Math.abs(rise) / (opts.riser || 0.17))), yaw = Math.atan2(x1 - x0, z1 - z0); + var cc = C(opts.col || '#cfc6b6'), cd = C(opts.col2 || opts.col || '#c6bcab'), up = rise >= 0, hw = width / 2; + var c = Math.cos(yaw), s = Math.sin(yaw), run = L / n, h = B.bucket(opts.mat || 'stone', (x0 + x1) / 2, (z0 + z1) / 2, opts.cls || 'detail'), dk = new T.Color(); + function P(lx, y, lz) { return V3(x0 + lx * c + lz * s, y, z0 - lx * s + lz * c); } + // each step is a tread and the riser on its downhill side (the sides are hidden by the ground or the stair's body) + for (var i = 0; i < n; i++) { + var za = run * i, zb = run * (i + 1), yy = y0 + rise * (up ? i + 1 : i) / n, col = i % 2 ? cc : cd, lo = yy - Math.abs(rise) / n - 0.02; + B.quad(h, P(-hw, yy, za), P(-hw, yy, zb), P(hw, yy, zb), P(hw, yy, za), [0, za / 1.2, 0, zb / 1.2, width / 1.2, zb / 1.2, width / 1.2, za / 1.2], col); + dk.copy(col).multiplyScalar(0.8); + if (up) B.quad(h, P(hw, lo, za), P(-hw, lo, za), P(-hw, yy, za), P(hw, yy, za), [0, 0, width / 1.2, 0, width / 1.2, 0.15, 0, 0.15], dk, dk, col, col); + else B.quad(h, P(-hw, lo, zb), P(hw, lo, zb), P(hw, yy, zb), P(-hw, yy, zb), [0, 0, width / 1.2, 0, width / 1.2, 0.15, 0, 0.15], dk, dk, col, col); + } + }; + // a free-standing stair: steps, a solid body under them, a ramp box to walk on, optional side walls + K.stair = function (x0, z0, y0, x1, z1, y1, width, opts) { + opts = opts || {}; + var L = Math.hypot(x1 - x0, z1 - z0), yaw = Math.atan2(x1 - x0, z1 - z0), cx = (x0 + x1) / 2, cz = (z0 + z1) / 2, lo = Math.min(y0, y1), hi = Math.max(y0, y1); + var base = opts.base != null ? opts.base : Math.min(lo, W.terrainH(x0, z0), W.terrainH(x1, z1)) - 0.5; + K.steps(x0, z0, y0, x1, z1, y1, width, { col: opts.col, col2: opts.col2, mat: opts.mat, depth: 0.5, cls: opts.cls }); + // the body: a wedge under the steps (two side triangles and the underside are enough) + var c = Math.cos(yaw), s = Math.sin(yaw), hw = width / 2, bc = C(opts.sideCol || '#bdb3a2'), h = B.bucket(opts.sideMat || 'rubble', cx, cz, 'shell'); + function P(lx, y, lz) { return V3(cx + lx * c + lz * s, y, cz - lx * s + lz * c); } + var ya = y0 - 0.45, yb = y1 - 0.45; + [-1, 1].forEach(function (sd) { + var a = P(sd * hw, base, -L / 2), b = P(sd * hw, base, L / 2), cA = P(sd * hw, ya, -L / 2), cB = P(sd * hw, yb, L / 2); + if (sd > 0) B.quad(h, b, a, cA, cB, [L / 2, base / 2, 0, base / 2, 0, ya / 2, L / 2, yb / 2], bc); else B.quad(h, a, b, cB, cA, [0, base / 2, L / 2, base / 2, L / 2, yb / 2, 0, ya / 2], bc); + }); + var e0 = y0 > y1 ? -L / 2 : L / 2, ye = hi - 0.45; // the tall end + if (y0 > y1) B.quad(h, P(hw, base, e0), P(-hw, base, e0), P(-hw, ye, e0), P(hw, ye, e0), [0, base / 2, width / 2, base / 2, width / 2, ye / 2, 0, ye / 2], bc); + else B.quad(h, P(-hw, base, e0), P(hw, base, e0), P(hw, ye, e0), P(-hw, ye, e0), [0, base / 2, width / 2, base / 2, width / 2, ye / 2, 0, ye / 2], bc); + W.addBox({ x: cx, z: cz, y0: base, y1: hi, hx: hw, hz: L / 2, yaw: yaw, mat: 'stone', ramp: [y0, y1], kind: 'stairs', deck: true }); + if (opts.walls) [-1, 1].forEach(function (sd) { + if (opts.walls === 'L' && sd > 0 || opts.walls === 'R' && sd < 0) return; + var n = Math.max(1, Math.round(L / 3.2)), wh = opts.wallH || 1.0; + for (var k = 0; k < n; k++) { + var ta = (k + 0.5) / n, wy = y0 + (y1 - y0) * ta, lz = -L / 2 + L * ta, lx = sd * (hw + 0.2); + var wl = Math.abs(y1 - y0) / n; + B.box('stucco', cx + lx * c + lz * s, base, cz - lx * s + lz * c, 0.4, wy + wl / 2 + wh - base, L / n + 0.02, yaw, { col: C(opts.wallCol || '#e6dfd0'), uvs: 3, cls: 'shell', collide: 'plaster', cover: true, kind: 'wall' }); + } + }); + }; + + // ------------------------------------------------------------------ walls + K.wall = function (x0, z0, x1, z1, y, h, t, hex, opts) { + opts = opts || {}; + var L = Math.hypot(x1 - x0, z1 - z0), yaw = Math.atan2(x1 - x0, z1 - z0) + Math.PI / 2; + var cx = (x0 + x1) / 2, cz = (z0 + z1) / 2; + var gy = Math.min(W.terrainH(x0, z0), W.terrainH(x1, z1), W.terrainH(cx, cz)); + var yb = y == null ? gy : y, lo = Math.min(yb, gy) - 0.5; + var b = B.box(opts.mat || 'aged', cx, lo, cz, L, yb + h - lo, t || 0.4, yaw, { col: C(hex || '#e9e1d0'), collide: opts.cmat || 'plaster', cover: !opts.noCover, kind: opts.kind || 'wall', uvs: opts.uvs || 3, cls: 'shell' }); + if (opts.cap) B.box('stone', cx, yb + h, cz, L + 0.1, 0.1, (t || 0.4) + 0.14, yaw, { col: C('#e4dccb'), ao: 0, cls: 'shell', uvs: 1.5 }); + return b; + }; + // classical balustrade (terraces): rail, plinth and turned balusters + K.balustrade = function (x0, z0, x1, z1, y, opts) { + opts = opts || {}; + var L = Math.hypot(x1 - x0, z1 - z0), yaw = Math.atan2(x1 - x0, z1 - z0) + Math.PI / 2, cx = (x0 + x1) / 2, cz = (z0 + z1) / 2; + var h = opts.h || 1.0, cc = C(opts.col || '#e8e0d2'); + B.box('stone', cx, y + h - 0.12, cz, L, 0.14, 0.34, yaw, { col: cc, ao: 0, cls: 'shell', uvs: 1.5 }); + B.box('stone', cx, y, cz, L, 0.16, 0.38, yaw, { col: cc, ao: 0, cls: 'shell', uvs: 1.5 }); + var n = Math.floor(L / 0.34); + for (var i = 0; i < n; i++) { + var t = (i + 0.5) / n; + B.geo('stone', B.geos.cyl6, x0 + (x1 - x0) * t, y + 0.16, z0 + (z1 - z0) * t, 0, 0.16, h - 0.3, 0.16, cc, { uvs: 1, cls: 'detail' }); + } + for (i = 0; i <= Math.round(L / 4); i++) { t = i / Math.max(1, Math.round(L / 4)); B.box('stone', x0 + (x1 - x0) * t, y, z0 + (z1 - z0) * t, 0.36, h + 0.06, 0.36, yaw, { col: cc, ao: 0.1, cls: 'shell', uvs: 1.5 }); } + W.addBox({ x: cx, z: cz, y0: y, y1: y + h, hx: L / 2, hz: 0.17, yaw: yaw, mat: 'stone', cover: !opts.noCover, kind: 'balustrade', see: true }); + }; + // an iron railing (cut-out texture) with collision + K.railing = function (x0, z0, y0, x1, z1, y1, opts) { + opts = opts || {}; + var L = Math.hypot(x1 - x0, z1 - z0), h = opts.h || 1.0, bk = B.bucket('rail', (x0 + x1) / 2, (z0 + z1) / 2, 'flat'); + B.quad(bk, V3(x0, y0, z0), V3(x1, y1, z1), V3(x1, y1 + h, z1), V3(x0, y0 + h, z0), [0, 0, L, 0, L, 1, 0, 1], C('#ffffff')); + if (!opts.noCol) W.addBox({ x: (x0 + x1) / 2, z: (z0 + z1) / 2, y0: Math.min(y0, y1), y1: Math.max(y0, y1) + h, hx: L / 2, hz: 0.06, yaw: Math.atan2(x1 - x0, z1 - z0) + Math.PI / 2, mat: 'metal', see: true, kind: 'railing' }); + }; + + // ------------------------------------------------------------------ plants + function leaf(x, y, z, sx, sy, sz, hex, rot) { B.leaf(x, y, z, sx, sy, sz, Cv(hex, 0.85 + Math.random() * 0.3), rot); } + K.leaf = leaf; + K.tree = function (kind, x, z, y) { + y = y == null ? W.terrainH(x, z) : y; + var r = Math.random, i; + if (kind === 'pine') { // umbrella pine: tall bare trunk, flat wide crown + var h = 8.5 + r() * 5, lx = (r() - 0.5) * 0.22, lz = (r() - 0.5) * 0.22; + B.geo('bark', B.geos.cyl6, x, y - 0.3, z, 0, 0.5, h, 0.5, C('#6f5d4f'), { pitch: lx, roll: lz, cls: 'shell', uvs: 1 }); + var tx = x - Math.sin(lz) * h * 0.95, tz = z + Math.sin(lx) * h * 0.95; + B.geo('foliage', B.geos.blob, tx, y + h + 0.4, tz, r() * 3, 6.5 + r() * 2, 1.7, 6.5 + r() * 2, C('#33491f'), { cls: 'shell' }); + for (i = 0; i < 8; i++) { var a = i / 8 * 6.28, rr = i ? 2.6 + r() * 1.5 : 0; leaf(tx + Math.cos(a) * rr, y + h + 0.5 + r() * 0.7, tz + Math.sin(a) * rr, 5 + r() * 2, 1.7 + r(), 5 + r() * 2, '#415e2c'); } + W.addBox({ x: x, z: z, y0: y - 1, y1: y + h * 0.8, hx: 0.3, hz: 0.3, mat: 'wood', see: true }); + } else if (kind === 'cypress') { + var hc = 8 + r() * 6; + B.geo('foliage', B.geos.cone5, x, y + 0.5, z, r() * 3, 2.0, hc, 2.0, C('#2c4a26'), { cls: 'shell' }); + for (i = 0; i < 4; i++) { var t = i / 4; leaf(x, y + 1.2 + t * hc * 0.8, z, 2.3 * (1 - t * 0.7), hc / 3.6, 2.3 * (1 - t * 0.7), '#2c4a2a'); } + W.addBox({ x: x, z: z, y0: y - 1, y1: y + hc, hx: 0.6, hz: 0.6, mat: 'wood', see: true }); + } else if (kind === 'palm') { + var hp = 6 + r() * 3; + B.geo('bark', B.geos.cyl6, x, y - 0.2, z, 0, 0.36, hp, 0.36, C('#8a7a68'), { pitch: (r() - 0.5) * 0.16, cls: 'shell', uvs: 1 }); + for (i = 0; i < 7; i++) leaf(x, y + hp, z, 5, 1.2, 1.6, '#4d7a35', i / 7 * 6.28); + W.addBox({ x: x, z: z, y0: y - 1, y1: y + hp, hx: 0.25, hz: 0.25, mat: 'wood', see: true }); + } else if (kind === 'lemon') { + B.geo('bark', B.geos.cyl6, x, y - 0.2, z, 0, 0.2, 1.5, 0.2, C('#6d5a45'), { cls: 'detail', uvs: 1 }); + leaf(x + 0.3, y + 1.7, z - 0.2, 2.2, 1.9, 2.2, '#3d6328'); + leaf(x, y + 2.0, z, 2.7, 2.2, 2.7, '#47712e'); + for (i = 0; i < 3; i++) leaf(x + (r() - 0.5) * 1.7, y + 1.5 + r() * 1.1, z + (r() - 0.5) * 1.7, 0.36, 0.36, 0.36, '#f2d23a'); + } else if (kind === 'olive') { + B.geo('bark', B.geos.cyl6, x, y - 0.2, z, 0, 0.36, 2.3, 0.36, C('#7d7162'), { pitch: (r() - 0.5) * 0.4, roll: (r() - 0.5) * 0.4, cls: 'detail', uvs: 1 }); + for (i = 0; i < 3; i++) leaf(x + (r() - 0.5) * 2, y + 2.6 + r(), z + (r() - 0.5) * 2, 2.6, 1.8, 2.6, '#7d8a5a'); + } else if (kind === 'agave') { + for (i = 0; i < 2; i++) leaf(x, y + 0.45, z, 1.5, 1.0, 1.5, '#6f8f7a'); + } else { // scrub (maquis) on the cliffs + leaf(x, y + 0.4, z, 1.5 + r() * 1.5, 0.8 + r() * 0.8, 1.5 + r() * 1.5, r() < 0.3 ? '#6d7a45' : '#4b6233'); + } + }; + // bougainvillea or ivy on a wall face: F is a face frame from faceFrame() + K.climbers = function (F, len, y0, top, hex) { + var n = 5 + Math.floor(Math.random() * 6), u0 = (Math.random() - 0.5) * len * 0.5; + for (var i = 0; i < n; i++) { + var u = u0 + (Math.random() - 0.5) * len * 0.45, yy = y0 + 0.8 + Math.random() * Math.min(top - y0 - 1, 7), p = fp(F, u, yy, 0.28); + leaf(p.x, p.y, p.z, 1.4 + Math.random(), 1.2 + Math.random(), 0.7, Math.random() < 0.75 ? hex : '#3f6b2c'); + } + }; + K.planter = function (x, y, z, yaw, opts) { + opts = opts || {}; + if (opts.pot) { + B.geo('stucco', B.geos.cyl8, x, y, z, 0, 0.62, 0.55, 0.62, C('#b5643f'), { cls: 'detail', uvs: 1 }); + leaf(x, y + 0.9, z, 1.1, 1.0, 1.1, opts.hex || (M.hash2(x, z) < 0.5 ? '#3f6b2c' : '#c43d77')); + } else { + B.box('stucco', x, y, z, 0.6, 0.32, 0.26, yaw, { col: C('#b5643f'), ao: 0, cls: 'detail' }); + leaf(x, y + 0.5, z, 0.8, 0.6, 0.8, opts.hex || (M.hash2(x, z) < 0.5 ? '#c43d77' : '#d1443a')); + } + }; + // a pergola: posts, beams, a roof of leaves; lemons: hanging fruit dots + K.pergola = function (x, z, w, d, y, yaw, opts) { + opts = opts || {}; + var c = Math.cos(yaw || 0), s = Math.sin(yaw || 0), h = opts.h || 2.5, nx = Math.max(1, Math.round(w / 3.2)), nz = Math.max(1, Math.round(d / 3.2)), pc = C(opts.col || '#7a5f44'); + for (var i = 0; i <= nx; i++) for (var j = 0; j <= nz; j++) { + var lx = -w / 2 + w * i / nx, lz = -d / 2 + d * j / nz, px = x + lx * c + lz * s, pz = z - lx * s + lz * c; + if (opts.stone) B.box('stucco', px, y, pz, 0.4, h, 0.4, yaw, { col: C('#efe9dc'), cls: 'shell', collide: opts.noCol ? null : 'plaster', kind: 'pillar' }); + else B.geo('bark', B.geos.cyl6, px, y, pz, 0, 0.13, h, 0.13, pc, { cls: 'detail', uvs: 1 }); + } + for (i = 0; i <= nx; i++) { lx = -w / 2 + w * i / nx; B.box('bark', x + lx * c, y + h, z - lx * s, 0.1, 0.1, d + 0.5, yaw, { col: pc, ao: 0, cls: 'detail' }); } + for (j = 0; j <= nz * 2; j++) { lz = -d / 2 + d * j / (nz * 2); B.box('bark', x + lz * s, y + h + 0.1, z + lz * c, w + 0.5, 0.07, 0.07, yaw, { col: pc, ao: 0, cls: 'detail' }); } + var nl = Math.round(w * d / 9); + for (i = 0; i < nl; i++) { lx = (Math.random() - 0.5) * w; lz = (Math.random() - 0.5) * d; leaf(x + lx * c + lz * s, y + h + 0.15, z - lx * s + lz * c, 3.2, 0.7, 3.2, opts.leaf || '#4b6d33'); if (opts.lemons) leaf(x + lx * c + lz * s + 0.5, y + h - 0.25, z - lx * s + lz * c, 0.3, 0.3, 0.3, '#f2d23a'); } + }; + + // ------------------------------------------------------------------ houses + // a face frame: centre x,z; yaw; lx,lz the face's centre in house space; nx,nz its outward normal in house space + function faceFrame(x, z, c, s, lx, lz, nx, nz) { return { x: x, z: z, c: c, s: s, lx: lx, lz: lz, nx: nx, nz: nz, tx: nz, tz: -nx, yaw: 0 }; } + function fp(F, u, y, o) { var px = F.lx + F.tx * u + F.nx * o, pz = F.lz + F.tz * u + F.nz * o; return V3(F.x + px * F.c + pz * F.s, y, F.z - px * F.s + pz * F.c); } + var UV01 = [0, 0, 1, 0, 1, 1, 0, 1]; + // a rectangle on a face from u0..u1 along it, y0..y1, pushed out by o + function fq(mat, F, u0, u1, y0, y1, colr, o, uv, cls, c2) { + var bk = B.bucket(mat, F.x, F.z, cls); + B.quad(bk, fp(F, u0, y0, o), fp(F, u1, y0, o), fp(F, u1, y1, o), fp(F, u0, y1, o), uv || [u0, y0, u1, y0, u1, y1, u0, y1], colr, colr, c2 || colr, c2 || colr); + } + K.faceFrame = faceFrame; K.fq = fq; K.fp = fp; + // a box sitting on a face (sills, balcony slabs, lanterns): centre u, bottom y, size w x h, sticking out dep + function fbox(mat, F, u, y, w, h, dep, colr, cls, o) { + var p = fp(F, u, y, (o || 0) + dep / 2); + B.box(mat, p.x, y, p.z, w, h, dep, F.fyaw, { col: colr, ao: 0, cls: cls || 'detail' }); + } + K.WALLS = ['#f1ebdd', '#ede2c6', '#efd9a0', '#ebc79a', '#e8b897', '#e4a998', '#efe6d2', '#d99f6f', '#f3e3b5', '#e9cfa8', '#f4efe6', '#e7c08a']; + K.PASTEL = ['#f4eee2', '#f0c9a6', '#eaa58c', '#f2dca2', '#e8b4a0', '#f6f1e8', '#e6966f', '#f1d3b4', '#dfa07e', '#f3e6c4', '#f7f3ec', '#e9bfa9', '#d98a6a', '#f2e2cf']; + K.SHUTTERS = ['#3e6b52', '#2f5d4a', '#4f7a5a', '#6b4b33', '#3a6a72', '#e9e5db', '#7f9a86', '#2f4f6e']; + K.DOORS = ['#5b3b26', '#3e5a48', '#6e4a2e', '#2f4a5e', '#4a3324', '#7a5a3a']; + var hipCache = {}; + K.hipGeo = function (w, d, h) { + var k = w.toFixed(1) + '|' + d.toFixed(1) + '|' + h.toFixed(1); if (hipCache[k]) return hipCache[k]; + var r = Math.min(w, d) / 2, hw = w / 2, hd = d / 2, rx = Math.max(0, hw - r), rz = Math.max(0, hd - r); + var p = [-hw, 0, -hd, hw, 0, -hd, hw, 0, hd, -hw, 0, hd, -rx, h, -rz, rx, h, -rz, rx, h, rz, -rx, h, rz]; + var idx = [3, 2, 6, 3, 6, 7, 1, 0, 4, 1, 4, 5, 2, 1, 5, 2, 5, 6, 0, 3, 7, 0, 7, 4]; + var g = new T.BufferGeometry(), pos = [], uv = []; + for (var i = 0; i < idx.length; i++) { + var j = idx[i] * 3, f = Math.floor(i / 6), along = f < 2 ? p[j] : p[j + 2], up = Math.hypot(p[j + 1], (f < 2 ? Math.abs(p[j + 2]) - hd : Math.abs(p[j]) - hw)); + pos.push(p[j], p[j + 1], p[j + 2]); uv.push(along * 0.6, up * 0.6); + } + g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setAttribute('uv', new T.Float32BufferAttribute(uv, 2)); g.computeVertexNormals(); + return (hipCache[k] = g); + }; + + // house: centre x,z; width w (local x, along the street), depth d; yaw: local +z faces the street. + // opts: floors, wall, shutter, door (sRGB hex), roof ('flat'|'vault'|'tile'|'dome'), base (street level y; default the + // ground in front), shop (true or a sign index), sides ('party': blank side walls), noBack (blank back wall), + // arched (arched top-floor windows), balc (0..1 chance per bay), awning, lamp, plain (no clutter), grille + K.house = function (x, z, w, d, yaw, opts) { + opts = opts || {}; + var floors = opts.floors || 3, c = Math.cos(yaw), s = Math.sin(yaw), r = Math.random, i; + var hs = []; + for (var a = -1; a <= 1; a += 2) for (var b = -1; b <= 1; b += 2) hs.push(W.terrainH(x + (a * w / 2) * c + (b * d / 2) * s, z - (a * w / 2) * s + (b * d / 2) * c)); + var yFront = opts.base != null ? opts.base : W.terrainH(x + (d / 2 + 0.8) * s, z + (d / 2 + 0.8) * c); + var gMin = Math.min(hs[0], hs[1], hs[2], hs[3], yFront) - 0.6, gMax = Math.max(hs[0], hs[1], hs[2], hs[3]); + var y0 = yFront; + // a house dug deep into the hill gets extra storeys so some of it shows above the ground behind + if (opts.base == null && gMax - y0 > (floors - 1.2) * FH) floors = Math.min(6, Math.ceil((gMax - y0) / FH + 1.3)); + var top = y0 + floors * FH; + var wc = Cv(opts.wall || K.WALLS[0], 0.95 + r() * 0.07), wd = wc.clone().multiplyScalar(0.74), sc = C(opts.shutter || K.SHUTTERS[0]); + var white = C('#ffffff'), stoneC = C('#ddd4c4'), trim = C('#f1ece1'); + K.houses++; + // ---- collision, far box, foundation + W.addBox({ x: x, z: z, y0: gMin, y1: top, hx: w / 2, hz: d / 2, yaw: yaw, mat: 'plaster', kind: 'house' }); + var faces = [faceFrame(x, z, c, s, 0, d / 2, 0, 1), faceFrame(x, z, c, s, 0, -d / 2, 0, -1), faceFrame(x, z, c, s, w / 2, 0, 1, 0), faceFrame(x, z, c, s, -w / 2, 0, -1, 0)]; + var lens = [w, w, d, d], fy = [yaw, yaw + Math.PI, yaw + Math.PI / 2, yaw - Math.PI / 2]; + var roof = opts.roof || 'flat', roofC = roof === 'tile' ? C('#c47a52') : roof === 'flat' ? Cv(r() < 0.5 ? '#c9b6a2' : '#d9d2c4', 0.9) : wc; + var bays = [], blank = []; + for (var f = 0; f < 4; f++) { + faces[f].fyaw = fy[f]; + blank[f] = (f === 1 && (opts.noBack || opts.base == null)) || (f > 1 && opts.sides === 'party') || lens[f] < 2.6; + bays[f] = Math.max(1, Math.round(lens[f] / 3.3)); + var n = bays[f], len = lens[f], F = faces[f], mat = blank[f] ? 'aged' : 'facade'; + var uv = blank[f] ? [0, y0 / 3, len / 3, y0 / 3, len / 3, top / 3, 0, top / 3] : [0, 0, n, 0, n, floors, 0, floors]; + fq(mat, F, -len / 2, len / 2, y0, top, wc, 0, uv, 'far'); + // shell: a darker foot (rising damp, splashes), then the wall + var v1 = 1.3 / FH, uvA = blank[f] ? [0, y0 / 3, len / 3, y0 / 3, len / 3, (y0 + 1.3) / 3, 0, (y0 + 1.3) / 3] : [0, 0, n, 0, n, v1, 0, v1]; + var uvB = blank[f] ? [0, (y0 + 1.3) / 3, len / 3, (y0 + 1.3) / 3, len / 3, top / 3, 0, top / 3] : [0, v1, n, v1, n, floors, 0, floors]; + fq(mat, F, -len / 2, len / 2, y0, y0 + 1.3, wd, 0, uvA, 'shell', wc); + fq(mat, F, -len / 2, len / 2, y0 + 1.3, top, wc, 0, uvB, 'shell'); + } + var hf = B.bucket('aged', x, z, 'far'); + B.quad(hf, fp(faces[0], -w / 2, top, 0), fp(faces[0], w / 2, top, 0), fp(faces[1], -w / 2, top, 0), fp(faces[1], w / 2, top, 0), [0, 0, 1, 0, 1, 1, 0, 1], roofC); + if (y0 - gMin > 0.05) B.box('rubble', x, gMin, z, w + 0.1, y0 - gMin + 0.02, d + 0.1, yaw, { col: C('#b9ada0'), ao: 0.3, noTop: true, uvs: 2, cls: 'shell' }); + // stone or painted base course on the street side, a cornice, a string course under the first-floor windows + if (!opts.noPlinth) B.box(opts.plinthMat || 'stone', x, y0, z, w + 0.07, 0.85, d + 0.07, yaw, { col: C(opts.plinth || '#c9bfb0'), ao: 0.25, noTop: false, uvs: 1.6, cls: 'shell' }); + B.box('stucco', x, top - 0.26, z, w + 0.36, 0.26, d + 0.36, yaw, { col: trim, ao: 0.12, uvs: 3, cls: 'shell', bottom: true }); + if (floors > 2 && M.hash2(x * 0.7, z * 1.3) < 0.6) B.box('stucco', x, y0 + FH - 0.08, z, w + 0.12, 0.14, d + 0.12, yaw, { col: trim, ao: 0, uvs: 3, cls: 'detail', noTop: false }); + + // ---- windows, doors, balconies: drawn near the camera only, exactly over the painted bays + var Bz = RP.MapTex.BAY, doorBay = Math.floor(bays[0] / 2), shopN = 0, lowQ = RP.R.qname === 'low'; + var doorC = C(opts.door || K.DOORS[Math.floor(M.hash2(x, z * 3) * K.DOORS.length)]); + for (f = 0; f < 4; f++) { + if (blank[f] || (lowQ && f > 0)) continue; // Low keeps the painted bays on the side walls and draws real windows on the front only + n = bays[f]; len = lens[f]; F = faces[f]; + var sp = len / n, hw = Bz.hw * sp, shw = Bz.sh * sp; + for (var bay = 0; bay < n; bay++) { + var u = -len / 2 + sp * (bay + 0.5); + var colBalc = f === 0 && M.hash2(x + bay * 13.7, z - 3.1) < (opts.balc == null ? 0.38 : opts.balc); + for (var fl = 0; fl < floors; fl++) { + var fyb = y0 + fl * FH, wy = fyb + 1.0, wh = 1.5; + if (f !== 0 && fl < 2) { // side and back windows the hill has buried + var gp = fp(F, u, 0, 0.4); if (W.terrainH(gp.x, gp.z) > wy - 0.5) continue; + } + if (fl === 0 && f === 0) { + if (bay === doorBay && !opts.noDoor) { + // front door in a stone frame, a fanlight over some + var dw = Math.min(0.78, sp * 0.3); + fq('dark', F, u - dw - 0.02, u + dw + 0.02, y0, y0 + 2.42, white, 0.045); + fq('door', F, u - dw, u + dw, y0, y0 + 2.36, doorC, 0.06, UV01); + fq('stone', F, u - dw - 0.2, u - dw, y0, y0 + 2.5, stoneC, 0.075); fq('stone', F, u + dw, u + dw + 0.2, y0, y0 + 2.5, stoneC, 0.075); + fq('stone', F, u - dw - 0.26, u + dw + 0.26, y0 + 2.42, y0 + 2.7, stoneC, 0.085); + if (M.hash2(x * 2.1, z) < 0.5) { var pd = fp(F, u, y0 + 2.7, 0.07); B.geo('window', B.geos.halfDisc, pd.x, pd.y, pd.z, F.fyaw, dw * 2, dw * 1.6, 1, white, { cls: 'flat' }); } + // a step or two where the street is lower than the floor + var gd = fp(F, u, 0, 0.7), gy = W.terrainH(gd.x, gd.z); + if (y0 - gy > 0.14) { var stp = fp(F, u, 0, 0.45); B.box('stone', stp.x, Math.min(gy, y0 - 0.5) - 0.2, stp.z, dw * 2 + 0.7, y0 - Math.min(gy, y0 - 0.5) + 0.2, 0.9, F.fyaw, { col: stoneC, cls: 'detail', uvs: 1.2 }); } + if (opts.lamp !== false && M.hash2(x, z * 1.9) < 0.7) K.wallLamp(F, u + dw + 0.7, y0 + 2.75); + continue; + } + if (opts.shop != null && opts.shop !== false) { + var sw = Math.min(1.25, sp * 0.42), si = (typeof opts.shop === 'number' ? opts.shop : Math.floor(M.hash2(x * 1.7, z * 0.9) * 16)) + shopN; + fq('shop', F, u - sw, u + sw, y0 + 0.02, y0 + 2.5, white, 0.06, UV01); + var suv = RP.MapTex.signUV(si); + fq('sign', F, u - Math.min(sw, 1.15), u + Math.min(sw, 1.15), y0 + 2.56, y0 + 3.0, white, 0.08, [suv[0], suv[1], suv[2], suv[1], suv[2], suv[3], suv[0], suv[3]]); + if (opts.awning !== false && M.hash2(x + bay, z * 2.3) < 0.75) K.awning(F, u, y0 + 2.52, sw * 2 + 0.2, 1.25, (si + bay) % 4); + shopN++; + continue; + } + // ground-floor window behind an iron grille + fq('window', F, u - hw, u + hw, wy, wy + wh, white, 0.035, UV01); + fq('rail', F, u - hw - 0.05, u + hw + 0.05, wy - 0.05, wy + wh + 0.05, white, 0.1, [0, 0, hw * 2 + 0.1, 0, hw * 2 + 0.1, 1.2, 0, 1.2]); + continue; + } + var balc = colBalc && fl > 0 && M.hash2(x - fl * 3.3, z + bay) < 0.8; + var arched = opts.arched && fl === floors - 1 && fl > 0; + var w0 = balc ? fyb + 0.12 : wy, w1 = wy + wh + (arched ? 0 : 0); + fq('window', F, u - hw, u + hw, w0, w1, white, 0.035, UV01); + if (arched) { var pa = fp(F, u, w1, 0.035); B.geo('window', B.geos.halfDisc, pa.x, pa.y, pa.z, F.fyaw, hw * 2, hw * 2, 1, white, { cls: 'flat', vScale: 0.5 }); } + // louvred shutters: open against the wall, a few closed, a few half open + var hsh = M.hash2(x * 3 + bay + f * 7, z + fl * 7); + if (hsh < 0.16) { fq('louvre', F, u - hw, u, w0, w1, sc, 0.06, UV01); fq('louvre', F, u, u + hw, w0, w1, sc, 0.06, UV01); } + else { + fq('louvre', F, u - hw - shw - 0.012 * sp, u - hw - 0.012 * sp, w0, w1, sc, 0.055, UV01); + fq('louvre', F, u + hw + 0.012 * sp, u + hw + shw + 0.012 * sp, w0, w1, sc, 0.055, UV01); + } + if (f === 0 || fl > 0) { + if (balc) K.balcony(F, u, fyb + 0.02, hw * 2 + shw * 1.2 + 0.5, opts); + else if (f === 0) fq('stone', F, u - hw - 0.12, u + hw + 0.12, wy - 0.11, wy, stoneC, 0.09); + } + if (opts.frames && f === 0) fq('stucco', F, u - hw - 0.1, u + hw + 0.1, w1, w1 + 0.16, trim, 0.05, null, 'flat'); + } + } + } + // ---- roof + if (roof === 'flat') { + B.quad(B.bucket('paving', x, z, 'shell'), fp(faces[0], -w / 2, top, 0), fp(faces[0], w / 2, top, 0), fp(faces[1], -w / 2, top, 0), fp(faces[1], w / 2, top, 0), [0, 0, w / 3, 0, w / 3, d / 3, 0, d / 3], roofC); + // parapet: the outer faces are part of the shell; the inner faces and the top are drawn near the camera only + var pc = wc, ph = 0.8, pt = 0.24; + B.box('aged', x, top, z, w, ph, d, yaw, { col: pc, ao: 0.1, uvs: 3, cls: 'shell', noTop: true }); + for (f = 0; f < 4; f++) { + var PF = faces[f], pl = lens[f], pb = B.bucket('aged', x, z, 'detail'), po = -pt; + B.quad(pb, fp(PF, pl / 2 - pt, top, po), fp(PF, -pl / 2 + pt, top, po), fp(PF, -pl / 2 + pt, top + ph, po), fp(PF, pl / 2 - pt, top + ph, po), [0, 0, pl / 3, 0, pl / 3, ph / 3, 0, ph / 3], pc); + B.quad(pb, fp(PF, -pl / 2, top + ph, 0), fp(PF, pl / 2, top + ph, 0), fp(PF, pl / 2 - pt, top + ph, po), fp(PF, -pl / 2 + pt, top + ph, po), [0, 0, pl / 3, 0, pl / 3, 0.1, 0, 0.1], trim); + } + if (!opts.plain) K.roofClutter(x, z, w, d, yaw, top, wc); + } else if (roof === 'vault') { + // barrel vaults running front to back, the classic roof of the coast + var nv = M.clamp(Math.round(w / 4.6), 1, 3), vw = w / nv, vr = Math.min(vw * 0.34, 1.7), vcol = Cv('#f2ede2', 0.97); + for (i = 0; i < nv; i++) { + var vx = -w / 2 + vw * (i + 0.5), cxv = x + vx * c, czv = z - vx * s; + B.geo('stucco', B.geos.vault8, cxv, top, czv, yaw, vw, vr * 2, d, vcol, { uvs: 3, cls: 'shell' }); + var e1 = fp(faces[0], vx, top, 0), e2 = fp(faces[1], -vx, top, 0); + B.geo('aged', B.geos.halfDisc7, e1.x, e1.y, e1.z, yaw, vw, vr * 2, 1, wc, { cls: 'shell', uScale: vw / 3, vScale: vr / 3 }); + B.geo('aged', B.geos.halfDisc7, e2.x, e2.y, e2.z, yaw + Math.PI, vw, vr * 2, 1, wc, { cls: 'shell', uScale: vw / 3, vScale: vr / 3 }); + } + } else if (roof === 'dome') { + // a low whitewashed dome on a flat roof (Positano), parapet round it + var dr = Math.min(w, d) * 0.78; + B.quad(B.bucket('stucco', x, z, 'shell'), fp(faces[0], -w / 2, top, 0), fp(faces[0], w / 2, top, 0), fp(faces[1], -w / 2, top, 0), fp(faces[1], w / 2, top, 0), [0, 0, w / 3, 0, w / 3, d / 3, 0, d / 3], Cv('#efe9dc', 0.95)); + B.geo('stucco', B.geos.hemi8, x, top, z, yaw, dr, dr * 0.62, dr, Cv('#f4f0e6', 0.98), { uScale: 4, vScale: 2, cls: 'shell' }); + B.box('aged', x, top, z, w, 0.45, d, yaw, { col: wc, ao: 0, uvs: 3, cls: 'shell', noTop: true }); + } else { + B.geo('roof', K.hipGeo(w + 0.7, d + 0.7, Math.min(w, d) * 0.3), x, top, z, yaw, 1, 1, 1, white, { cls: 'shell' }); + } + // ---- dressing: drainpipe, climbers, laundry, plants by the door + if (!opts.plain) { + if (M.hash2(x * 1.9, z * 0.3) < 0.45) fbox('metal', faces[0], w / 2 - 0.25, y0 + 0.3, 0.09, top - y0 - 0.6, 0.09, C('#8f8a80'), 'detail'); + if (M.hash2(x * 1.3, z) < 0.32) K.climbers(faces[0], w, y0, top, M.hash2(x, z * 2) < 0.6 ? '#c2337a' : '#3f6b2c'); + if (floors > 1 && M.hash2(x * 0.37, z * 2.9) < (opts.laundry == null ? 0.22 : opts.laundry)) K.laundry(faces[0], (M.hash2(x, z) - 0.5) * w * 0.4, y0 + FH * (1 + Math.floor(M.hash2(z, x) * (floors - 1))) + 0.75, Math.min(3.4, w * 0.5)); + if (opts.base != null && M.hash2(x * 5.1, z * 0.77) < 0.4) { var pp = fp(faces[0], -w / 2 + 0.7 + M.hash2(x, z) * 0.5, 0, 0.5); K.planter(pp.x, yFront, pp.z, 0, { pot: true }); } + } + return { top: top, y0: y0, faces: faces, floors: floors }; + }; + // balcony on a face: slab, iron railing (three cut-out quads), sometimes flower boxes + K.balcony = function (F, u, y, w, opts) { + var dep = 0.85, slabC = C('#e2d9c9'), white = C('#ffffff'); + fbox('stone', F, u, y - 0.12, w, 0.12, dep, slabC, 'detail', 0); + var a = fp(F, u - w / 2, y, dep - 0.03), b = fp(F, u + w / 2, y, dep - 0.03), a0 = fp(F, u - w / 2, y, 0), b0 = fp(F, u + w / 2, y, 0), h = B.bucket('rail', F.x, F.z, 'flat'); + B.quad(h, a, b, V3(b.x, y + 1, b.z), V3(a.x, y + 1, a.z), [0, 0, w, 0, w, 1, 0, 1], white); + B.quad(h, a0, a, V3(a.x, y + 1, a.z), V3(a0.x, y + 1, a0.z), [0, 0, dep, 0, dep, 1, 0, 1], white); + B.quad(h, b, b0, V3(b0.x, y + 1, b0.z), V3(b.x, y + 1, b.z), [0, 0, dep, 0, dep, 1, 0, 1], white); + if (M.hash2(F.x + u * 3, F.z + y) < 0.45) { var p = fp(F, u + (M.hash2(u, y) - 0.5) * w * 0.4, y + 0.02, dep - 0.2); K.planter(p.x, y + 0.02, p.z, F.fyaw); } + }; + // a striped awning sloping out from a face; variant 0..3 picks the cloth + K.awning = function (F, u, y, w, out, variant) { + var h = B.bucket('awning', F.x, F.z, 'detail'), u0 = (variant % 4) * 0.25 + 0.001, u1 = u0 + 0.248, drop = 0.5, white = C('#ffffff'); + var a = fp(F, u - w / 2, y + 0.25, 0.05), b = fp(F, u + w / 2, y + 0.25, 0.05), cP = fp(F, u + w / 2, y + 0.25 - drop, out), d = fp(F, u - w / 2, y + 0.25 - drop, out); + B.quad(h, d, cP, b, a, [u0, 0, u1, 0, u1, 1, u0, 1], white); + B.quad(h, V3(d.x, d.y - 0.22, d.z), V3(cP.x, cP.y - 0.22, cP.z), cP, d, [u0, 0, u1, 0, u1, 0.2, u0, 0.2], white); + }; + // a washing line along a face with a few cloths + K.laundry = function (F, u, y, len) { + var CL = ['#f4f0e8', '#e9e2d0', '#9fb7c9', '#d9a0a0', '#f1d98a', '#f4f0e8', '#b9c9a8']; + fbox('metal', F, u, y + 0.0, len, 0.015, 0.015, C('#d8d4cc'), 'detail', 0.45); + var n = Math.max(2, Math.round(len / 0.8)), h = B.bucket('fabric', F.x, F.z, 'detail'); + for (var i = 0; i < n; i++) { + var cu = u - len / 2 + len * (i + 0.5) / n, cw = 0.28 + M.hash2(cu, y) * 0.3, chh = 0.45 + M.hash2(y, cu) * 0.55; + var cc = C(CL[Math.floor(M.hash2(cu * 3, y * 7) * CL.length)]); + B.quad(h, fp(F, cu - cw / 2, y - chh, 0.46), fp(F, cu + cw / 2, y - chh, 0.5), fp(F, cu + cw / 2, y, 0.46), fp(F, cu - cw / 2, y, 0.46), UV01, cc); + } + }; + // a lantern on a wall bracket (lights up at dusk) + K.wallLamp = function (F, u, y) { + var p = fp(F, u, y, 0.32); + fbox('metal', F, u, y + 0.3, 0.04, 0.04, 0.36, C('#1f1c1a'), 'detail', 0); + B.box('metal', p.x, y + 0.26, p.z, 0.2, 0.06, 0.2, F.fyaw, { col: C('#1f1c1a'), ao: 0, cls: 'detail' }); + B.box('lamp', p.x, y - 0.04, p.z, 0.16, 0.3, 0.16, F.fyaw, { cls: 'flat', ao: 0 }); + K.LAMPS.push(V3(p.x, y + 0.1, p.z)); + }; + // things on a flat roof terrace: water tank, chimney, pergola, pots, an aerial, a line of washing + K.roofClutter = function (x, z, w, d, yaw, top, wc) { + var c = Math.cos(yaw), s = Math.sin(yaw), h = M.hash2(x * 0.91, z * 1.37), k = Math.floor(h * 8); + function at(lx, lz) { return { x: x + lx * c + lz * s, z: z - lx * s + lz * c }; } + var p; + if (k === 0 || k === 5) { p = at(w * 0.2, -d * 0.2); B.box('aged', p.x, top, p.z, 1.6, 1.5, 1.6, yaw, { col: wc, cls: 'shell', uvs: 3 }); } + if (k === 1 || k === 6) { p = at(-w * 0.18, -d * 0.2); B.geo('paint', B.geos.cyl8, p.x, top + 0.25, p.z, 0, 1.1, 1.2, 1.1, C('#cfd3d4'), { cls: 'detail' }); B.box('metal', p.x, top, p.z, 1.0, 0.25, 1.0, yaw, { col: C('#6b6a68'), cls: 'detail', ao: 0 }); } + if (k === 2 && w > 5 && d > 5) K.pergola(x, z, w * 0.5, d * 0.5, top, yaw, { h: 2.2, noCol: true, leaf: '#4f7636' }); + if (k === 3 || k === 7) { p = at(w * 0.25, d * 0.1); B.box('aged', p.x, top, p.z, 0.6, 1.3, 0.6, yaw, { col: wc, cls: 'detail', uvs: 3 }); B.box('roof', p.x, top + 1.3, p.z, 0.8, 0.12, 0.8, yaw, { col: C('#ffffff'), cls: 'detail', ao: 0 }); } + if (k === 4 || k === 6) { p = at(-w * 0.3, d * 0.25); K.planter(p.x, top, p.z, 0, { pot: true }); p = at(w * 0.3, d * 0.3); K.planter(p.x, top, p.z, 0, { pot: true, hex: '#3f6b2c' }); } + if (h > 0.55) { p = at(-w * 0.3, -d * 0.3); B.box('metal', p.x, top, p.z, 0.03, 2.2, 0.03, yaw, { col: C('#55524e'), cls: 'detail', ao: 0 }); B.box('metal', p.x, top + 1.9, p.z, 0.8, 0.02, 0.02, yaw, { col: C('#55524e'), cls: 'detail', ao: 0 }); } + }; + // an arcade (portico) in front of a row of buildings: piers, round arches, a terrace on top. + // from (x0,z0) to (x1,z1) along the building line; out: depth toward the open side (left of the direction a->b) + K.arcade = function (x0, z0, x1, z1, y, out, opts) { + opts = opts || {}; + var L = Math.hypot(x1 - x0, z1 - z0), n = Math.max(1, Math.round(L / (opts.bay || 3.6))), dx = (x1 - x0) / L, dz = (z1 - z0) / L, ox = dz, oz = -dx; + var yaw = Math.atan2(dx, dz) + Math.PI / 2, h = opts.h || 3.4, wc = C(opts.col || '#efe6d3'), bw = L / n; + for (var i = 0; i <= n; i++) { + var px = x0 + dx * L * i / n + ox * (out - 0.3), pz = z0 + dz * L * i / n + oz * (out - 0.3); + B.box('stone', px, y, pz, 0.62, h - 0.9, 0.62, yaw, { col: C('#e4dccd'), collide: 'stone', cover: true, kind: 'pillar', cls: 'shell', uvs: 1.5 }); + B.box('stone', px, y + h - 0.95, pz, 0.78, 0.14, 0.78, yaw, { col: C('#efe9dc'), ao: 0, cls: 'detail', uvs: 1.5 }); + } + // the arch wall above the piers: a band with half-disc openings (dark discs read as the arch soffits) + var cx = (x0 + x1) / 2 + ox * (out - 0.3), cz = (z0 + z1) / 2 + oz * (out - 0.3); + B.box('aged', cx, y + h - 0.9, cz, L + 0.62, 1.5, 0.5, yaw, { col: wc, ao: 0.1, uvs: 3, cls: 'shell' }); + for (i = 0; i < n; i++) { + var ax = x0 + dx * L * (i + 0.5) / n + ox * (out - 0.04), az = z0 + dz * L * (i + 0.5) / n + oz * (out - 0.04); + B.geo('dark', B.geos.halfDisc, ax, y + h - 0.9, az, yaw - Math.PI / 2 + Math.PI / 2, bw - 0.7, (bw - 0.7) * 0.72, 1, C('#ffffff'), { cls: 'flat' }); + } + // roof slab (a terrace) and its ceiling + var mx = (x0 + x1) / 2 + ox * out / 2, mz = (z0 + z1) / 2 + oz * out / 2; + B.box('aged', mx, y + h + 0.6, mz, L + 0.6, 0.28, out + 0.3, yaw, { col: wc, uvs: 3, cls: 'shell', bottom: true, ao: 0.2, topMat: 'paving' }); + W.addBox({ x: mx, z: mz, y0: y + h + 0.5, y1: y + h + 0.9, hx: L / 2 + 0.3, hz: out / 2 + 0.15, yaw: yaw, mat: 'plaster', kind: 'roof' }); + if (opts.rail !== false) K.railing(x0 + ox * out, z0 + oz * out, y + h + 0.88, x1 + ox * out, z1 + oz * out, y + h + 0.88, { noCol: true }); + }; + // a building bridging a lane (supportico): two side piers, rooms above, a vault under them + K.archOver = function (x, z, yaw, span, depth, y, opts) { + opts = opts || {}; + var c = Math.cos(yaw), s = Math.sin(yaw), clear = opts.clear || 3.3, floors = opts.floors || 2, wc = C(opts.wall || '#efe4cc'), top = y + clear + floors * FH; + [-1, 1].forEach(function (sd) { + var lx = sd * (span / 2 + 0.45); + B.box('aged', x + lx * c, y - 1, z - lx * s, 0.9, clear + 1.2, depth, yaw, { col: wc, uvs: 3, cls: 'shell', collide: 'plaster', kind: 'pier', cover: true }); + }); + B.box('facade', x, y + clear, z, span + 1.8, floors * FH, depth, yaw, { col: wc, cls: 'shell', fitUV: [Math.max(1, Math.round((span + 1.8) / 3.3)), floors], topMat: 'paving', ao: 0.12 }); + B.box('facade', x, y + clear, z, span + 1.8, floors * FH, depth, yaw, { col: wc, cls: 'far', fitUV: [Math.max(1, Math.round((span + 1.8) / 3.3)), floors], noTop: false }); + W.addBox({ x: x, z: z, y0: y + clear, y1: top, hx: span / 2 + 0.9, hz: depth / 2, yaw: yaw, mat: 'plaster', kind: 'house' }); + B.geo('aged', B.geos.vault, x, y + clear - span * 0.25, z, yaw, span, span * 0.5, depth, Cv('#e6dac0', 0.85), { uvs: 3, cls: 'shell', inside: true }); + [-1, 1].forEach(function (sd) { B.geo('aged', K.archGeo(span, span * 0.25 + 0.02, span * 0.25), x + sd * (depth / 2 + 0.01) * s, y + clear - span * 0.25, z + sd * (depth / 2 + 0.01) * c, sd > 0 ? yaw : yaw + Math.PI, 1, 1, 1, wc, { cls: 'shell', uvs: 3 }); }); + B.box('stucco', x, top - 0.2, z, span + 2.1, 0.22, depth + 0.3, yaw, { col: C('#f1ece1'), ao: 0, cls: 'shell', uvs: 3 }); + W.addZone({ x0: x - span / 2 - depth / 2, z0: z - span / 2 - depth / 2, x1: x + span / 2 + depth / 2, z1: z + span / 2 + depth / 2, y0: y - 1, y1: y + clear, indoor: true, name: opts.name || 'archway' }); + K.LAMPS.push(V3(x, y + clear - 0.6, z)); B.box('lamp', x, y + clear - 0.75, z, 0.2, 0.3, 0.2, yaw, { cls: 'flat', ao: 0 }); + }; + // houses along both sides of a road (pts [[x,z,y],...], width w): tight frontage, shops on the ground floor + K.frontage = function (pts, w, rnd, opts) { + opts = opts || {}; + var placed = 0; + for (var k = opts.from || 0; k < Math.min(pts.length - 1, opts.to == null ? 1e9 : opts.to); k++) { + var a = pts[k], b = pts[k + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), dir = Math.atan2(b[0] - a[0], b[1] - a[1]); + var nx = Math.cos(dir), nz = -Math.sin(dir), u = 0, rowId = K.occId; K.occId += 3; + while (u < L - 2) { + var hwid = (opts.minW || 6) + rnd() * (opts.varW || 4), t = (u + hwid / 2) / L; + for (var side = -1; side <= 1; side += 2) { + if (opts.side && opts.side !== side) continue; + var d = (opts.minD || 8) + rnd() * 3, off = w / 2 + 0.8 + d / 2; + var x = a[0] + (b[0] - a[0]) * t + nx * off * side, z = a[1] + (b[1] - a[1]) * t + nz * off * side; + var yaw = dir + (side > 0 ? -Math.PI / 2 : Math.PI / 2); + if (!K.occFree(x, z, hwid - 0.2, d, yaw, 0.1, 0.3, rowId + side)) { + // no room for a house: a garden wall keeps the street closed in (unless a lane or a square opens here) + if (opts.walls === false) continue; + var wo = w / 2 + 0.75, t0 = u / L, t1 = Math.min(1, (u + hwid) / L), clear = true; + var wx0 = a[0] + (b[0] - a[0]) * t0 + nx * wo * side, wz0 = a[1] + (b[1] - a[1]) * t0 + nz * wo * side, wx1 = a[0] + (b[0] - a[0]) * t1 + nx * wo * side, wz1 = a[1] + (b[1] - a[1]) * t1 + nz * wo * side; + for (var q = 0; q <= 6 && clear; q++) { + var qx = wx0 + (wx1 - wx0) * q / 6, qz = wz0 + (wz1 - wz0) * q / 6, qo = K.occ[occIdx(qx, qz)]; + if (K.land.onRoad(qx, qz, 0.5) || K.land.onRoad(qx + nx * side * 1.5, qz + nz * side * 1.5, 0.5) || (qo && qo !== 2)) clear = false; + } + if (clear && Math.hypot(wx1 - wx0, wz1 - wz0) > 1.5) { + var wy = Math.min(a[2] + (b[2] - a[2]) * t0, a[2] + (b[2] - a[2]) * t1), wh = 2.3 + Math.abs(b[2] - a[2]) * (t1 - t0); + K.wall(wx0, wz0, wx1, wz1, wy, wh, 0.45, rnd() < 0.5 ? '#e6dccb' : '#d9cdb6', { cap: true, mat: rnd() < 0.4 ? 'rubble' : 'aged', cmat: 'stone', uvs: 2.6 }); + if (rnd() < 0.6) { var lx2 = (wx0 + wx1) / 2 + nx * side * 0.5, lz2 = (wz0 + wz1) / 2 + nz * side * 0.5; leaf(lx2, wy + wh + 0.3, lz2, 2.6, 1.3, 1.6, rnd() < 0.5 ? '#c2337a' : '#3f6b2c'); leaf(lx2 + (wx1 - wx0) * 0.2, wy + wh + 0.2, lz2 + (wz1 - wz0) * 0.2, 2.2, 1.2, 1.4, '#3f6b2c'); } + if (rnd() < 0.3) K.tree(rnd() < 0.5 ? 'lemon' : 'olive', (wx0 + wx1) / 2 + nx * side * 2.6, (wz0 + wz1) / 2 + nz * side * 2.6); + } + continue; + } + var pal = opts.palette || K.WALLS; + K.house(x, z, hwid - 0.15, d, yaw, { floors: (opts.minF || 3) + Math.floor(rnd() * (opts.varF || 3)), wall: pal[Math.floor(rnd() * pal.length)], shutter: K.SHUTTERS[Math.floor(rnd() * K.SHUTTERS.length)], + roof: opts.roofs ? opts.roofs(rnd) : rnd() < 0.3 ? 'vault' : 'flat', shop: rnd() < (opts.shops == null ? 0.5 : opts.shops) ? true : null, arched: rnd() < 0.3, sides: opts.sides === undefined ? 'party' : opts.sides, noBack: true, laundry: 0.35, balc: opts.balc, + base: W.terrainH(x - nx * side * (d / 2 + 0.8), z - nz * side * (d / 2 + 0.8)) }); + K.occMark(x, z, hwid, d, yaw, 0.2, rowId + side); placed++; + } + u += hwid; + } + } + return placed; + }; + // houses scattered up a slope in rows along the contours, each facing downhill. + // region: { x0, x1, z0, z1, ok(x, z, h) -> bool }, opts: rowStep, minW, palette, floors [min, var], roofs(rnd) -> kind + K.fillSlope = function (reg, rnd, opts) { + opts = opts || {}; + var n = 0, pal = opts.palette || K.WALLS, nrm = new T.Vector3(); + for (var z = reg.z1; z > reg.z0; z -= (opts.rowStep || 7.5)) { + for (var x = reg.x0; x < reg.x1; x += (opts.minStep || 6.5) + rnd() * (opts.varStep || 4)) { + var xx = x + (rnd() - 0.5) * 4, zz = z + (rnd() - 0.5) * 4, h0 = W.terrainH(xx, zz); + if (h0 < (opts.minH || 3) || h0 > (opts.maxH || 95)) continue; + if (reg.ok && !reg.ok(xx, zz, h0)) continue; + W.terrainN(xx, zz, nrm); + if (nrm.y < (opts.minNy || 0.42)) continue; + var w2 = (opts.minW || 6) + rnd() * (opts.varW || 5), d2 = (opts.minD || 6) + rnd() * (opts.varD || 4); + var yaw2 = Math.atan2(nrm.x, nrm.z); // face downhill + if (opts.faceTo) { var fa = Math.atan2(opts.faceTo[0] - xx, opts.faceTo[1] - zz); yaw2 = nrm.y > 0.97 ? fa : yaw2 + M.wrap(fa - yaw2) * (opts.facePull || 0.3); } + yaw2 = Math.round(yaw2 / (Math.PI / 8)) * (Math.PI / 8); + if (!K.occFree(xx, zz, w2, d2, yaw2, opts.gap == null ? 0.8 : opts.gap)) continue; + if (opts.gaps !== false && M.noise2(xx * 0.04, zz * 0.04) < 0.22 && (!reg.core || !reg.core(xx, zz))) continue; // gaps of garden and rock + var fl = opts.floors || [2, 3]; + K.house(xx, zz, w2, d2, yaw2, { floors: fl[0] + Math.floor(rnd() * fl[1]), wall: pal[Math.floor(rnd() * pal.length)], shutter: K.SHUTTERS[Math.floor(rnd() * K.SHUTTERS.length)], + roof: opts.roofs ? opts.roofs(rnd) : (rnd() < 0.35 ? 'vault' : (rnd() < 0.12 ? 'tile' : (rnd() < 0.04 ? 'dome' : 'flat'))), arched: rnd() < 0.25, balc: opts.balc, noPlinth: rnd() < 0.5 }); + K.occMark(xx, zz, w2, d2, yaw2, opts.mark == null ? 0.6 : opts.mark); n++; + if (rnd() < (opts.trees == null ? 0.35 : opts.trees)) { + var tx = xx + (rnd() - 0.5) * 10 + Math.sin(yaw2) * (d2 / 2 + 2), tz = zz + Math.cos(yaw2) * (d2 / 2 + 2); + if (!K.occAt(tx, tz) && !K.land.onRoad(tx, tz, 1)) K.tree(rnd() < 0.5 ? 'lemon' : 'olive', tx, tz); + } + } + } + return n; + }; + + // ------------------------------------------------------------------ street furniture and props + K.lamp = function (x, z, y, opts) { + y = y == null ? W.terrainH(x, z) : y; + var dk = C('#1f1c1a'); + B.geo('metal', B.geos.cyl8, x, y, z, 0, 0.2, 0.5, 0.2, dk, { cls: 'detail' }); + B.geo('metal', B.geos.cyl6, x, y + 0.5, z, 0, 0.1, 3.1, 0.1, dk, { cls: 'shell' }); + B.box('metal', x, y + 3.55, z, 0.34, 0.06, 0.34, 0, { col: dk, ao: 0, cls: 'detail' }); + B.geo('metal', B.geos.cone5, x, y + 3.95, z, 0, 0.4, 0.22, 0.4, dk, { cls: 'detail' }); + B.box('lamp', x, y + 3.62, z, 0.22, 0.34, 0.22, 0, { cls: 'flat', ao: 0 }); + K.LAMPS.push(V3(x, y + 3.8, z)); + W.addBox({ x: x, z: z, y0: y, y1: y + 3.8, hx: 0.09, hz: 0.09, mat: 'metal', see: true }); + }; + K.crate = function (x, z, yaw, h, hex, y) { + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; h = h || 1; + B.box('wood', x, y, z, 1.1, h, 1.1, yaw || 0, { col: C(hex || '#a98a63'), collide: 'wood', cover: true, kind: 'crate', uvs: 1, cls: 'detail' }); + }; + // small stacking fruit / fish crates (no cover: too low) + K.box = function (x, z, y, yaw, hex, n) { + for (var i = 0; i < (n || 1); i++) B.box('wood', x + (M.hash2(x, i) - 0.5) * 0.08, y + i * 0.3, z, 0.6, 0.28, 0.42, (yaw || 0) + (M.hash2(z, i) - 0.5) * 0.3, { col: C(hex || '#b99a6e'), cls: 'detail', uvs: 0.8 }); + }; + K.bollard = function (x, z, y, kind) { + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; + if (kind === 'iron') { B.geo('metal', B.geos.cyl8, x, y, z, 0, 0.36, 0.5, 0.36, C('#2b2826'), { cls: 'detail' }); B.geo('metal', B.geos.cyl8, x, y + 0.5, z, 0, 0.5, 0.14, 0.5, C('#2b2826'), { cls: 'detail' }); } + else { B.geo('stone', B.geos.cyl8, x, y, z, 0, 0.3, 0.8, 0.3, C('#d2c9b8'), { cls: 'detail', uvs: 1 }); B.geo('stone', B.geos.blob, x, y + 0.82, z, 0, 0.34, 0.26, 0.34, C('#d2c9b8'), { cls: 'detail' }); } + W.addBox({ x: x, z: z, y0: y, y1: y + (kind === 'iron' ? 0.64 : 0.9), hx: 0.18, hz: 0.18, mat: kind === 'iron' ? 'metal' : 'stone', see: true, kind: 'bollard' }); + }; + K.bin = function (x, z, y, yaw) { + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; + B.geo('paint', B.geos.cyl8, x, y, z, yaw || 0, 0.5, 0.85, 0.5, C('#3f5a48'), { cls: 'detail' }); + B.geo('metal', B.geos.cyl8, x, y + 0.85, z, 0, 0.56, 0.06, 0.56, C('#2b2a28'), { cls: 'detail' }); + W.addBox({ x: x, z: z, y0: y, y1: y + 0.9, hx: 0.26, hz: 0.26, mat: 'metal', cover: false, kind: 'bin', see: true }); + }; + K.bench = function (x, z, y, yaw) { + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; + var c = Math.cos(yaw || 0), s = Math.sin(yaw || 0); + B.box('wood', x, y + 0.4, z, 1.7, 0.07, 0.45, yaw, { col: C('#8a6a48'), cls: 'detail', ao: 0, bottom: true }); + B.box('wood', x - s * 0.24, y + 0.55, z - c * 0.24, 1.7, 0.4, 0.05, yaw, { col: C('#8a6a48'), cls: 'detail', ao: 0 }); + [-0.75, 0.75].forEach(function (o) { B.box('metal', x + o * c, y, z - o * s, 0.06, 0.42, 0.42, yaw, { col: C('#2a2725'), cls: 'detail', ao: 0 }); }); + W.addBox({ x: x, z: z, y0: y, y1: y + 0.5, hx: 0.85, hz: 0.25, yaw: yaw || 0, mat: 'wood', kind: 'bench', see: true }); + }; + K.cafeTable = function (x, z, y, opts) { + opts = opts || {}; + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; + B.geo('metal', B.geos.cyl6, x, y, z, 0, 0.07, 0.72, 0.07, C('#2a2725'), { cls: 'detail' }); + B.geo('paint', B.geos.cyl8, x, y + 0.72, z, 0, 0.8, 0.04, 0.8, C(opts.cloth || '#f6f1e6'), { cls: 'detail' }); + var n = opts.chairs == null ? 2 : opts.chairs, a0 = M.hash2(x, z) * 6.28; + for (var i = 0; i < n; i++) { + var a = a0 + i * 6.283 / n, cx = x + Math.cos(a) * 0.72, cz = z + Math.sin(a) * 0.72, cy = Math.atan2(x - cx, z - cz); + B.box('paint', cx, y + 0.42, cz, 0.42, 0.04, 0.42, cy, { col: C(opts.chair || '#3a3532'), cls: 'detail', ao: 0, bottom: true }); + B.box('paint', cx - Math.sin(cy) * 0.2, y + 0.46, cz - Math.cos(cy) * 0.2, 0.42, 0.42, 0.035, cy, { col: C(opts.chair || '#3a3532'), cls: 'detail', ao: 0 }); + B.box('metal', cx, y, cz, 0.34, 0.42, 0.34, cy, { col: C('#2a2725'), cls: 'detail', ao: 0, noTop: true }); + } + }; + // a sun umbrella: pole and a striped cone; variant 0..3 picks the cloth (see the awning layer) + K.umbrella = function (x, z, y, variant, opts) { + opts = opts || {}; + y = y == null ? W.terrainH(x, z) : y; + var r = opts.r || 2.5; + B.geo('metal', B.geos.cyl6, x, y, z, 0, 0.06, 2.35, 0.06, C('#e3e1dc'), { cls: 'detail' }); + B.geo('awning', B.geos.cone8, x, y + 1.95, z, M.hash2(x, z), r, 0.55, r, C('#ffffff'), { cls: 'shell', uScale: 0.248, uOff: (variant % 4) * 0.25 + 0.001 }); + }; + K.lounger = function (x, z, y, yaw, hex) { + y = y == null ? W.terrainH(x, z) : y; + B.box('fabric', x, y + 0.26, z, 0.66, 0.07, 1.85, yaw, { col: C(hex || '#f4f0e8'), ao: 0, cls: 'detail' }); + B.box('paint', x, y, z, 0.6, 0.26, 1.6, yaw, { col: C('#d9d4c8'), ao: 0.3, cls: 'detail', noTop: true }); + }; + // an invented small three-wheel delivery van and a compact car, parked as cover (driving comes in phase 2) + K.car = function (x, z, yaw, hex, kind, y) { + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; + var cc = C(hex), c = Math.cos(yaw), s = Math.sin(yaw), dk = C('#ffffff'), D = { cls: 'detail' }; + function wheel(lx, lz, rad) { B.geo('dark', B.geos.cyl8, x + lx * c + lz * s - c * 0.11 * Math.sign(lx || 1), y + rad, z - lx * s + lz * c + s * 0.11 * Math.sign(lx || 1), yaw, rad * 2, 0.22, rad * 2, dk, { roll: Math.PI / 2, cls: 'detail' }); } + if (kind === 'van') { + B.box('paint', x, y + 0.35, z, 1.4, 1.5, 1.4, yaw, { col: cc, ao: 0.2, cls: 'detail' }); + B.box('glass', x + s * 0.71, y + 1.05, z + c * 0.71, 1.2, 0.6, 0.02, yaw, { cls: 'detail' }); + B.box('wood', x - s * 1.4, y + 0.55, z - c * 1.4, 1.4, 0.7, 1.8, yaw, { col: C('#8a6a48'), cls: 'detail' }); + B.box('dark', x - s * 1.4, y + 0.1, z - c * 1.4, 1.2, 0.45, 1.5, yaw, { cls: 'detail' }); + wheel(0.01, 0.55, 0.3); wheel(0.7, -1.9, 0.3); wheel(-0.7, -1.9, 0.3); + W.addBox({ x: x - s * 0.6, z: z - c * 0.6, y0: y, y1: y + 1.85, hx: 0.72, hz: 1.55, yaw: yaw, mat: 'car', cover: true, kind: 'car' }); + return; + } + B.box('paint', x, y + 0.3, z, 1.66, 0.62, 3.8, yaw, { col: cc, ao: 0.2, cls: 'detail' }); + B.box('paint', x - s * 0.25, y + 0.92, z - c * 0.25, 1.46, 0.5, 2.0, yaw, { col: cc, ao: 0, cls: 'detail' }); + B.box('glass', x - s * 0.25, y + 0.95, z - c * 0.25, 1.49, 0.4, 2.04, yaw, { cls: 'detail', noTop: true }); + B.box('glass', x - s * 0.25, y + 0.95, z - c * 0.25, 1.3, 0.4, 2.04, yaw, { cls: 'detail', noTop: true }); + wheel(0.78, 1.2, 0.31); wheel(-0.78, 1.2, 0.31); wheel(0.78, -1.25, 0.31); wheel(-0.78, -1.25, 0.31); + B.box('lamp', x + s * 1.91, y + 0.62, z + c * 1.91, 1.3, 0.1, 0.02, yaw, { cls: 'flat' }); + B.box('paint', x - s * 1.91, y + 0.62, z - c * 1.91, 1.3, 0.1, 0.02, yaw, { col: C('#a02a22'), cls: 'flat', ao: 0 }); + B.box('dark', x, y + 0.12, z, 1.7, 0.2, 3.9, yaw, { cls: 'detail', noTop: true }); + W.addBox({ x: x, z: z, y0: y, y1: y + 1.42, hx: 0.84, hz: 1.92, yaw: yaw, mat: 'car', cover: true, kind: 'car' }); + }; + // an invented step-through scooter on its stand (low cover) + K.scooter = function (x, z, yaw, hex, y) { + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; + var c = Math.cos(yaw), s = Math.sin(yaw), cc = C(hex || '#c7d9d2'), dk = C('#ffffff'); + function P(lz) { return { x: x + lz * s, z: z + lz * c }; } + var p = P(0.62); B.geo('dark', B.geos.cyl8, p.x - c * 0.05, y + 0.22, p.z + s * 0.05, yaw, 0.44, 0.1, 0.44, dk, { roll: Math.PI / 2, cls: 'detail' }); + p = P(-0.62); B.geo('dark', B.geos.cyl8, p.x - c * 0.05, y + 0.22, p.z + s * 0.05, yaw, 0.44, 0.1, 0.44, dk, { roll: Math.PI / 2, cls: 'detail' }); + p = P(-0.45); B.box('paint', p.x, y + 0.28, p.z, 0.4, 0.42, 0.9, yaw, { col: cc, cls: 'detail', ao: 0.2 }); + B.box('dark', p.x, y + 0.7, p.z, 0.32, 0.1, 0.7, yaw, { cls: 'detail' }); + p = P(0.05); B.box('paint', p.x, y + 0.2, p.z, 0.36, 0.08, 0.5, yaw, { col: cc, cls: 'detail', ao: 0 }); + p = P(0.5); B.box('paint', p.x, y + 0.25, p.z, 0.42, 0.75, 0.12, yaw, { col: cc, cls: 'detail', ao: 0.1 }); + B.box('metal', p.x, y + 1.0, p.z, 0.62, 0.05, 0.05, yaw, { col: C('#3a3836'), cls: 'detail', ao: 0 }); + B.box('lamp', p.x + s * 0.07, y + 0.82, p.z + c * 0.07, 0.14, 0.12, 0.03, yaw, { cls: 'flat' }); + W.addBox({ x: x, z: z, y0: y, y1: y + 1.05, hx: 0.3, hz: 0.9, yaw: yaw, mat: 'metal', cover: true, kind: 'scooter' }); + }; + var boatG = {}; + function boatGeo(len) { + if (boatG[len]) return boatG[len]; + var g = new T.SphereGeometry(1, 12, 6, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2); + g.scale(1.05, 0.65, len / 2); g.translate(0, 0.6, 0); + var p = g.attributes.position; + for (var i = 0; i < p.count; i++) { var z = p.getZ(i), t = Math.abs(z) / (len / 2); p.setX(i, p.getX(i) * (1 - Math.pow(t, 3) * 0.7)); if (p.getY(i) > 0.55) p.setY(i, 0.6 + Math.pow(t, 2) * 0.35); } + g.computeVertexNormals(); + return (boatG[len] = g); + } + // trim for a gozzo of length len, in the hull's own space (so a hauled-out boat's tilt carries it): + // wood: the gunwale cap (outer rim to the inner hull) and two thwarts; band: the coloured strake under the rim and + // the tall stem posts at bow and stern + var trimG = {}; + function boatTrim(len) { + if (trimG[len]) return trimG[len]; + var hl = len / 2, N = 40, wood = { p: [], n: [] }, band = { p: [], n: [] }; + function rim(a) { // the hull's top edge (boatGeo's equator after its pinch and sheer) + var t = Math.abs(Math.sin(a)), x = 1.05 * Math.cos(a) * (1 - Math.pow(t, 3) * 0.7), z = hl * Math.sin(a), y = 0.6 + t * t * 0.35; + var nx = x / (1.05 * 1.05), nz = z / (hl * hl), l = Math.hypot(nx, nz) || 1; + return { x: x, y: y, z: z, nx: nx / l, nz: nz / l }; + } + function quad(o, a, b, c, d, n0, n1, out) { // a b (top) c d (bottom), normals n0 for a/c, n1 for b/d; out: wind for an outside face + var vs = out ? [a, b, c, b, d, c] : [a, c, b, b, c, d], ns = out ? [n0, n1, n0, n1, n1, n0] : [n0, n0, n1, n1, n0, n1]; + vs.forEach(function (v, i) { o.p.push(v[0], v[1], v[2]); var n = ns[i]; o.n.push(n[0], n[1], n[2]); }); + } + for (var i = 0; i < N; i++) { + var A = rim(i / N * 6.2832), Bq = rim((i + 1) / N * 6.2832); + // cap: outer rim down to the inner hull (scaled 0.93, 0.92, 0.96, as K.boat draws it), facing up + quad(wood, [A.x, A.y + 0.01, A.z], [Bq.x, Bq.y + 0.01, Bq.z], [A.x * 0.93, A.y * 0.92, A.z * 0.96], [Bq.x * 0.93, Bq.y * 0.92, Bq.z * 0.96], [0, 1, 0], [0, 1, 0]); + // the coloured strake just under the rim, standing proud of the planking + var o = 0.018; + quad(band, [A.x + A.nx * o, A.y - 0.03, A.z + A.nz * o], [Bq.x + Bq.nx * o, Bq.y - 0.03, Bq.z + Bq.nz * o], + [A.x + A.nx * o * 0.6, A.y - 0.17, A.z + A.nz * o * 0.6], [Bq.x + Bq.nx * o * 0.6, Bq.y - 0.17, Bq.z + Bq.nz * o * 0.6], [A.nx, 0, A.nz], [Bq.nx, 0, Bq.nz], true); + } + function box(o, w, h, d, x, y, z, rx) { + var g = new T.BoxGeometry(w, h, d); if (rx) g.rotateX(rx); g.translate(x, y, z); g = g.toNonIndexed(); + var P = g.attributes.position, Nn = g.attributes.normal; + for (var k = 0; k < P.count; k++) { o.p.push(P.getX(k), P.getY(k), P.getZ(k)); o.n.push(Nn.getX(k), Nn.getY(k), Nn.getZ(k)); } + } + [-0.12, 0.2].forEach(function (f) { var t = Math.abs(f) / 0.5, w = 2 * 1.05 * 0.9 * (1 - Math.pow(t, 3) * 0.7); box(wood, w, 0.05, 0.26, 0, 0.45, f * len); }); + box(band, 0.07, 0.62, 0.08, 0, 1.0, hl * 0.985, -0.18); // the bow's tall stem post, raked forward + box(band, 0.07, 0.42, 0.08, 0, 0.92, -hl * 0.985, 0.14); // the stern post + function geo(o) { var g = new T.BufferGeometry(); g.setAttribute('position', new T.Float32BufferAttribute(o.p, 3)); g.setAttribute('normal', new T.Float32BufferAttribute(o.n, 3)); return g; } + return (trimG[len] = { wood: geo(wood), band: geo(band) }); + } + // a small wooden boat (gozzo): afloat (y = sea level) or hauled out on the sand (y given, tilt) + K.boat = function (x, z, yaw, hex, len, y, tilt) { + len = len || 6; y = y == null ? -0.1 : y; + var band = C(M.hash2(x, z) < 0.5 ? '#2f6fa8' : M.hash2(x, z) < 0.75 ? '#3a8b6f' : '#b8433a'), O = { cls: 'detail', roll: tilt || 0 }, tr = boatTrim(len); + B.geo('paint', boatGeo(len), x, y, z, yaw, 1, 1, 1, C(hex || '#f2efe8'), { cls: 'shell', roll: tilt || 0 }); + B.geo('wood', boatGeo(len), x, y, z, yaw, 0.93, 0.92, 0.96, C('#8a6a48'), { cls: 'detail', roll: tilt || 0, inside: true }); // the open hull inside + B.geo('wood', tr.wood, x, y, z, yaw, 1, 1, 1, C('#a88458'), O); + B.geo('paint', tr.band, x, y, z, yaw, 1, 1, 1, band, O); + if (y > 0) W.addBox({ x: x, z: z, y0: y - 0.2, y1: y + 0.95, hx: 0.95, hz: len * 0.45, yaw: yaw, mat: 'wood', cover: true, kind: 'boat' }); + }; + // a heap of fishing nets with floats + K.nets = function (x, z, y, hex) { + y = y == null ? W.ground(x, z, W.terrainH(x, z) + 1).y : y; + B.geo('fabric', B.geos.blob, x, y + 0.12, z, M.hash2(x, z) * 3, 1.5, 0.5, 1.1, C(hex || '#4f7d6a'), { cls: 'detail' }); + for (var i = 0; i < 4; i++) B.geo('paint', B.geos.blob, x + (M.hash2(x, i) - 0.5) * 1.1, y + 0.3, z + (M.hash2(z, i) - 0.5) * 0.8, 0, 0.22, 0.22, 0.22, C(i % 2 ? '#e8743a' : '#f2efe6'), { cls: 'detail' }); + }; + // boulders: a few lumps of rock (sea stacks at the foot of cliffs, rockfall by the road) + K.rocks = function (x, z, y, r, n, opts) { + opts = opts || {}; + for (var i = 0; i < (n || 3); i++) { + var a = M.hash2(x + i, z) * 6.28, rr = i ? r * (0.5 + M.hash2(z, i) * 0.7) : 0, s = r * (i ? 0.45 + M.hash2(i, x) * 0.5 : 1); + var px = x + Math.cos(a) * rr, pz = z + Math.sin(a) * rr, py = (y == null ? W.terrainH(px, pz) : y) - s * 0.25; + B.geo('rock', B.geos.blob, px, py + s * 0.35, pz, a, s * 2.1, s * (opts.tall || 1.3), s * 1.8, Cv('#cfc6b4', 0.8 + M.hash2(px, pz) * 0.3), { cls: 'shell', uScale: 3, vScale: 2 }); + if (!opts.noCol && s > 0.5) W.addBox({ x: px, z: pz, y0: py - 1, y1: py + s * (opts.tall || 1.3) * 0.75, hx: s * 0.75, hz: s * 0.65, yaw: a, mat: 'stone', cover: s > 0.8, kind: 'rock' }); + } + }; + + // ------------------------------------------------------------------ arches + // a wall panel w wide and h tall (bottom centre at the origin, facing +z) with an arched opening that springs from its + // bottom edge and rises `rise`; pointed: a Gothic two-centred arch instead of a round/segmental one + var archCache = {}; + function archPts(w, rise, pointed, n) { + var pts = [], hw = w / 2; + for (var i = 0; i <= n; i++) { + var t = i / n, x = -hw + w * t, y; + if (pointed) y = rise * (1 - Math.pow(Math.abs(x) / hw, 1.7)); + else y = rise * Math.sqrt(Math.max(0, 1 - (x / hw) * (x / hw))); + pts.push([x, y]); + } + return pts; + } + K.archGeo = function (w, h, rise, pointed) { + var k = 'p' + w.toFixed(2) + '|' + h + '|' + rise + '|' + !!pointed; if (archCache[k]) return archCache[k]; + var n = 12, a = archPts(w - 0.02, rise, pointed, n), pos = [], uv = [], idx = []; + // a strip between the arch curve and the panel's top edge + for (var i = 0; i <= n; i++) { pos.push(a[i][0], a[i][1], 0, a[i][0], h, 0); uv.push(a[i][0], a[i][1], a[i][0], h); } + for (i = 0; i < n; i++) { var v = i * 2; idx.push(v, v + 2, v + 1, v + 1, v + 2, v + 3); } + var g = new T.BufferGeometry(); g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setAttribute('uv', new T.Float32BufferAttribute(uv, 2)); g.setIndex(idx); g.computeVertexNormals(); + return (archCache[k] = g); + }; + // the ring of voussoirs round an arch of span w and the given rise, t thick + K.archRing = function (w, rise, t, pointed) { + var k = 'r' + w.toFixed(2) + '|' + rise + '|' + t + '|' + !!pointed; if (archCache[k]) return archCache[k]; + var n = 12, a = archPts(w, rise, pointed, n), b = archPts(w + t * 2, rise + t, pointed, n), pos = [], uv = [], idx = []; + for (var i = 0; i <= n; i++) { pos.push(a[i][0], a[i][1], 0, b[i][0], b[i][1], 0); uv.push(i / n * 6, 0, i / n * 6, t); } + for (i = 0; i < n; i++) { var v = i * 2; idx.push(v, v + 2, v + 1, v + 1, v + 2, v + 3); } + var g = new T.BufferGeometry(); g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setAttribute('uv', new T.Float32BufferAttribute(uv, 2)); g.setIndex(idx); g.computeVertexNormals(); + return (archCache[k] = g); + }; + + // ------------------------------------------------------------------ tunnels and bridges + // A short rock tunnel on a road (one of the road's `tunnels` ranges [i0, i1], whose bed makeLand cut as a narrow + // trench): lined side walls and vault, a lid of rock with the hill's own shape over the trench, a stone arch at each mouth. + K.tunnel = function (L, road, range, opts) { + opts = opts || {}; + var i0 = range[0], i1 = range[1], w = road.w, clear = opts.clear || 5.2, hw = w / 2 + 0.6; + for (var k = i0; k < i1; k++) { + var a = road.pts[k], b = road.pts[k + 1], Ln = Math.hypot(b[0] - a[0], b[1] - a[1]), dir = Math.atan2(b[0] - a[0], b[1] - a[1]); + var cx = (a[0] + b[0]) / 2, cz = (a[1] + b[1]) / 2, c = Math.cos(dir), s = Math.sin(dir), ym = (a[2] + b[2]) / 2, yl = Math.min(a[2], b[2]); + // lining: side walls (collision) and the vault + [-1, 1].forEach(function (sd) { + B.box('concrete', cx + sd * (hw + 0.5) * c, yl - 1, cz - sd * (hw + 0.5) * s, 1.0, clear - 1.4 + 1 + (ym - yl), Ln + 0.4, dir, { col: C('#b9b2a4'), uvs: 3, cls: 'shell', collide: 'stone', kind: 'tunnel', ao: 0.3 }); + }); + B.geo('concrete', B.geos.vault, cx, ym + clear - 1.45, cz, dir, hw * 2 + 0.05, 2.9, Ln + 0.4, Cv('#b0a999', 0.85), { uvs: 3, cls: 'shell', inside: true }); + // a raised kerb along each wall + [-1, 1].forEach(function (sd) { B.box('concrete', cx + sd * (hw - 0.32) * c, yl - 0.5, cz - sd * (hw - 0.32) * s, 0.66, (ym - yl) + 0.5 + 0.2, Ln + 0.4, dir, { col: C('#a9a294'), uvs: 3, cls: 'shell', ao: 0 }); }); + // lamps along the crown + for (var q = 0; q < Math.max(1, Math.round(Ln / 12)); q++) { + var t = (q + 0.5) / Math.max(1, Math.round(Ln / 12)), lx = a[0] + (b[0] - a[0]) * t, lz = a[1] + (b[1] - a[1]) * t; + B.box('lamp', lx, ym + clear - 0.35, lz, 0.5, 0.08, 0.2, dir, { cls: 'flat', ao: 0 }); K.LAMPS.push(V3(lx, ym + clear - 0.5, lz)); + } + // the lid: the hill as it was before the trench, as a strip of terrain, and boxes to stand on and stop bullets + var half = hw + 4, st = 2, nu = Math.ceil(half * 2 / st), nv = Math.max(1, Math.ceil(Ln / st)), pos = [], nrm = [], idx = [], colA = []; + for (var j = 0; j <= nv; j++) for (var i = 0; i <= nu; i++) { + var lu = -half + (half * 2) * i / nu, lv = -Ln / 2 + Ln * j / nv, px = cx + lu * c + lv * s, pz = cz - lu * s + lv * c; + var hh = L.heightAt(px, pz, true), e = 1.5, hx = L.heightAt(px + e, pz, true) - L.heightAt(px - e, pz, true), hz = L.heightAt(px, pz + e, true) - L.heightAt(px, pz - e, true); + var nn = V3(-hx, 2 * e, -hz).normalize(); + pos.push(px, Math.max(hh, ym + clear + 0.3), pz); nrm.push(nn.x * 127, nn.y * 127, nn.z * 127); colA.push(181, 181, 181, 255); + } + for (j = 0; j < nv; j++) for (i = 0; i < nu; i++) { var v0 = j * (nu + 1) + i; idx.push(v0, v0 + 1, v0 + nu + 1, v0 + 1, v0 + nu + 2, v0 + nu + 1); } + var g = new T.BufferGeometry(); + g.setAttribute('position', new T.BufferAttribute(new Float32Array(pos), 3)); g.setAttribute('normal', new T.BufferAttribute(new Int8Array(nrm), 3, true)); + g.setAttribute('aCol', new T.BufferAttribute(new Uint8Array(colA), 4, true)); + g.setIndex(idx); g.computeBoundingSphere(); + var lid = new T.Mesh(g, RP.mat.land); lid.receiveShadow = true; lid.castShadow = true; lid.matrixAutoUpdate = false; lid.visible = false; + RP.R.scene.add(lid); var ch = B.chunkAt(cx, cz); (ch.extra = ch.extra || []).push(lid); + var nb = Math.max(1, Math.round(Ln / 6)); + for (q = 0; q < nb; q++) { + var t0 = (q + 0.5) / nb, bx = a[0] + (b[0] - a[0]) * t0, bz = a[1] + (b[1] - a[1]) * t0, top = 1e9; + for (i = -2; i <= 2; i++) top = Math.min(top, L.heightAt(bx + i * (hw / 2) * c, bz - i * (hw / 2) * s, true)); + W.addBox({ x: bx, z: bz, y0: ym + clear - 1.3, y1: Math.max(top, ym + clear + 0.3), hx: hw + 1.2, hz: Ln / nb / 2 + 0.2, yaw: dir, mat: 'stone', kind: 'tunnel' }); + } + } + // mouths: a ring of dressed stone round the opening, a rubble face above it + [[i0, 1], [i1, -1]].forEach(function (m) { + var p = road.pts[m[0]], q2 = road.pts[m[0] + m[1]], dir2 = Math.atan2(q2[0] - p[0], q2[1] - p[1]), c2 = Math.cos(dir2), s2 = Math.sin(dir2); + var mx = p[0] - s2 * 0.25, mz = p[1] - c2 * 0.25; + [-1, 1].forEach(function (sd) { + B.box('stone', mx + sd * (hw + 0.55) * c2, p[2] - 1, mz - sd * (hw + 0.55) * s2, 1.1, clear - 0.2, 0.9, dir2, { col: C('#cfc5b2'), uvs: 1.6, cls: 'shell', collide: 'stone', kind: 'portal', cover: true }); + B.box('rubble', mx + sd * (hw + 3.1) * c2, p[2] - 1, mz - sd * (hw + 3.1) * s2, 4.2, clear + 3.2, 0.7, dir2, { col: C('#c2b8a6'), uvs: 2.2, cls: 'shell', collide: 'stone', kind: 'portal' }); + }); + // the rock face above the mouth, up to the hill as it was before the trench + var hb = B.bucket('rock', mx, mz, 'shell'), half2 = hw + 4, nq = Math.ceil(half2), yb0 = p[2] + clear + 2.1, topMax = yb0, rc = C('#c9bfae'); + function hwPt(u, y) { return V3(mx - s2 * 0.1 + u * c2, y, mz - c2 * 0.1 - u * s2); } + function hwTop(u) { return Math.max(yb0, L.heightAt(mx + s2 * 1.2 + u * c2, mz + c2 * 1.2 - u * s2, true) + 0.3); } + for (var q3 = -nq; q3 < nq; q3++) { + var ua = q3 * half2 / nq, ub = (q3 + 1) * half2 / nq, ta = hwTop(ua), tb = hwTop(ub); topMax = Math.max(topMax, ta, tb); + B.quad(hb, hwPt(ub, yb0), hwPt(ua, yb0), hwPt(ua, ta), hwPt(ub, tb), [ub / 4, yb0 / 4, ua / 4, yb0 / 4, ua / 4, ta / 4, ub / 4, tb / 4], rc); + } + if (topMax > yb0 + 0.5) W.addBox({ x: mx + s2 * 0.5, z: mz + c2 * 0.5, y0: yb0, y1: topMax, hx: half2, hz: 0.6, yaw: dir2, mat: 'stone', kind: 'portal' }); + B.box('rubble', mx, p[2] + clear - 0.3, mz, hw * 2 + 2.2, 2.5, 0.7, dir2, { col: C('#c2b8a6'), uvs: 2.2, cls: 'shell', bottom: true }); + B.box('stone', mx, p[2] + clear - 1.25, mz, hw * 2 + 0.2, 1.0, 0.95, dir2, { col: C('#d6ccb9'), uvs: 1.6, cls: 'shell', bottom: true }); + B.geo('dark', B.geos.halfDisc, mx - s2 * 0.5, p[2] + clear - 1.25, mz - c2 * 0.5, dir2 + Math.PI, hw * 2, -2.6, 1, C('#ffffff'), { cls: 'flat' }); + W.addBox({ x: mx, z: mz, y0: p[2] + clear - 1.3, y1: p[2] + clear + 2.2, hx: hw + 5, hz: 0.4, yaw: dir2, mat: 'stone', kind: 'portal' }); + }); + }; + // A road bridge on a road's `bridge: [i0, i1]` segments: a deck to walk on, parapets, and tall stone arches under it. + K.bridge = function (L, road, opts) { + opts = opts || {}; + var i0 = road.bridge[0], i1 = road.bridge[1], w = road.w, sc = C(opts.col || '#cfc4b0'); + for (var k = i0; k < i1; k++) { + var a = road.pts[k], b = road.pts[k + 1], Ln = Math.hypot(b[0] - a[0], b[1] - a[1]), dir = Math.atan2(b[0] - a[0], b[1] - a[1]); + var cx = (a[0] + b[0]) / 2, cz = (a[1] + b[1]) / 2, c = Math.cos(dir), s = Math.sin(dir), ya = a[2], yb = b[2], ym = (ya + yb) / 2; + B.box('rubble', cx, ym - 1.5, cz, w + 1.6, 1.46, Ln + 0.3, dir, { col: sc, uvs: 2.2, cls: 'shell', bottom: true, noTop: true }); + W.addBox({ x: cx, z: cz, y0: ym - 1.5, y1: Math.max(ya, yb), hx: w / 2 + 0.8, hz: Ln / 2 + 0.15, yaw: dir, mat: 'stone', ramp: [ya, yb], deck: true, kind: 'bridge' }); + [-1, 1].forEach(function (sd) { + var ox = sd * (w / 2 + 0.5) * c, oz = -sd * (w / 2 + 0.5) * s; + B.box('rubble', cx + ox, ym - 0.2, cz + oz, 0.5, 1.25, Ln + 0.3, dir, { col: C('#d6ccba'), uvs: 2, cls: 'shell', topMat: 'stone', topUvs: 1.5 }); + W.addBox({ x: cx + ox, z: cz + oz, y0: ym - 1.5, y1: ym + 1.05, hx: 0.25, hz: Ln / 2 + 0.15, yaw: dir, mat: 'stone', cover: true, kind: 'parapet' }); + }); + // piers at each end of the span down to the ground, and an arch between them + var floor = Math.min(W.terrainH(cx, cz), 0) - 1; + [a, b].forEach(function (p, pi) { + if ((pi === 0 && k === i0) || (pi === 1 && k === i1 - 1)) return; // the abutments are the cliffs + var g = Math.min(W.terrainH(p[0], p[1]), 0) - 2; + B.box('rubble', p[0], g, p[1], w + 1.2, p[2] - 1.4 - g, 2.6, dir, { col: sc, uvs: 2.2, cls: 'shell', collide: 'stone', kind: 'pier' }); + }); + var rise = Math.min(Ln * 0.45, ym - 1.5 - floor - 1); + B.geo('rubble', B.geos.vault, cx, ym - 1.5 - rise, cz, dir + Math.PI / 2, Ln - 2.4, rise * 2, w + 1.2, Cv(opts.col || '#cfc4b0', 0.8), { uvs: 2.2, cls: 'shell', inside: true }); + // spandrels: the wall between the arch and the deck on each side, as a fan of quads + [-1, 1].forEach(function (sd) { + var h = B.bucket('rubble', cx, cz, 'shell'), N = 10, R = (Ln - 2.4) / 2, ox = sd * (w / 2 + 0.6) * c, oz = -sd * (w / 2 + 0.6) * s; + for (var q = 0; q < N; q++) { + var t0 = q / N, t1 = (q + 1) / N, u0 = -Math.cos(t0 * Math.PI) * R, u1 = -Math.cos(t1 * Math.PI) * R, h0 = Math.sin(t0 * Math.PI) * rise, h1 = Math.sin(t1 * Math.PI) * rise; + var p0 = V3(cx + ox + u0 * s, ym - 1.5 - rise + h0, cz + oz + u0 * c), p1 = V3(cx + ox + u1 * s, ym - 1.5 - rise + h1, cz + oz + u1 * c); + var p2 = V3(p1.x, ym - 1.5, p1.z), p3 = V3(p0.x, ym - 1.5, p0.z); + if (sd > 0) B.quad(h, p1, p0, p3, p2, [u1 / 2.2, p1.y / 2.2, u0 / 2.2, p0.y / 2.2, u0 / 2.2, p3.y / 2.2, u1 / 2.2, p2.y / 2.2], sc); + else B.quad(h, p0, p1, p2, p3, [u0 / 2.2, p0.y / 2.2, u1 / 2.2, p1.y / 2.2, u1 / 2.2, p2.y / 2.2, u0 / 2.2, p3.y / 2.2], sc); + } + }); + } + }; + + // ------------------------------------------------------------------ minimap image (drawn from data) + K.minimap = function (L, opts) { + opts = opts || {}; + var Bd = L.bounds, wm = Bd.x1 - Bd.x0, hm = Bd.z1 - Bd.z0, S = opts.pxPerM || 1, cw = Math.round(wm * S), chh = Math.round(hm * S); + var c = document.createElement('canvas'); c.width = cw; c.height = chh; + var x = c.getContext('2d'), img = x.createImageData(cw, chh), d = img.data, sx = wm / cw, sz = hm / chh; + for (var j = 0; j < chh; j++) for (var i = 0; i < cw; i++) { + var wx = Bd.x0 + i * sx, wz = Bd.z0 + j * sz, h = W.terrainH(wx, wz), o = (j * cw + i) * 4; + if (h < 0) { var dp = M.clamp(-h / 12, 0, 1); d[o] = 30 - dp * 14; d[o + 1] = 74 - dp * 30; d[o + 2] = 102 - dp * 30; } + else { var e = W.terrainH(wx + 2, wz) - h, shade = M.clamp(0.85 - e * 0.25, 0.5, 1.15); d[o] = (92 + h * 0.6) * shade; d[o + 1] = (98 + h * 0.4) * shade; d[o + 2] = (80 + h * 0.2) * shade; } + d[o + 3] = 235; + } + x.putImageData(img, 0, 0); + // roads, then buildings (from the collision boxes) + x.lineCap = 'round'; x.lineJoin = 'round'; + L.roads.forEach(function (r) { + x.strokeStyle = r.mat === 'asphalt' ? 'rgba(210,206,198,0.95)' : 'rgba(236,226,206,0.9)'; x.lineWidth = Math.max(2, r.w / sx); + x.beginPath(); r.pts.forEach(function (p, k) { var px = (p[0] - Bd.x0) / sx, pz = (p[1] - Bd.z0) / sz; if (k) x.lineTo(px, pz); else x.moveTo(px, pz); }); x.stroke(); + }); + (opts.squares || []).forEach(function (q) { x.fillStyle = 'rgba(232,226,214,0.9)'; x.fillRect((q[0] - Bd.x0) / sx, (q[1] - Bd.z0) / sz, (q[2] - q[0]) / sx, (q[3] - q[1]) / sz); }); + W.boxes.forEach(function (b) { + if (b.y1 - b.y0 < 2.5 || b.kind === 'stairs' || b.kind === 'ramp' || b.kind === 'tunnel' || b.kind === 'bridge' || b.see) return; + x.save(); x.translate((b.x - Bd.x0) / sx, (b.z - Bd.z0) / sz); x.rotate(-b.yaw); + x.fillStyle = b.kind === 'church' || b.kind === 'tower' ? 'rgba(196,170,120,0.95)' : 'rgba(176,160,146,0.92)'; + x.fillRect(-b.hx / sx, -b.hz / sz, 2 * b.hx / sx, 2 * b.hz / sz); x.restore(); + }); + return { canvas: c, x0: Bd.x0, z0: Bd.z0, w: wm, h: hm }; + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/maps/amalfi.js b/e63334287a3deaa3/blacktie/js/maps/amalfi.js new file mode 100644 index 00000000..271e91fe --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/maps/amalfi.js @@ -0,0 +1,1047 @@ +/* + * Map: the Amalfi Coast (RP.maps 'amalfi'). Hand-laid from public photos and general knowledge of the real places (no + * map data was downloaded). It is a condensed coast, about 1.9 km of shoreline instead of the real 16 km of road, and + * for the game the drive runs west to east: Amalfi, the cliff road, lemon terraces, a fjord with a fishing hamlet, and + * a second town in the manner of Positano at the far end (the real Positano lies west of Amalfi). + * + * x -256..190 Amalfi: the town fills the mouth of a steep valley that runs north from the sea; Piazza Duomo sits + * just inland, reached from the waterfront through the Porta della Marina arch; the cathedral of + * Sant'Andrea stands at the top of a long flight of steps on the piazza's east side, with a striped + * front, an arcaded porch and a bell tower capped with majolica; the main street climbs north between + * tall houses; a stone mole shelters the harbour. Villa Calcara (invented) is on the western headland. + * x 190..560 the coast road (in the manner of the SS163): cut into the cliff, stone parapet on the sea side, a + * short rock tunnel through a spur, a belvedere lay-by with a kiosk + * x 560..800 lemon terraces: dry-stone steps of land, pergolas, a farmhouse and a roadside stall + * x 850..910 the fjord: the road crosses a narrow inlet on a two-arch bridge; steps go down to a pocket beach + * with fishermen's houses and hauled-out boats (in the manner of the Fiordo di Furore) + * x 910..1250 more cliff road: a bus lay-by on the headland, a second tunnel + * x 1250..1664 the bowl town: pastel houses stacked up a steep amphitheatre, a street that hairpins down from the + * coast road, stair lanes, the church with its majolica dome behind the beach, umbrellas and boats + * + * Coordinates: x east, z south (the sea), y up, metres. Sea level y = 0. + * Everything gameplay-related (walls, cover, stairs, the nav grid) is RP.W data built here; the art follows it. + * The builders themselves live in ../mapkit.js (RP.Kit); this file is the data and the hand-made places. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W, B = RP.B, K = RP.Kit; + var col = RP.col, C = K.C; + var BOUNDS = { x0: -256, z0: -256, x1: 1664, z1: 256 }; + var V3 = function (x, y, z) { return new T.Vector3(x, y, z); }; + + // ------------------------------------------------------------------ the shape of the land + function G(x, c, w) { var t = (x - c) / w; return Math.exp(-t * t); } + // the smooth coastline the road follows, then the real one with the spurs it tunnels through and the fjord + function coast0(x) { return 42 + 46 * G(x, -170, 42) + 22 * G(x, 138, 34) - 6 * G(x, 0, 30) + 4 * Math.sin(x * 0.05) + 12 * G(x, 470, 34) + 8 * G(x, 660, 80) + 30 * G(x, 1010, 40) - 22 * G(x, 1420, 120) + 46 * G(x, 1640, 46); } + function coastZ(x) { return coast0(x) + 26 * G(x, 335, 22) - 78 * G(x, 880, 17) + 20 * G(x, 1160, 22); } + function wild(x) { return M.smooth((x - 190) / 110); } // 0 in Amalfi, 1 on the open coast + function terr(x) { return M.smooth((x - 560) / 60) * (1 - M.smooth((x - 790) / 50)); } // the lemon terraces + var VAL = [ + { ax: function (z) { return -2 + (z < 0 ? 10 * Math.sin(z * 0.018) : 0); }, half: 26, blend: 104, f0: 1.25, f1: 0.0198, f2: 0.000447, beach: 13 }, // Amalfi: the floor climbs with the main street + { ax: function (z) { return 880 + 5 * Math.sin(z * 0.03); }, half: 7, blend: 30, f1: 0.05, f2: 0.003, beach: 12 }, // the fjord's ravine + { ax: function () { return 1420; }, half: 60, blend: 170, f1: 0.1, f2: 0.0016, beach: 18 } // the bowl town + ]; + function valleyX(z) { return VAL[0].ax(z); } + function baseH(x, z) { + var wl = wild(x), n = M.fbm(x * 0.03, z * 0.03, 4); + var d = coastZ(x) - z; + if (wl > 0) d += wl * 9 * (M.noise2(x * 0.023, 3.3) - 0.5) + wl * 5 * (M.noise2(x * 0.07, z * 0.02) - 0.5); // buttresses and gullies + if (d < 0) return Math.max(-30, -0.6 + d * 0.32) + (n - 0.5) * 1.5; + var axA = Math.abs(x - valleyX(z)), te = wl > 0 ? terr(x) : 0; + // the valley's shoulders rise inland; by the sea they stay low so the coast road runs on the cliff face, not in a trench + var ridge = Math.min(Math.max(0, axA - 28) * 0.55, 130) * (1 - wl) * M.smooth((d - 25) / 90); + var side = 0.5 + Math.min(d * 1.5, 26 + 8 * wl - 8 * te + d * (0.32 + 0.2 * wl - 0.13 * te)) + ridge + (n - 0.5) * 9; + if (wl > 0) side += wl * (M.fbm(x * 0.008, z * 0.008, 3) - 0.5) * 18; + var h = side, inVal = 0; + for (var i = 0; i < 3; i++) { + var v = VAL[i], ax = Math.abs(x - v.ax(z)); if (ax >= v.blend) continue; + var vv = M.smooth((v.blend - ax) / (v.blend - v.half)); + h = M.lerp(h, (v.f0 || 0.6) + v.f1 * d + v.f2 * d * d, vv); inVal = Math.max(inVal, vv); + if (d < v.beach && vv > 0.4) h = Math.min(h, 0.25 + d * 0.11); + } + // limestone beds: the open cliffs step up in ledges with near-vertical faces between them; the lemon slopes are + // cut into real terraces + // (always on the sea cliffs, in patches of outcrop higher up) + var crag = Math.max(1 - M.smooth((d - 40) / 30), M.smooth((M.noise2(x * 0.011, z * 0.011 + 5) - 0.42) / 0.2)); + var amt = Math.max(M.smooth((axA - 112) / 20) * (1 - wl), wl) * (1 - inVal) * M.smooth((h - 3) / 5) * crag; + if (te > 0.01 && h > 9) { + var bt = 3.4, ft = h / bt, it = Math.floor(ft), tt = ft - it; + h = M.lerp(h, (it + M.smooth((tt - 0.4) / 0.2)) * bt, te * 0.92); amt *= 1 - te; + } + if (amt > 0.01) { + var band = 5 + 5 * M.noise2(x * 0.004 + 9, z * 0.004), wob = M.noise2(x * 0.013, z * 0.013) * 1.6, f = h / band + wob, fi = Math.floor(f), ft2 = f - fi; + h = M.lerp(h, (fi + M.smooth((ft2 - 0.42) / 0.16) - wob) * band, amt * 0.62); + } + return h; + } + // beyond the map's edge (the far ring): the same coast carried on, rising to the mountains behind + function outerH(x, z) { + var xc = M.clamp(x, BOUNDS.x0, BOUNDS.x1), zc = M.clamp(z, BOUNDS.z0, BOUNDS.z1); + var e = Math.max(BOUNDS.x0 - x, x - BOUNDS.x1, 0), nrt = Math.max(BOUNDS.z0 - z, 0); + var cz = 44 + 60 * G(x, -700, 260) + 90 * G(x, 2300, 320) + 30 * Math.sin(x * 0.006) - (z > BOUNDS.z0 ? 0 : 0); + var d = (e > 0 ? M.lerp(coastZ(xc), cz, M.smooth(e / 300)) : coastZ(xc)) - z; + if (d < 0) return Math.max(-30, d * 0.3); + var edge = W.terrainH(xc, zc), far = Math.max(e, nrt), n = M.fbm(x * 0.004, z * 0.004, 3); + // inland: the ground at the map's edge carried on, climbing gently to ridges a kilometre back + var h = edge * M.smooth(d / 60) + far * (0.16 + 0.1 * M.noise2(x * 0.002, 7)) + (n - 0.5) * 70 * M.smooth(far / 300) + Math.abs(M.noise2(x * 0.0035, z * 0.0035) - 0.5) * 240 * M.smooth(far / 700); + if (e > 0) h = M.lerp(h, Math.min(d * 1.2, 30 + d * 0.42) + far * 0.08 + (n - 0.5) * 60, M.smooth(e / 200) * (nrt > 0 ? 0.5 : 1)); + return Math.max(h, d < 40 ? -30 : 2); + } + // Li Galli-like islets off the bowl town (far ring only) + function isletH(x, z) { return 46 * G(Math.hypot(x - 1250, z - 900), 0, 70) + 30 * G(Math.hypot(x - 1420, z - 980), 0, 50) + 22 * G(Math.hypot(x - 1090, z - 1010), 0, 40) - 6; } + + // ---- the coast road east of Amalfi, laid along the cliff top + var ROADY = [[188, 22], [260, 26], [335, 29], [420, 32], [470, 34], [560, 35], [700, 36], [820, 34], [852, 32], [908, 32], [950, 34], [1010, 38], [1090, 42], [1160, 45], [1252, 49.5]]; + function roadY(x) { for (var i = 0; i < ROADY.length - 1; i++) if (x <= ROADY[i + 1][0]) { var a = ROADY[i], b = ROADY[i + 1]; return a[1] + (b[1] - a[1]) * M.clamp((x - a[0]) / (b[0] - a[0]), 0, 1); } return ROADY[ROADY.length - 1][1]; } + var OFF = 21; // metres inland of the smooth coastline: on the cliff face + var COAST_X = [212, 236, 262, 288, 312, 335, 358, 384, 410, 436, 458, 482, 506, 532, 560, 590, 620, 650, 680, 710, 740, 770, 800, 828, 852, 880, 908, 934, 960, 986, 1010, 1034, 1060, 1086, 1112, 1138, 1160, 1182, 1206, 1230, 1252]; + var coastPts = [[22, 16, 2.6], [44, 18, 3.4], [66, 22, 6.2], [92, 28, 10.5], [116, 35, 14.6], [138, 41, 18.2], [162, 38, 20.6], [188, 26, 22]]; + COAST_X.forEach(function (x) { coastPts.push([x, Math.round((coast0(x) - OFF) * 10) / 10, roadY(x)]); }); + [[1278, -2, 51], [1300, -40, 53], [1316, -80, 55], [1340, -118, 57], [1375, -142, 58], [1420, -152, 58], [1465, -146, 58], [1505, -126, 57], [1540, -96, 56], [1570, -60, 55], [1596, -26, 54], [1626, -6, 53], [1652, 2, 52.5]].forEach(function (p) { coastPts.push(p); }); + // Catmull-Rom through a road's points, n steps per span (hairpins and bends come out round) + function smoothPts(pts, n) { + var out = []; + for (var i = 0; i < pts.length - 1; i++) { + var p0 = pts[Math.max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[Math.min(pts.length - 1, i + 2)]; + for (var k = 0; k < n; k++) { + var t = k / n, t2 = t * t, t3 = t2 * t; + var f = function (a, b, c, d) { return 0.5 * (2 * b + (c - a) * t + (2 * a - 5 * b + 4 * c - d) * t2 + (3 * b - a - 3 * c + d) * t3); }; + out.push(k ? [Math.round(f(p0[0], p1[0], p2[0], p3[0]) * 10) / 10, Math.round(f(p0[1], p1[1], p2[1], p3[1]) * 10) / 10, p1[2] + (p2[2] - p1[2]) * t] : p1); + } + } + out.push(pts[pts.length - 1]); + return out; + } + coastPts = coastPts.slice(0, 7).concat(smoothPts(coastPts.slice(7), 2)); + function ptIndex(x) { for (var i = 0; i < coastPts.length; i++) if (coastPts[i][0] === x) return i; return -1; } + + // flattened pads (piazzas, terraces) + var PADS = [ + { x0: -30, z0: 6, x1: 24, z1: 22, y: 2.4, blend: 6 }, // 0 Amalfi waterfront square + road + { x0: -19, z0: -38, x1: 12, z1: -2, y: 4.75, blend: 5 }, // 1 Piazza Duomo + { x0: 26, z0: -46, x1: 66, z1: -6, y: 12.75, blend: 6 }, // 2 the cathedral's terrace + { x0: 11, z0: -30, x1: 26.5, z1: -10, y: 4.6, cut: true }, // 3 under the cathedral steps (the steps are boxes) + { x0: 8, z0: 22, x1: 44, z1: 34, y: 1.4, blend: 3 }, // 4 harbour quay + { cx: -168, cz: 40, r: 32, y: 23.85, blend: 14 }, // 5 villa plateau + { x0: -154, z0: 17.3, x1: -139.2, z1: 35, y: 23.2, cut: true }, // 5b under the villa's pool and its deck (the deck hides the edge) + { cx: -133.5, cz: 12.5, r: 5.5, y: 23.7, blend: 5 }, // the forecourt outside the villa gate + { cx: -176, cz: 2, r: 13, y: 20, blend: 8 }, // lemon terrace 1 (below the villa, north) + { cx: -150, cz: -10, r: 12, y: 16.5, blend: 8 }, // lemon terrace 2 + { cx: 140, cz: 54, r: 9, y: 22, blend: 8 }, // the watchtower's rock + { x0: -4.6, z0: -3.4, x1: 5.6, z1: 9.6, y: 2.25, cut: true }, // under the ramp through the Porta della Marina + { x0: -180.2, z0: 65, x1: -175.8, z1: 89, y: 2.4, cut: true }, // the slot the villa's cliff steps go down + { cx: 466, cz: 36, r: 13, y: 33.8, blend: 6 }, // the belvedere lay-by + { cx: 848.5, cz: 13.5, r: 3.6, y: 32, blend: 3 }, // the landing at the top of the fjord steps + { x0: 868, z0: -64, x1: 893, z1: -42, y: 2.3, blend: 4 }, // the fishing hamlet's yard behind its beach + { cx: 1012, cz: 62, r: 11, y: 38, blend: 6 }, // bus lay-by on the headland + { x0: 1376, z0: -44, x1: 1432, z1: -16, y: 7.6, blend: 5, n: 'church' }, // the bowl town: church square + { x0: 1362, z0: -9, x1: 1480, z1: 3, y: 3.4, blend: 3, n: 'prom' }, // beach promenade + { cx: 1458, cz: -56, r: 9, y: 20, blend: 6 }, // the piazzetta where the street ends + { x0: -1.2, z0: -58.5, x1: 8.6, z1: -49.6, y: 6.5, blend: 2.5 }, // three small corners off Amalfi's main street + { x0: -13.4, z0: -61.6, x1: -8.0, z1: -55.4, y: 6.9, blend: 2.5 }, + { x0: -10.4, z0: -102.2, x1: -5.8, z1: -97.8, y: 12.2, blend: 2 }, + { cx: 640, cz: -16, r: 10, y: 0, blend: 7, auto: true } // the lemon farm's yard (height set from the ground) + ]; + var ROADS = [ + // 0 coast road west, up to the villa gate + { w: 7, mat: 'asphalt', pts: [[-28, 16, 2.6], [-48, 22, 3.2], [-72, 30, 6], [-98, 37, 11.5], [-118, 35, 16.5], [-129, 27, 20.5], [-134.5, 18, 23], [-140, 13.2, 23.9], [-150, 12.6, 23.9]] }, + // 1 waterfront road east and the long coast road (two tunnels, the fjord bridge), round the back of the bowl town + { w: 7, mat: 'asphalt', name: 'coast', pts: coastPts }, + // 2 main street north up the valley + { w: 5, mat: 'basalt', name: 'main', pave: 1.7, pts: [[-4, -36, 5], [-5, -58, 6.8], [-9, -80, 9.3], [-13, -102, 12.4], [-12, -126, 16.2], [-6, -150, 20.6], [-1, -176, 25.6], [0, -205, 32], [2, -238, 39.5]] }, + // 3 the stair path (scalinata) west from the piazza to the villa's lemon terraces + { w: 3.2, mat: 'paving', steps: true, pts: [[-18, -22, 5], [-34, -28, 7.2], [-56, -26, 9.6], [-80, -20, 12], [-104, -14, 14.4], [-128, -12, 16], [-150, -10, 16.5], [-168, -2, 19.2], [-176, 2, 20]] }, + // 4-6 side lanes (stepped) up the east and west slopes + { w: 3, mat: 'paving', steps: true, pts: [[-10, -86, 10], [12, -92, 14.5], [30, -88, 19]] }, + { w: 3, mat: 'paving', steps: true, pts: [[-12, -118, 15], [-34, -124, 21], [-50, -118, 26]] }, + { w: 3, mat: 'paving', steps: true, pts: [[-3, -60, 7], [18, -64, 11.5], [26, -52, 13]] }, + // 7 steps from the coast road down the fjord's west wall to the hamlet + { w: 3.6, mat: 'paving', steps: true, blend: 2.2, name: 'coveSteps', pts: [[849, 13, 32], [849.4, 9.5, 31.2], [851, 2, 27], [856, -10, 20.5], [860, -22, 14], [864, -34, 8], [869, -44, 3.2], [872, -50, 2.4]] }, + // 8 the bowl town's street: down from the coast road in three legs and two hairpins to the piazzetta + { w: 5.5, mat: 'basalt', name: 'descent', pave: 1.7, pts: smoothPts([[1385, -146, 57.6], [1420, -138, 53.5], [1455, -128, 48.6], [1467, -120, 46.2], [1458, -113, 43.6], [1420, -107, 39.5], [1382, -100, 36], [1369, -93, 33.8], [1380, -86, 31.3], [1415, -76, 27], [1450, -66, 22.8], [1458, -58, 20]], 3) }, + // 9-14 its stair lanes + { w: 3.4, mat: 'paving', steps: true, blend: 3, name: 'mulini', pts: [[1456, -54, 20], [1447, -44, 15.6], [1438, -35, 11.6], [1431, -29, 8.4], [1428, -27, 7.6]] }, + { w: 3.4, mat: 'paving', steps: true, blend: 3, pts: [[1378, -30, 7.6], [1364, -36, 12], [1348, -48, 20], [1334, -60, 29], [1326, -68, 35]] }, + { w: 3.4, mat: 'paving', steps: true, blend: 3, pts: [[1476, -3, 3.4], [1490, -14, 9], [1506, -30, 17], [1520, -50, 27], [1532, -72, 39], [1539, -90, 51], [1540, -95, 55.6]] }, + { w: 3.4, mat: 'paving', steps: true, blend: 3, pts: [[1404, -44, 7.6], [1403, -56, 14], [1402, -68, 21.5], [1401, -78, 28.2]] }, + { w: 3.4, mat: 'paving', steps: true, blend: 3, pts: [[1430, -73, 25.4], [1432, -88, 31.5], [1434, -100, 37], [1434, -108, 40.8]] }, + { w: 3.4, mat: 'paving', steps: true, blend: 3, pts: [[1400, -104, 37.8], [1402, -118, 44.5], [1404, -132, 51.5], [1404, -140, 55.2]] }, + // 15 a farm track up through the lemon terraces + { w: 2.6, mat: 'paving', steps: true, blend: 2.5, pts: [[628, 23.6, 35.6], [629, 8, 0], [633, -3, 0], [637, -9, 0]], auto: true } + ]; + var COAST = ROADS[1], MAIN = ROADS[2]; + COAST.tunnels = [[ptIndex(312), ptIndex(358)], [ptIndex(1138), ptIndex(1182)]]; + COAST.bridge = [ptIndex(852), ptIndex(908)]; + + // ------------------------------------------------------------------ palettes (sRGB, from photos of the coast) + var WALLS = K.WALLS, SHUTTERS = K.SHUTTERS; + var LAND = null, rnd = null; + + // ------------------------------------------------------------------ the build + function build() { + var R = RP.R; + rnd = M.rng(1977); + Math.random = rnd; // the map is the same on every visit (restored at the end) + RP.MapTex.build(); + W.reset(BOUNDS); + W.water = 0; + B.reset(); K.reset(BOUNDS); + // pads and tracks whose height follows the natural ground + PADS.forEach(function (p) { if (p.auto) p.y = Math.round(baseH(p.cx, p.cz) * 10) / 10; }); + ROADS.forEach(function (r) { if (r.auto) { var fy = PADS[PADS.length - 1].y, y0 = r.pts[0][2]; r.pts[1][2] = y0 + (fy - y0) * 0.36; r.pts[2][2] = y0 + (fy - y0) * 0.76; r.pts[3][2] = fy; } }); + LAND = K.makeLand({ bounds: BOUNDS, cell: 2, base: baseH, pads: PADS, roads: ROADS }); + var hf = LAND.hf; + W.setTerrain(hf); + W.surfaceMat = function (x, z) { + var y = W.terrainH(x, z); + if (y < 1.5 && y > -0.3) return 'sand'; + if (LAND.onRoad(x, z, 0.5)) return 'stone'; + if (x > -20 && x < 13 && z > -39 && z < 23) return 'stone'; + return 'dirt'; + }; + B.land = { hf: hf }; // so terrain queries work while building; the meshes and textures are made at the end + + // paved squares + [0, 1, 2, 4].forEach(function (k) { var p = PADS[k]; K.occMark((p.x0 + p.x1) / 2, (p.z0 + p.z1) / 2, p.x1 - p.x0, p.z1 - p.z0, 0, 0); }); + K.roads(LAND, { parapet: function (r, k, a, b) { + if (Math.abs(a[0]) < 30 && Math.abs(b[0]) < 30) return false; // the waterfront square is open to the beach + if (r === COAST && a[0] > 455 && b[0] < 484) return false; // the belvedere has its own + if (r === COAST && a[0] > 985 && b[0] < 1036) return false; // so has the bus lay-by + if (r === COAST && a[0] >= 1252 && a[0] < 1630) return a[0] < 1340 || a[0] > 1545; // houses line the road round the bowl + } }); + + buildPiazza(); + buildCathedral(); + buildWaterfront(); + buildVilla(); + buildTower(); + buildTown(); + buildCoastRoad(); + buildTerraces(); + buildCove(); + buildBowlTown(); + buildNature(); + + // terrain meshes and textures (after everything has marked the ground it stands on), then the merged scenery + B.setLand({ hf: hf, cap: LAND.cap, outer: function (x, z) { return Math.max(outerH(x, z), isletH(x, z)); }, colour: landColour, ringX: 1792, ringN: 1408, ringCell: 64 }); + B.finish(); + RP.map.lamps = K.LAMPS.slice(); + W.buildNav(1); + W.buildCover(); + RP.map.hf = hf; + RP.map.houses = K.houses; + Math.random = RP._random; + } + + // tint (1 = plain rock/scrub) and vegetation amount for the terrain textures and the far ring + var _ln = new T.Vector3(); + function landColour(x, z, h, slope, out, outer) { + var r = 1, g = 1, b = 1, veg = 0.85; + if (outer) { out[0] = 0.98; out[1] = 1; out[2] = 1.02; out[3] = h < 1 ? 0 : 0.9; return; } + var occ = K.occAt(x, z), te = x > 540 && x < 850 ? terr(x) : 0; + if (occ) { r = 0.98; g = 0.94; b = 0.88; veg = 0.12; } + else if (te > 0.3 && h > 9) { r = 0.9; g = 0.98; b = 0.8; veg = 0.95; } + else { + // inside the towns the ground between houses is trodden earth and garden, not macchia + var axA = Math.abs(x - valleyX(z)), axP = Math.abs(x - 1420); + if ((x < 200 && axA < 105) || (axP < 150 && z < 0)) { veg = axA < 60 || axP < 110 ? 0.36 : 0.55; r = 1.02; g = 0.98; b = 0.9; } + } + // beaches: grey-gold sand, darker where the sea wets it (the three town beaches are sand right up to their walls) + var beach = (Math.abs(x) < 62 && z > 21) || (Math.abs(x - 880) < 17 && z > -45) || (Math.abs(x - 1420) < 78 && z > 3.2), top = beach ? 3.4 : 2.2; + if (h < top && slope < 0.3) { + var s = M.smooth((top - h) / (beach ? 0.5 : 1.0)) * (1 - M.smooth((slope - 0.12) / 0.18)); + r = M.lerp(r, 1.36, s); g = M.lerp(g, 1.27, s); b = M.lerp(b, 1.1, s); veg *= 1 - s; + } + if (h < 0.3) { var wet = M.smooth((0.3 - h) / 0.5); r *= 1 - 0.3 * wet; g *= 1 - 0.27 * wet; b *= 1 - 0.22 * wet; veg = 0; } + if (h < -1) { var dp = M.smooth((-1 - h) / 6); r *= 1 - 0.45 * dp; g *= 1 - 0.3 * dp; b *= 1 - 0.2 * dp; } + out[0] = r; out[1] = g; out[2] = b; out[3] = veg; + } + + // ---- Piazza Duomo: the fountain, cafés, shops round the square, the Porta della Marina + function buildPiazza() { + var y = 5, i; + B.box('paving', -3.5, 4.85, -20, 31, 0.15, 36, 0, { col: C('#e6dfd2'), ao: 0, uvs: 3, collide: 'stone', kind: 'floor', cls: 'shell' }); // Piazza Duomo + // bands of dark basalt divide the pale slabs into panels + for (i = 0; i < 4; i++) B.box('basalt', -3.5, 4.86, -34 + i * 9.4, 31, 0.15, 0.4, 0, { col: C('#f2eee6'), ao: 0, uvs: 2.4, cls: 'shell', noSides: true }); + for (i = 0; i < 3; i++) B.box('basalt', -14 + i * 10.5, 4.862, -20, 0.4, 0.15, 36, 0, { col: C('#f2eee6'), ao: 0, uvs: 2.4, cls: 'shell', noSides: true }); + // Fountain of Sant'Andrea: an octagonal basin on a step, a tiered stem, a figure on top (low cover) + var fx = -3, fz = -22, st = C('#e8e2d6'); + B.geo('stone', new T.CylinderGeometry(3.0, 3.1, 0.16, 8), fx, y + 0.08, fz, 0.39, 1, 1, 1, C('#d9d2c4'), { uvs: 1.5, cls: 'shell' }); + B.geo('stone', new T.CylinderGeometry(2.3, 2.4, 0.9, 8), fx, y + 0.45, fz, 0.39, 1, 1, 1, st, { uvs: 1.5, cls: 'shell' }); + B.geo('stone', new T.CylinderGeometry(2.42, 2.42, 0.1, 8), fx, y + 0.9, fz, 0.39, 1, 1, 1, C('#f1ece2'), { uvs: 1.5, cls: 'detail' }); + B.geo('water', new T.CylinderGeometry(2.08, 2.08, 0.04, 16), fx, y + 0.8, fz, 0, 1, 1, 1, C('#ffffff'), { cls: 'flat' }); + B.geo('stone', new T.CylinderGeometry(0.55, 0.75, 1.5, 8), fx, y + 1.5, fz, 0, 1, 1, 1, C('#ddd6c8'), { cls: 'shell' }); + B.geo('stone', new T.CylinderGeometry(1.15, 0.5, 0.3, 10), fx, y + 2.4, fz, 0, 1, 1, 1, st, { cls: 'detail' }); + B.geo('water', new T.CylinderGeometry(1.02, 1.02, 0.03, 10), fx, y + 2.545, fz, 0, 1, 1, 1, C('#ffffff'), { cls: 'flat' }); + B.geo('stone', new T.CylinderGeometry(0.28, 0.42, 1.0, 8), fx, y + 3.05, fz, 0, 1, 1, 1, C('#ddd6c8'), { cls: 'detail' }); + B.geo('stone', B.geos.sphere, fx, y + 3.95, fz, 0, 0.6, 0.95, 0.5, C('#e7e1d4'), { cls: 'detail' }); + B.geo('stone', B.geos.sphere, fx, y + 4.55, fz, 0, 0.34, 0.38, 0.34, C('#e7e1d4'), { cls: 'detail' }); + for (i = 0; i < 4; i++) { var fa = i * Math.PI / 2 + 0.39; B.geo('stone', B.geos.sphere, fx + Math.cos(fa) * 1.5, y + 1.05, fz + Math.sin(fa) * 1.5, 0, 0.4, 0.4, 0.4, st, { cls: 'detail' }); } + W.addBox({ x: fx, z: fz, y0: y, y1: y + 0.9, hx: 2.2, hz: 2.2, yaw: 0.39, mat: 'stone', cover: true, kind: 'fountain' }); + W.addBox({ x: fx, z: fz, y0: y, y1: y + 3.4, hx: 0.6, hz: 0.6, mat: 'stone', cover: true, kind: 'pillar' }); + // café tables and umbrellas along the west side, planters, lamps + for (i = 0; i < 5; i++) { + var tz = -33 + i * 6; + K.cafeTable(-14, tz, y, { chairs: 3 }); K.cafeTable(-11.5, tz + 2.5, y, { chairs: 2 }); + K.umbrella(-12.8, tz + 1.2, y, i % 2 ? 1 : 3, { r: 2.6 }); + } + // a second café under the cathedral steps + for (i = 0; i < 3; i++) { K.cafeTable(8.2, -4.5 - i * 2.4, y, { chairs: 2, cloth: '#e9dfc6', chair: '#5a4a3a' }); } + [[-16, -6], [9, -36], [9, -6], [-16, -36], [4, -14]].forEach(function (p) { + B.box('stone', p[0], y, p[1], 1.4, 0.75, 1.4, 0, { col: C('#cfc5b4'), collide: 'stone', cover: true, kind: 'planter', cls: 'shell', uvs: 1.5 }); + B.box('stone', p[0], y + 0.75, p[1], 1.5, 0.08, 1.5, 0, { col: C('#e4dccb'), cls: 'detail', ao: 0, uvs: 1.5 }); + K.tree('lemon', p[0], p[1], y + 0.4); + }); + [[-17, -18], [10, -28], [10, -12], [-17, -30]].forEach(function (p) { K.lamp(p[0], p[1], y); }); + K.car(6, -32, 0.2, '#e8e2cf', 'van', y); + K.crate(-8, -36.5, 0.1, 1.05, null, y); K.crate(-6.8, -36.6, 0.5, 1.05, null, y); K.crate(-7.5, -35.4, 0.3, 0.9, '#8f7253', y); + // the market stall (boxes of lemons and tomatoes under an awning) on the north side + B.box('wood', 2, y, -36.5, 4, 0.95, 1.2, 0, { col: C('#9a7a55'), collide: 'wood', cover: true, kind: 'stall', cls: 'detail' }); + for (i = 0; i < 5; i++) { B.box('wood', 0.4 + i * 0.8, y + 0.95, -36.5, 0.7, 0.16, 1.0, 0, { col: C('#b99a6e'), cls: 'detail', ao: 0, topCol: C(['#e9c93a', '#c9402e', '#e9c93a', '#6f9a3e', '#d98a2e'][i]) }); } + [0.1, 3.9].forEach(function (px) { B.box('wood', px, y, -35.9, 0.07, 2.35, 0.07, 0, { col: C('#6d5a45'), cls: 'detail', ao: 0 }); B.box('wood', px, y, -37.1, 0.07, 2.6, 0.07, 0, { col: C('#6d5a45'), cls: 'detail', ao: 0 }); }); + B.quad(B.bucket('awning', 2, -36.5, 'detail'), V3(-0.2, y + 2.3, -35.5), V3(4.2, y + 2.3, -35.5), V3(4.2, y + 2.65, -37.2), V3(-0.2, y + 2.65, -37.2), [0.001, 0, 0.249, 0, 0.249, 1, 0.001, 1], C('#ffffff')); + // clutter: scooters by the north houses, bins, benches facing the fountain, pots + K.scooter(-2.5, -37.2, 1.7, '#c7d9d2', y); K.scooter(-4.2, -37.3, 1.5, '#b8433a', y); K.scooter(10.6, -20, 0.1, '#e8d9a8', y); + K.bin(-18, -24, y); K.bin(11, -34.5, y); + K.bench(-8.5, -22, y, Math.PI / 2); K.bench(2.5, -22, y, -Math.PI / 2); + [[-18.2, -3.4], [-18.2, -37], [-9, -3.2], [9.5, -3.2]].forEach(function (p) { K.planter(p[0], y, p[1], 0, { pot: true }); }); + // bollards across the mouth of the main street and by the gate + [-7.5, -5.2, -2.9, -0.6].forEach(function (bx) { K.bollard(bx, -37.6, y); }); + [-3.4, 4.4].forEach(function (bx) { K.bollard(bx, -2.6, y, 'iron'); }); + // houses framing the piazza (west and north sides), shops on the ground floor + var west = ['#ecd7a2', '#f0e7d6', '#e9b899', '#efe1c0', '#e4a998']; + for (i = 0; i < 5; i++) { + var hz = -34 + i * 7.6; + K.house(-24, hz, 7.4, 10, Math.PI / 2, { floors: 4 + (i % 2), wall: west[i], shutter: SHUTTERS[i % 3], roof: i % 2 ? 'vault' : 'flat', shop: i * 2, base: y, sides: 'party', noBack: true, balc: 0, frames: true, awning: false, lamp: false }); + K.occMark(-24, hz, 10, 7.4, 0, 0.5); + } + // an arcade runs along the west row: cafés and shops in its shade, a terrace with a rail on top + K.arcade(-20.25, -37.6, -20.25, -0.4, y, 3.1, { h: 3.4, col: '#f0e7d6', bay: 3.72 }); + var north = ['#f2e9d5', '#e8c597', '#efd9a0']; + for (i = 0; i < 2; i++) { + var hx = i ? 10 : -14; + K.house(hx, -45, 9, 9, 0, { floors: 4, wall: north[i], shutter: SHUTTERS[i], roof: 'flat', shop: 10 + i * 3, base: y, noBack: true, frames: true }); + K.occMark(hx, -45, 9, 9, 0, 0.5); + } + // the south row with the Porta della Marina: an arch through the houses to the waterfront + K.house(-15, 2.6, 22, 8, Math.PI, { floors: 4, wall: '#efe4cc', shutter: '#3e6b52', roof: 'flat', base: y, shop: 5, noBack: false, frames: true }); + K.house(14, 2.6, 18, 8, Math.PI, { floors: 3, wall: '#ecc9a0', shutter: '#3a6a72', roof: 'vault', base: y, shop: 8, noBack: false }); + K.occMark(-15, 2.6, 22, 8, 0, 0.4); K.occMark(14, 2.6, 18, 8, 0, 0.4); + // the gate: rooms over the passage, a vault under them, a shallow arch on each face; open passage at x -4..5 + var gw = C('#efe4cc'); + B.box('aged', 0.5, y + 4.2, 2.6, 9, 9, 8, 0, { col: gw, collide: 'plaster', kind: 'gate', uvs: 3, cls: 'shell', topMat: 'paving' }); + B.box('aged', 0.5, y + 4.2, 2.6, 9, 9, 8, 0, { col: gw, uvs: 3, cls: 'far' }); + B.geo('aged', B.geos.vault, 0.5, y + 2.6, 2.6, 0, 9, 3.2, 8, Cv('#e6dac0', 0.88), { uvs: 3, cls: 'shell', inside: true }); + [[-1.42, Math.PI], [6.62, 0]].forEach(function (f) { + B.geo('aged', K.archGeo(9, 2.2, 1.6), 0.5, y + 2.6, f[0], f[1], 1, 1, 1, gw, { cls: 'shell', uvs: 3 }); + B.geo('stone', K.archRing(9, 1.6, 0.42), 0.5, y + 2.6, f[0] + (f[1] ? -0.04 : 0.04), f[1], 1, 1, 1, C('#d8cfbf'), { cls: 'detail', uvs: 1.5 }); + B.box('stone', 0.5, y + 4.75, f[0] + (f[1] ? -0.06 : 0.06), 9.4, 0.3, 0.14, 0, { col: C('#d8cfbf'), cls: 'detail', ao: 0, uvs: 1.5 }); + }); + var gf = K.faceFrame(0.5, 2.6, -1, 0, 0, 4, 0, 1); gf.fyaw = Math.PI; // the piazza face (north) + [-2.6, 0, 2.6].forEach(function (u) { K.fq('window', gf, u - 0.5, u + 0.5, y + 6.1, y + 7.7, C('#ffffff'), 0.035, [0, 0, 1, 0, 1, 1, 0, 1]); K.fq('louvre', gf, u - 1.05, u - 0.52, y + 6.1, y + 7.7, C('#3e6b52'), 0.05, [0, 0, 1, 0, 1, 1, 0, 1]); K.fq('louvre', gf, u + 0.52, u + 1.05, y + 6.1, y + 7.7, C('#3e6b52'), 0.05, [0, 0, 1, 0, 1, 1, 0, 1]); }); + W.addZone({ x0: -4, z0: -1.4, x1: 5, z1: 6.6, y0: 0, y1: 9, indoor: true, name: 'Porta della Marina' }); + // the way down through the gate: a paved ramp of long shallow steps (the walking surface is one smooth ramp box) + W.addBox({ x: 0.5, z: 3, y0: -1, y1: 5, hx: 4.5, hz: 6, mat: 'stone', ramp: [5, 2.6], kind: 'ramp', deck: true }); + var nS = 16; + for (i = 0; i < nS; i++) { + var zs = -3 + 12 * (i + 0.5) / nS, ys = 5 - 2.4 * (i + 1) / nS; + B.box(i % 4 === 0 ? 'basalt' : 'paving', 0.5, 1.9, zs, 9, ys - 1.9 + 0.075, 12 / nS + 0.01, 0, { col: C(i % 4 === 0 ? '#f2eee6' : '#d9d2c5'), ao: 0.1, uvs: i % 4 === 0 ? 2.4 : 3, cls: 'shell' }); + } + K.wallLamp(K.faceFrame(-4.0, 2.6, 1, 0, 0, 0, 1, 0), 0, y + 2.2); K.LAMPS.push(V3(0.5, y + 3.6, 2.6)); + B.box('lamp', 0.5, y + 3.75, 2.6, 0.26, 0.4, 0.26, 0, { cls: 'flat', ao: 0 }); B.box('metal', 0.5, y + 4.15, 2.6, 0.03, 0.3, 0.03, 0, { col: C('#1f1c1a'), cls: 'detail', ao: 0 }); + } + function Cv(hex, k) { return col(hex).multiplyScalar(k); } + + // ---- the Cathedral of Sant'Andrea: steps, striped arcaded front, mosaic gable, bell tower with majolica top + function buildCathedral() { + var yP = 5, yT = 13, sx0 = 12, sx1 = 26.5, z0 = -29, z1 = -11, i, b; + // the great stair: collision is a ramp; the art is 46 steps with side walls + W.addBox({ x: (sx0 + sx1) / 2, z: (z0 + z1) / 2, y0: 0, y1: yT, hx: (z1 - z0) / 2, hz: (sx1 - sx0) / 2, yaw: Math.PI / 2, mat: 'stone', ramp: [yP, yT], kind: 'stairs', deck: true }); + var n = 46, run = (sx1 - sx0) / n; + for (i = 0; i < n; i++) { + var yy = yP + (yT - yP) * (i + 1) / n, xx = sx0 + run * (i + 0.5); + B.box('stone', xx, yP - 0.5, (z0 + z1) / 2, run + 0.01, yy - yP + 0.5, z1 - z0, 0, { col: C(i % 2 ? '#e2dbcd' : '#d8d0c1'), ao: 0.05, uvs: 1.5, cls: 'shell' }); + } + // side walls of the stair (cover going up), capped + [z0 - 0.4, z1 + 0.4].forEach(function (z) { + for (var k = 0; k < 6; k++) { + var xa = sx0 + (sx1 - sx0) * k / 6, xb = sx0 + (sx1 - sx0) * (k + 1) / 6, ya = yP + (yT - yP) * k / 6; + B.box('stone', (xa + xb) / 2, ya - 0.5, z, xb - xa, 1.6 + (yT - yP) / 6, 0.8, 0, { col: C('#cdc3b1'), collide: 'stone', cover: true, kind: 'wall', uvs: 1.5, cls: 'shell' }); + B.box('stone', (xa + xb) / 2, ya + 1.1 + (yT - yP) / 6, z, xb - xa + 0.1, 0.1, 0.95, 0, { col: C('#ebe5d8'), cls: 'detail', ao: 0, uvs: 1.5 }); + } + }); + // terrace in front of the church + B.box('paving', 46, yT - 0.15, -26, 40, 0.15, 40, 0, { col: C('#ddd6c9'), uvs: 3, collide: 'stone', kind: 'floor', cls: 'shell' }); + K.occMark(40, -26, 54, 44, 0, 0); + // porch: five arches on striped piers + var fx = 29, fz0 = -31, fz1 = -9, bay = (fz1 - fz0) / 5; + for (i = 0; i <= 5; i++) { + var pz = fz0 + bay * i; + B.box('stone', fx, yT, pz, 0.9, 4.4, 0.9, 0, { col: C('#efebe3'), collide: 'stone', cover: true, kind: 'pillar', cls: 'shell', uvs: 1.5 }); + W.boxes[W.boxes.length - 1].y1 = yT + 6.2; + for (b = 0; b < 4; b++) B.box('stone', fx, yT + 0.35 + b * 1.05, pz, 0.95, 0.5, 0.95, 0, { col: C('#3a3836'), ao: 0, noTop: true, cls: 'detail', uvs: 1.5 }); + B.box('stone', fx, yT + 4.4, pz, 1.15, 0.25, 1.15, 0, { col: C('#f3efe6'), ao: 0, cls: 'detail', uvs: 1.5 }); + if (i < 5) { + B.geo('stone', K.archGeo(bay, 1.75, 1.6, true), fx - 0.44, yT + 4.65, pz + bay / 2, -Math.PI / 2, 1, 1, 1, C('#efebe3'), { cls: 'shell', uvs: 1.5 }); + B.geo('stone', K.archRing(bay - 0.5, 1.5, 0.3, true), fx - 0.47, yT + 4.65, pz + bay / 2, -Math.PI / 2, 1, 1, 1, C('#56524c'), { cls: 'detail', uvs: 1.5 }); + } + } + // porch roof, its back wall with the bronze doors, and the striped front above it + B.box('stone', fx + 2, yT + 6.4, (fz0 + fz1) / 2, 5, 0.8, fz1 - fz0 + 1, 0, { col: C('#efebe3'), cls: 'shell', uvs: 1.5, bottom: true }); + var wf = K.faceFrame(fx + 4.4, (fz0 + fz1) / 2, 1, 0, 0, 0, -1, 0); wf.fyaw = -Math.PI / 2; + [-6.6, 0, 6.6].forEach(function (u, k) { K.fq('dark', wf, u - 1.3, u + 1.3, yT, yT + 4.0, C('#ffffff'), 0.03); K.fq('door', wf, u - 1.2, u + 1.2, yT, yT + 3.9, C(k === 1 ? '#6a7a58' : '#5b3b26'), 0.05, [0, 0, 1, 0, 1, 1, 0, 1]); }); + W.addZone({ x0: fx - 0.5, z0: fz0, x1: fx + 4.5, z1: fz1, y0: yT - 1, y1: yT + 6, indoor: true, name: 'cathedral porch' }); + var frontY = yT + 7.2, frontH = 13, fw = fz1 - fz0 + 1, zc = (fz0 + fz1) / 2; + var ff = K.faceFrame(fx + 1.6, zc, 1, 0, -0.3, 0, -1, 0); + K.fq('duomo', ff, -fw / 2, fw / 2, frontY, frontY + frontH, C('#ffffff'), 0, [0, 0, 1, 0, 1, 0.64, 0, 0.64], 'shell'); + K.fq('duomo', ff, -fw / 2, fw / 2, frontY, frontY + frontH, C('#ffffff'), 0, [0, 0, 1, 0, 1, 0.64, 0, 0.64], 'far'); + B.tri(B.bucket('duomo', fx, zc, 'shell'), V3(fx + 1.3, frontY + frontH, zc - fw / 2), V3(fx + 1.3, frontY + frontH, zc + fw / 2), V3(fx + 1.3, frontY + frontH + 6, zc), [0, 0.64, 1, 0.64, 0.5, 0.985], C('#ffffff')); + B.box('stone', fx + 1.9, frontY, zc, 0.6, frontH, fw, 0, { col: C('#e9e3d6'), ao: 0, cls: 'shell', uvs: 1.5, noTop: true }); + // the nave (solid, collision), its roof, the apse dome + B.box('aged', fx + 18, yT, zc, 30, 18, 22, 0, { col: C('#efe6d3'), collide: 'plaster', kind: 'church', uvs: 3, cls: 'shell' }); + B.box('aged', fx + 18, yT, zc, 30, 18, 22, 0, { col: C('#efe6d3'), uvs: 3, cls: 'far', topCol: C('#c98a66') }); + B.box('stucco', fx + 18, yT + 18, zc, 30, 0.6, 23, 0, { col: C('#f4efe4'), ao: 0, cls: 'shell', uvs: 3 }); + B.geo('roof', K.hipGeo(31, 23, 5), fx + 18, yT + 18.6, zc, 0, 1, 1, 1, C('#f1e2d6'), { cls: 'shell' }); + for (i = 0; i < 5; i++) { var nf = K.faceFrame(fx + 18, zc, 1, 0, 0, i < 0 ? 0 : 11, 0, 1); K.fq('window', nf, -11 + i * 5.5 - 0.6, -11 + i * 5.5 + 0.6, yT + 10, yT + 13.2, C('#ffffff'), 0.04, [0, 0, 1, 0, 1, 1, 0, 1]); var nb = K.faceFrame(fx + 18, zc, 1, 0, 0, -11, 0, -1); K.fq('window', nb, -11 + i * 5.5 - 0.6, -11 + i * 5.5 + 0.6, yT + 10, yT + 13.2, C('#ffffff'), 0.04, [0, 0, 1, 0, 1, 1, 0, 1]); } + B.geo('stone', new T.CylinderGeometry(4.6, 4.6, 2.2, 12), fx + 30, yT + 19.6, -20, 0, 1, 1, 1, C('#ece6da'), { cls: 'shell', uvs: 2 }); + B.geo('majolica', B.geos.hemi, fx + 30, yT + 20.7, -20, 0, 9, 7, 9, null, { uScale: 5, vScale: 2, cls: 'shell' }); + B.geo('stone', B.geos.cyl8, fx + 30, yT + 24.1, -20, 0, 0.9, 1.2, 0.9, C('#ece6da'), { cls: 'detail' }); + // the bell tower (campanile): five stages, the top with interlaced arches and a majolica cupola, four small turrets + var tx = 33, tz = -38, ty = yT; + B.box('stone', tx, ty - 3, tz, 6.4, 22, 6.4, 0, { col: C('#d9cfbd'), collide: 'stone', kind: 'tower', uvs: 1.6, cls: 'shell' }); + B.box('stone', tx, ty - 3, tz, 6.4, 27, 6.4, 0, { col: C('#d9cfbd'), uvs: 1.6, cls: 'far', topCol: C('#d9b03a') }); + for (i = 0; i < 4; i++) { + B.box('stone', tx, ty + 4 + i * 4.5, tz, 6.8, 0.35, 6.8, 0, { col: C('#efe9dc'), ao: 0, cls: 'shell', uvs: 1.5 }); + for (b = 0; b < 4; b++) { + var tf = K.faceFrame(tx, tz, 1, 0, b < 2 ? 0 : (b === 2 ? 3.2 : -3.2), b === 0 ? 3.2 : b === 1 ? -3.2 : 0, b < 2 ? 0 : (b === 2 ? 1 : -1), b === 0 ? 1 : b === 1 ? -1 : 0); + var two = i > 1; + (two ? [-0.75, 0.75] : [0]).forEach(function (u) { K.fq('dark', tf, u - 0.55, u + 0.55, ty + 5.4 + i * 4.5, ty + 7.2 + i * 4.5, C('#ffffff'), 0.03); var p = K.fp(tf, u, ty + 7.2 + i * 4.5, 0.03); B.geo('dark', B.geos.halfDisc, p.x, p.y, p.z, Math.atan2(tf.nx, tf.nz), 1.1, 1.1, 1, C('#ffffff'), { cls: 'flat' }); }); + } + } + B.geo('stone', new T.CylinderGeometry(2.7, 2.9, 5, 12), tx, ty + 21.5, tz, 0, 1, 1, 1, C('#ece6da'), { cls: 'shell', uvs: 1.6 }); + for (i = 0; i < 12; i++) { var a = i / 12 * 6.283; B.box('dark', tx + Math.cos(a) * 2.75, ty + 20.4, tz + Math.sin(a) * 2.75, 0.6, 2.2, 0.6, -a + Math.PI / 2, { cls: 'detail' }); } + B.geo('majolica', B.geos.hemi, tx, ty + 24, tz, 0, 5.6, 6.2, 5.6, null, { uScale: 4, vScale: 2, cls: 'shell' }); + for (i = 0; i < 4; i++) { + var ox = (i % 2 ? 2.7 : -2.7), oz = (i < 2 ? 2.7 : -2.7); + B.geo('stone', new T.CylinderGeometry(0.55, 0.6, 2.4, 8), tx + ox, ty + 20.2, tz + oz, 0, 1, 1, 1, C('#e2dccf'), { cls: 'shell' }); + B.geo('majolica', B.geos.hemi8, tx + ox, ty + 21.4, tz + oz, 0, 1.2, 1.3, 1.2, null, { uScale: 2, vScale: 1, cls: 'shell' }); + } + K.lamp(28, -8, yT); K.lamp(28, -32, yT); + K.balustrade(27.2, -45.6, 27.2, -33, yT, { noCover: true }); K.balustrade(27.2, -7, 27.2, -6.2, yT, { noCover: true }); + K.planter(31, -7.5, yT, 0, { pot: true }); K.planter(31, -32.5, yT, 0, { pot: true, hex: '#3f6b2c' }); + } + + // ---- the waterfront: beach with umbrellas, the harbour breakwater and quay, moored boats, palms + function buildWaterfront() { + var i, k; + B.box('paving', -3, 2.45, 14, 54, 0.15, 16, 0, { col: C('#d6cfc2'), ao: 0, uvs: 3, collide: 'stone', kind: 'floor', cls: 'shell' }); // waterfront square + B.box('concrete', 26, 1.0, 28, 36, 0.6, 12, 0, { col: C('#d4cdbf'), ao: 0.2, uvs: 3, collide: 'stone', kind: 'floor', cls: 'shell', topMat: 'paving' }); // quay + W.addBox({ x: 26, z: 34.2, y0: -3, y1: 1.6, hx: 18, hz: 0.3, mat: 'stone' }); // quay edge (nothing to stand on beyond) + B.box('concrete', 26, -3, 34.3, 36.4, 4.5, 0.6, 0, { col: C('#bdb5a6'), uvs: 3, cls: 'shell', ao: 0.4 }); + // a low sea wall with gaps (steps down to the sand) between the square and the beach + [[-30, -17], [-13, -4], [4, 8]].forEach(function (s) { B.box('rubble', (s[0] + s[1]) / 2, 2.0, 22.3, s[1] - s[0], 1.3, 0.5, 0, { col: C('#d3c9b7'), uvs: 2, cls: 'shell', collide: 'stone', cover: true, kind: 'wall', topMat: 'stone' }); }); + [-15, -2].forEach(function (sx) { K.stair(sx, 22.2, 2.6, sx, 25.4, W.terrainH(sx, 26) + 0.05, 2.0, { base: 0.2 }); }); + // beach umbrellas and loungers in rows (Marina Grande), a lifeguard chair, boats pulled up on the sand + for (var r = 0; r < 3; r++) for (i = 0; i < 9; i++) { + var x = -38 + i * 4.2 + (r % 2) * 2, z = 26.5 + r * 3.6, ty = W.terrainH(x, z); + if (ty < 0.25 || (Math.abs(x + 15) < 2 && r === 0) || (Math.abs(x + 2) < 2 && r === 0)) continue; + K.umbrella(x, z, ty, r === 1 ? 3 : 2, { r: 2.5 }); + K.lounger(x + 1, z + 0.6, W.terrainH(x + 1, z + 0.6), 0.1, r === 1 ? '#f1d98a' : '#f4f0e8'); K.lounger(x - 0.9, z + 0.6, W.terrainH(x - 0.9, z + 0.6), -0.08, r === 1 ? '#f1d98a' : '#f4f0e8'); + } + B.box('wood', 2, W.terrainH(2, 28), 28, 1.2, 2.2, 1.2, 0, { col: C('#f2efe8'), cls: 'detail', noSides: false }); B.box('paint', 2, W.terrainH(2, 28) + 2.2, 28, 1.5, 0.08, 1.5, 0, { col: C('#c9402e'), cls: 'detail', ao: 0 }); + // the breakwater (molo): a stone mole out from the quay, then west + var mole = [[34, 30], [36, 60], [33, 92], [16, 108], [-6, 112]]; + for (i = 0; i < mole.length - 1; i++) { + var a = mole[i], b = mole[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), yaw = Math.atan2(b[0] - a[0], b[1] - a[1]); + B.box('rubble', (a[0] + b[0]) / 2, -6, (a[1] + b[1]) / 2, 7, 8.2, L + 3.5, yaw, { col: C('#c4baa9'), collide: 'stone', kind: 'mole', uvs: 2.4, cls: 'shell', topMat: 'paving', topUvs: 3, deck: true }); + // sea wall along the outer side (cover) + var sx = Math.cos(yaw), sz = -Math.sin(yaw); + B.box('rubble', (a[0] + b[0]) / 2 + sx * 3.2, 2.2, (a[1] + b[1]) / 2 + sz * 3.2, 0.8, 1.2, L + 3.5, yaw, { col: C('#b9af9e'), collide: 'stone', cover: true, kind: 'wall', uvs: 2, cls: 'shell', topMat: 'stone' }); + // concrete blocks against the waves, bollards and nets along the inner edge + for (k = 0; k < L / 3; k++) { + var t = k / (L / 3); + B.box('concrete', a[0] + (b[0] - a[0]) * t + sx * 5.3, -1.5, a[1] + (b[1] - a[1]) * t + sz * 5.3, 2.2, 3.2, 2.2, yaw + k, { col: Cv('#cbc5b9', 0.9 + M.hash2(k, i) * 0.2), ao: 0.3, cls: 'shell', uvs: 2 }); + } + for (k = 1; k < L / 9; k++) { t = k / (L / 9); K.bollard(a[0] + (b[0] - a[0]) * t - sx * 2.9, a[1] + (b[1] - a[1]) * t - sz * 2.9, 2.2, 'iron'); } + K.nets(a[0] + (b[0] - a[0]) * 0.4 - sx * 1.4, a[1] + (b[1] - a[1]) * 0.4 - sz * 1.4, 2.2, i % 2 ? '#4f7d6a' : '#a8683a'); + } + K.crate(35.2, 47, 0.3, 0.9, '#7d8a8c', 2.2); K.crate(34.2, 78, 0.8, 1.1, null, 2.2); K.crate(25, 101, 0.2, 1.0, '#8f7253', 2.2); + // the little lighthouse at the end of the mole + B.geo('stucco', new T.CylinderGeometry(0.8, 1.15, 6, 12), -6, 5.2, 112, 0, 1, 1, 1, C('#f2f0ea'), { cls: 'shell', uvs: 2 }); + B.geo('paint', B.geos.cyl, -6, 8.2, 112, 0, 2.1, 0.14, 2.1, C('#3a3836'), { cls: 'detail' }); + B.geo('glass', B.geos.cyl8, -6, 8.34, 112, 0, 1.2, 0.9, 1.2, C('#ffffff'), { cls: 'detail' }); + B.geo('paint', B.geos.cone, -6, 9.24, 112, 0, 1.6, 0.7, 1.6, C('#c43b31'), { cls: 'shell' }); + B.box('lamp', -6, 8.5, 112, 0.5, 0.5, 0.5, 0, { cls: 'flat' }); + W.addBox({ x: -6, z: 112, y0: 0, y1: 8, hx: 1, hz: 1, mat: 'plaster' }); + // boats moored inside the harbour, bows to the quay; a few pulled up on the beach + var bc = ['#f2efe8', '#e9e2d0', '#2f6fa8', '#f2efe8', '#c9473b', '#f2efe8']; + for (i = 0; i < 9; i++) K.boat(10 + i * 2.6, 39 + (i % 2) * 0.6, 0.05 * (i % 3), bc[i % bc.length], 5 + (i % 3)); + for (i = 0; i < 5; i++) K.boat(14 + i * 3.1, 70 + (i % 2) * 6, 1.6 + 0.1 * i, bc[(i + 2) % bc.length], 7); + [[-25, 31.5, 1.3, '#2f6fa8', 5], [-21, 32, 1.45, '#f2efe8', 4.5], [-41.5, 30, 1.9, '#e9e2d0', 5], [5.5, 30, 1.2, '#c9473b', 4.5]].forEach(function (q) { K.boat(q[0], q[1], q[2], q[3], q[4], W.terrainH(q[0], q[1]) + 0.05, 0.22); }); + K.nets(-23, 29.4, null, '#4f7d6a'); K.nets(3.6, 28.2, null, '#a8683a'); + // bollards, crates, fish boxes on the quay (cover) + for (i = 0; i < 6; i++) K.bollard(12 + i * 5.5, 33.3, 1.6, 'iron'); + K.crate(30, 26, 0.2, null, null, 1.6); K.crate(31.2, 26.2, 0.4, null, null, 1.6); K.crate(30.6, 27.3, 0.1, 0.8, null, 1.6); K.crate(40, 24, 0.7, 1.2, '#7d8a8c', 1.6); + K.box(22, 31.5, 1.6, 0.2, '#6f9aa8', 3); K.box(22.8, 31.6, 1.6, 0.5, '#6f9aa8', 2); K.box(15, 31.8, 1.6, 0.1, '#b99a6e', 2); K.nets(17.5, 31.2, 1.6, '#4f7d6a'); + K.car(20, 24.5, Math.PI / 2, '#3e5f7d', null, 1.6); K.car(-28, 12, Math.PI / 2 + 0.05, '#b8433a', null, 2.6); K.car(-35, 18, -Math.PI / 2, '#e8e2cf', 'van', 2.6); + K.scooter(-22, 9.3, 0.1, '#c7d9d2', 2.6); K.scooter(-20.6, 9.2, 0.2, '#e8d9a8', 2.6); K.scooter(18.5, 9.2, -0.1, '#b8433a', 2.6); + K.bench(-10, 20.6, 2.6, Math.PI); K.bench(10, 20.6, 2.6, Math.PI); K.bin(-6, 20.8, 2.6); K.bin(14.5, 20.8, 2.6); + // palms along the waterfront road; lamps + for (i = 0; i < 6; i++) K.tree('palm', -32 + i * 11, 21.3, 2.6); + for (i = 0; i < 5; i++) K.lamp(-30 + i * 14, 9.2, 2.6); + // waterfront buildings (hotels, cafés) east and west of the square, an arcade along the nearest ones + var hues = ['#f0e4c8', '#e9b899', '#efd9a0', '#f2eee6']; + for (i = 0; i < 3; i++) { + K.house(-44 - i * 12, 6 - i * 3, 11, 10, Math.PI * 0.95, { floors: 4 + (i % 2), wall: hues[i], roof: i === 1 ? 'vault' : 'flat', shutter: SHUTTERS[i], shop: 2 + i * 5, balc: 0.7, frames: true }); + K.occMark(-44 - i * 12, 6 - i * 3, 11, 10, 0, 1); + K.house(36 + i * 13, 4 + i * 2, 11, 11, Math.PI * 1.03, { floors: 4 + ((i + 1) % 2), wall: hues[(i + 2) % 4], roof: i === 2 ? 'tile' : 'flat', shutter: SHUTTERS[(i + 1) % 3], shop: 9 + i * 2, balc: 0.7, frames: true }); + K.occMark(36 + i * 13, 4 + i * 2, 11, 11, 0, 1); + } + // café terraces in front of the hotels + for (i = 0; i < 4; i++) { K.cafeTable(31 + i * 3, 11.5, null, { chairs: 2 }); if (i % 2 === 0) K.umbrella(32.4 + i * 3, 11.2, null, 0, { r: 2.4 }); } + for (i = 0; i < 3; i++) { K.cafeTable(-41 - i * 3, 12.8 - i * 0.7, null, { chairs: 2, cloth: '#e9dfc6' }); } + } + + // ---- Villa Calcara on the western headland (mission 1). The walls, doors and cover are exactly where the mission expects. + function buildVilla() { + var y = 24, vx = -170, vz = 30, i, k; + RP.map.villa = { x: vx, z: vz, y: y }; + K.occMark(-168, 40, 70, 64, 0, 0); + // the house: hollow ground floor with rooms (hall, salon, study), solid upper floor and roof terrace + var hx0 = -182, hx1 = -158, hz0 = 18, hz1 = 36, t = 0.4, fh = 3.6, wc = C('#ebbd9d'); + function hw(x0, z0, x1, z1) { // straight wall with collision + var L = Math.hypot(x1 - x0, z1 - z0), yaw = Math.atan2(x1 - x0, z1 - z0) + Math.PI / 2; + B.box('aged', (x0 + x1) / 2, y - 0.6, (z0 + z1) / 2, L, fh + 0.6, t, yaw, { col: wc, collide: 'plaster', kind: 'wall', uvs: 3, cover: true, cls: 'shell' }); + } + B.box('stone', (hx0 + hx1) / 2, y - 1, (hz0 + hz1) / 2, hx1 - hx0, 1.05, hz1 - hz0, 0, { col: C('#cfc3ae'), collide: 'stone', uvs: 1.5, cls: 'shell', topMat: 'tiles', topUvs: 2.4 }); // floor + // south front (toward the terrace): three tall French doors open onto the party + var doors = [-176, -170, -164]; + var xs = [hx0].concat([].concat.apply([], doors.map(function (d) { return [d - 1, d + 1]; }))).concat([hx1]); + for (i = 0; i < xs.length; i += 2) hw(xs[i], hz1, xs[i + 1], hz1); + doors.forEach(function (d) { B.box('aged', d, y + 2.6, hz1, 2, fh - 2.6, t, 0, { col: wc, collide: 'plaster', uvs: 3, cls: 'shell' }); }); + // north wall with a service door at x -164; west and east walls + hw(hx0, hz0, -165.2, hz0); hw(-162.8, hz0, hx1, hz0); + B.box('aged', -164, y + 2.4, hz0, 2.4, fh - 2.4, t, 0, { col: wc, collide: 'plaster', uvs: 3, cls: 'shell' }); + hw(hx0, hz0, hx0, hz1); hw(hx1, hz0, hx1, 25.8); hw(hx1, 28.2, hx1, hz1); // east door at z 27 + B.box('aged', hx1, y + 2.4, 27, t, fh - 2.4, 2.4, 0, { col: wc, collide: 'plaster', uvs: 3, cls: 'shell' }); + // interior: the study in the north-west corner (x -182..-172, z 18..26) with a door from the hall + hw(-172, hz0, -172, 23.8); hw(-182, 26, -175.4, 26); hw(-173.4, 26, -172, 26); + B.box('aged', -174.4, y + 2.4, 26, 2, fh - 2.4, t, 0, { col: wc, collide: 'plaster', uvs: 3, cls: 'shell' }); + // ceiling and the solid upper floor, cornice, roof terrace parapet + B.box('facade', (hx0 + hx1) / 2, y + fh, (hz0 + hz1) / 2, hx1 - hx0 + 0.4, 3.6, hz1 - hz0 + 0.4, 0, { col: wc, collide: 'plaster', kind: 'house', cls: 'shell', fitUV: [7, 1.125], bottom: true, topMat: 'paving' }); + B.box('aged', (hx0 + hx1) / 2, y - 0.6, (hz0 + hz1) / 2, hx1 - hx0 + 0.4, 7.8, hz1 - hz0 + 0.4, 0, { col: wc, uvs: 3, cls: 'far', topCol: C('#d9d2c4') }); + B.box('stucco', (hx0 + hx1) / 2, y + fh * 2, (hz0 + hz1) / 2, hx1 - hx0 + 0.9, 0.3, hz1 - hz0 + 0.9, 0, { col: C('#f4efe4'), ao: 0, cls: 'shell', uvs: 3 }); + B.box('stucco', (hx0 + hx1) / 2, y + fh - 0.1, (hz0 + hz1) / 2, hx1 - hx0 + 0.7, 0.2, hz1 - hz0 + 0.7, 0, { col: C('#f4efe4'), ao: 0, cls: 'detail', uvs: 3, noTop: true }); + K.railing(hx0, hz1 + 0.3, y + fh * 2 + 0.3, hx1, hz1 + 0.3, y + fh * 2 + 0.3, { noCol: true }); K.railing(hx0, hz0 - 0.3, y + fh * 2 + 0.3, hx1, hz0 - 0.3, y + fh * 2 + 0.3, { noCol: true }); + // upper-floor windows and shutters (pale green) over the painted bays, fanlights over the French doors + var fS = K.faceFrame((hx0 + hx1) / 2, (hz0 + hz1) / 2, 1, 0, 0, (hz1 - hz0) / 2 + 0.2, 0, 1), fN = K.faceFrame((hx0 + hx1) / 2, (hz0 + hz1) / 2, 1, 0, 0, -(hz1 - hz0) / 2 - 0.2, 0, -1); + var sp = (hx1 - hx0 + 0.4) / 7, Bz = RP.MapTex.BAY, UV = [0, 0, 1, 0, 1, 1, 0, 1]; + [fS, fN].forEach(function (F) { + for (i = 0; i < 7; i++) { + var u = -(hx1 - hx0 + 0.4) / 2 + sp * (i + 0.5), w0 = y + fh + 1.0, w1 = y + fh + 2.5; + K.fq('window', F, u - Bz.hw * sp, u + Bz.hw * sp, w0, w1, C('#ffffff'), 0.035, UV); + K.fq('louvre', F, u - (Bz.hw + Bz.sh + 0.012) * sp, u - (Bz.hw + 0.012) * sp, w0, w1, C('#7fa38a'), 0.05, UV); K.fq('louvre', F, u + (Bz.hw + 0.012) * sp, u + (Bz.hw + Bz.sh + 0.012) * sp, w0, w1, C('#7fa38a'), 0.05, UV); + } + }); + doors.forEach(function (d) { B.box('lamp', d, y + 2.7, hz1 + 0.21, 1.7, 0.6, 0.02, 0, { cls: 'flat' }); B.box('stone', d, y + 3.34, hz1 + 0.24, 2.3, 0.14, 0.1, 0, { col: C('#f4efe4'), cls: 'detail', ao: 0 }); }); + W.addZone({ x0: hx0, z0: hz0, x1: hx1, z1: hz1, y0: y - 1, y1: y + fh, indoor: true, name: 'villa' }); + // interior dressing: study desk (the objective), shelves, the hall's sofas and a cabinet (cover) + B.box('wood', -178, y, 20.2, 2.2, 0.8, 1.1, 0, { col: C('#5a3a26'), collide: 'wood', cover: true, kind: 'desk', cls: 'detail' }); + B.box('wood', -181.5, y, 22, 0.5, 2.4, 6, 0, { col: C('#4e3524'), collide: 'wood', kind: 'shelf', cls: 'detail' }); + B.box('fabric', -168, y, 30, 3, 0.8, 1, 0, { col: C('#ece3cf'), collide: 'cloth', cover: true, kind: 'sofa', cls: 'detail' }); + B.box('wood', -162, y, 21, 1.6, 1.1, 0.8, 0, { col: C('#2a1c14'), collide: 'wood', cover: true, kind: 'cabinet', cls: 'detail' }); + B.box('paint', -177.6, y + 0.8, 20.2, 0.5, 0.06, 0.36, 0.2, { col: C('#6e1f24'), cls: 'detail', ao: 0 }); // the ledger + RP.map.spots.ledger = { x: -178, y: y + 0.85, z: 20.2 }; + // the terrace: paving, balustrade on the cliff edge, the bar, tables, string lights, pergola with vines + B.box('paving', -168, y - 0.15, 50, 40, 0.15, 28, 0, { col: C('#e4dccd'), uvs: 2.4, collide: 'stone', kind: 'floor', cls: 'shell' }); + K.balustrade(-188, 64, -148, 64, y); K.balustrade(-188, 36, -188, 64, y); K.balustrade(-148, 44, -148, 64, y); + B.box('wood', -152, y, 40, 1.0, 1.15, 6, 0, { col: C('#efe9dc'), collide: 'wood', cover: true, kind: 'bar', cls: 'shell' }); + B.box('stone', -152, y + 1.15, 40, 1.2, 0.08, 6.2, 0, { col: C('#2b2a28'), cls: 'detail', ao: 0 }); + for (i = 0; i < 6; i++) { B.geo('glass', B.geos.cyl6, -152 + (M.hash2(i, 1) - 0.5) * 0.5, y + 1.23, 37.6 + i * 0.9, 0, 0.09, 0.3, 0.09, C('#9fd0b0'), { cls: 'detail' }); } + for (i = 0; i < 6; i++) { + var tx = -182 + (i % 3) * 9, tz = 46 + Math.floor(i / 3) * 8; + B.geo('fabric', B.geos.cyl, tx, y, tz, 0, 1.8, 0.78, 1.8, C('#f7f3ea'), { cls: 'shell' }); + B.box('lamp', tx, y + 0.8, tz, 0.08, 0.14, 0.08, 0, { cls: 'flat' }); + W.addBox({ x: tx, z: tz, y0: y, y1: y + 0.78, hx: 0.85, hz: 0.85, mat: 'cloth', cover: true, kind: 'table' }); + } + // pergola with vines over the east part of the terrace + for (i = 0; i < 4; i++) for (k = 0; k < 2; k++) { + var px = -160 + i * 3.5, pz = 44 + k * 8; + B.box('stucco', px, y, pz, 0.45, 2.9, 0.45, 0, { col: C('#efe9dc'), collide: 'plaster', kind: 'pillar', cls: 'shell', uvs: 3 }); + K.leaf(px, y + 3.05, pz + 2, 3.5, 0.6, 5, '#4b6d33'); + } + for (i = 0; i < 4; i++) B.box('bark', -160 + i * 3.5, y + 2.9, 48, 0.12, 0.12, 9, 0, { col: C('#7a6652'), ao: 0, cls: 'detail' }); + for (i = 0; i < 7; i++) B.box('bark', -154.75, y + 3.02, 44 + i * 1.33, 11.4, 0.07, 0.07, 0, { col: C('#7a6652'), ao: 0, cls: 'detail' }); + // string lights over the terrace (bloom at dusk) + for (i = 0; i < 4; i++) for (k = 0; k < 14; k++) { + var sx2 = -186 + k * 2.8, sz2 = 40 + i * 6.5, sag = Math.sin(k / 13 * Math.PI) * 0.6; + B.box('lamp', sx2, y + 3.6 - sag, sz2, 0.1, 0.1, 0.1, 0, { cls: 'flat' }); + } + [-186, -150].forEach(function (x) { K.lamp(x, 38.5, y); K.lamp(x, 62, y); }); + // the reflecting pool east of the house: a pale tiled basin 0.6 m deep inside a stone rim, under a glassy surface + B.box('tiles', -146, y - 0.75, 26, 10.6, 0.12, 12.6, 0, { col: C('#d7eef0'), ao: 0, cls: 'flat', uvs: 0.6 }); + [[-146, 19.35, 12, 0.7], [-146, 32.65, 12, 0.7], [-151.65, 26, 0.7, 12.6], [-140.35, 26, 0.7, 12.6]].forEach(function (r) { + B.box('stone', r[0], y - 0.75, r[1], r[2], 0.87, r[3], 0, { col: C('#e7e1d4'), ao: 0, cls: 'shell', uvs: 1.5 }); + }); + [[-146, 19.95, 10.6, 0.06], [-146, 32.05, 10.6, 0.06], [-151.25, 26, 0.06, 12.6], [-140.75, 26, 0.06, 12.6]].forEach(function (r) { + B.box('tiles', r[0], y - 0.65, r[1], r[2], 0.7, r[3], 0, { col: C('#bfe2e6'), ao: 0, cls: 'detail', uvs: 0.6 }); // the basin's tiled sides + }); + RP.Sea && RP.Sea.pool && RP.Sea.pool(-146, y + 0.02, 26, 10.6, 12.6); + // the stone deck round it, over the cut in the ground (walkable at the plateau's level) + [[-146, 18.15, 15.8, 1.7], [-146, 33.85, 15.8, 2.3], [-153.15, 26, 1.7, 13.4], [-139.12, 26, 1.75, 13.4]].forEach(function (r) { + B.box('paving', r[0], y - 0.9, r[1], r[2], 0.92, r[3], 0, { col: C('#e9e3d6'), ao: 0, cls: 'shell', uvs: 1 }); + W.addBox({ x: r[0], z: r[1], y0: y - 0.9, y1: y + 0.02, hx: r[2] / 2, hz: r[3] / 2, mat: 'stone', cover: false, kind: 'deck' }); + }); + // you can wade in: the floor is the basin's (water underfoot), the rim is a low kerb stepped over + W.addBox({ x: -146, z: 26, y0: y - 0.9, y1: y - 0.63, hx: 5.3, hz: 6.3, mat: 'water', cover: false, kind: 'pool' }); + [[-146, 19.35, 6, 0.35], [-146, 32.65, 6, 0.35], [-151.65, 26, 0.35, 6.3], [-140.35, 26, 0.35, 6.3]].forEach(function (r) { + W.addBox({ x: r[0], z: r[1], y0: y - 0.9, y1: y + 0.12, hx: r[2], hz: r[3], mat: 'stone', cover: false, kind: 'kerb' }); + }); + // boundary wall (2.2 m: climbable) with the front gate on the east and a service gate to the lemon terraces + var by = y, WO = { cap: true }; + K.wall(-196, 6, -158, 6, by - 0.4, 2.6, 0.5, '#e6dccb', WO); K.wall(-154, 6, -138, 6, by - 0.4, 2.6, 0.5, '#e6dccb', WO); + K.wall(-196, 6, -196, 36, by - 0.4, 2.6, 0.5, '#e6dccb', WO); + K.wall(-138, 6, -138, 10, by - 0.4, 2.6, 0.5, '#e6dccb', WO); K.wall(-138, 16, -138, 44, by - 0.4, 2.6, 0.5, '#e6dccb', WO); + // gate piers and a guard booth at the front gate + [9.6, 16.4].forEach(function (gz) { + B.box('stone', -138, by, gz, 1, 3.2, 1, 0, { col: C('#d7cbb6'), collide: 'stone', kind: 'pier', cls: 'shell', uvs: 1.5 }); + B.box('stone', -138, by + 3.2, gz, 1.25, 0.18, 1.25, 0, { col: C('#ebe4d5'), cls: 'detail', ao: 0, uvs: 1.5 }); B.geo('stone', B.geos.sphere, -138, by + 3.7, gz, 0, 0.6, 0.6, 0.6, C('#ebe4d5'), { cls: 'detail' }); + }); + // (the booth stands inside the gateway on its south side, on level ground and clear of the pool) + B.box('aged', -142.8, by, 11.6, 2.2, 2.6, 2.2, 0, { col: C('#efe6d6'), collide: 'plaster', cover: true, kind: 'booth', cls: 'shell', uvs: 3 }); + B.geo('roof', K.hipGeo(2.8, 2.8, 0.8), -142.8, by + 2.6, 11.6, 0, 1, 1, 1, C('#ffffff'), { cls: 'shell' }); + K.lamp(-136, 8.6, null); K.lamp(-136, 17.4, null); + // gardens inside the walls: cypress avenue, umbrella pines, hedges (block sight), lemon trees + for (i = 0; i < 6; i++) { K.tree('cypress', -192, 10 + i * 4.4); } + K.tree('pine', -150, 12); K.tree('pine', -186, 66); K.tree('pine', -142, 52); + for (i = 0; i < 5; i++) { + var hx2 = -186 + i * 6; + B.box('foliage', hx2, y - 0.2, 12, 4.4, 1.25, 1.0, 0, { col: C('#35522a'), collide: 'cloth', cover: true, kind: 'hedge', cls: 'shell' }); + K.leaf(hx2, y + 1.1, 12, 4.6, 0.8, 1.6, '#3f6131', 0); K.leaf(hx2, y + 0.6, 12, 4.6, 1.2, 1.5, '#3f6131', 0); + } + [[-153.5, 37.6], [-146.5, 37.8], [-141, 37.6], [-141, 14.5]].forEach(function (t) { K.tree('lemon', t[0], t[1], y); }); // round the pool, not in it + // lemon terraces below the villa (stealth route): dry-stone retaining walls and pergolas + [[-176, 2, 20], [-150, -10, 16.5]].forEach(function (p) { + for (var a = 0; a < 3; a++) for (var b = 0; b < 3; b++) { + var lx = p[0] - 6 + a * 6, lz = p[1] - 5 + b * 5; + K.tree('lemon', lx, lz, p[2]); + B.geo('bark', B.geos.cyl6, lx + 2.5, p[2], lz + 2.2, 0, 0.12, 2.4, 0.12, C('#6d5a45'), { cls: 'detail' }); + } + K.wall(p[0] - 12, p[1] + 9, p[0] + 12, p[1] + 9, p[2] - 3, 3.1, 0.7, '#b9ac96', { mat: 'rubble', cmat: 'stone', uvs: 2 }); + for (a = 0; a < 4; a++) B.box('bark', p[0] - 9 + a * 6, p[2] + 2.4, p[1], 0.08, 0.08, 14, 0, { col: C('#6d5f50'), cls: 'detail', ao: 0 }); + for (a = 0; a < 5; a++) B.box('bark', p[0], p[2] + 2.48, p[1] - 6 + a * 3, 18, 0.06, 0.06, 0, { col: C('#6d5f50'), cls: 'detail', ao: 0 }); + }); + // steps from the villa down to its private landing (phase 2 boat dock) + K.stair(-178, 64.5, y, -178, 80, 3, 2.2, { base: 0, sideMat: 'rubble', cls: 'shell' }); + B.box('concrete', -178, 0, 84, 8, 3, 8, 0, { col: C('#c8bdab'), collide: 'stone', kind: 'dock', cls: 'shell', uvs: 3, deck: true }); + K.bollard(-175.2, 87, 3, 'iron'); K.bollard(-180.8, 87, 3, 'iron'); + W.addBox({ x: -183, z: 72, y0: 0, y1: y + 1, hx: 0.3, hz: 8, mat: 'stone', see: true }); W.addBox({ x: -173, z: 72, y0: 0, y1: y + 1, hx: 0.3, hz: 8, mat: 'stone', see: true }); + K.railing(-179.3, 64.6, y, -179.3, 80, 3, { noCol: true }); K.railing(-176.7, 64.6, y, -176.7, 80, 3, { noCol: true }); + } + + // ---- the Saracen watchtower on the east point + function buildTower() { + var x = 140, z = 54, y = W.terrainH(x, z); + B.box('rubble', x, y - 4, z, 8, 17, 8, 0.3, { col: C('#cdbfa6'), collide: 'stone', kind: 'tower', uvs: 2.4, cls: 'shell', topMat: 'paving' }); + B.box('rubble', x, y - 4, z, 8, 17, 8, 0.3, { col: C('#cdbfa6'), uvs: 2.4, cls: 'far' }); + for (var i = 0; i < 8; i++) B.box('rubble', x + Math.cos(i * 0.785 + 0.3) * 3.6, y + 13, z + Math.sin(i * 0.785 + 0.3) * 3.6, 1.2, 0.9, 1.2, 0.3, { col: C('#c4b69c'), cls: 'shell', uvs: 2.4 }); + B.box('rubble', x, y + 12.6, z, 8.5, 0.4, 8.5, 0.3, { col: C('#bfb197'), cls: 'shell', uvs: 2.4, noTop: true }); + B.box('dark', x + 4.02 * Math.sin(0.3 + Math.PI / 2), y + 7, z + 4.02 * Math.cos(0.3 + Math.PI / 2), 1, 1.6, 0.02, 0.3 + Math.PI / 2, { cls: 'flat' }); + B.box('dark', x + 4.02 * Math.sin(0.3), y + 5, z + 4.02 * Math.cos(0.3), 0.8, 1.2, 0.02, 0.3, { cls: 'flat' }); + } + + // ---- Amalfi's houses: frontage up the main street, then terraced up both slopes + function buildTown() { + var main = MAIN.pts, k; + // two buildings bridge the main street (supportici), as in the real lanes + K.archOver(-7, -69, Math.atan2(-4, -22) + Math.PI / 2 - Math.PI / 2, 5.2, 5, 8.0, { wall: '#efe1c0', floors: 2, name: 'supportico' }); + K.occMark(-7, -69, 14, 6, 0, 0); + K.archOver(-12.6, -114, 0.02, 5.2, 4.5, 14.3, { wall: '#ecd7a2', floors: 1, name: 'supportico' }); + K.occMark(-12.6, -114, 14, 5.5, 0, 0); + // small paved corners off the street (the missions place people and pickups here): a well, a bench, pots + [[3.7, -54, 9.8, 8.9, 6.5], [-10.7, -58.5, 5.4, 6.2, 6.9], [-8.1, -100, 4.6, 4.4, 12.2]].forEach(function (q, qi) { + K.occMark(q[0], q[1], q[2] + 1, q[3] + 1, 0, 0); + var qy = q[4]; + B.box('basalt', q[0], qy - 0.3, q[1], q[2], 0.35, q[3], 0, { col: C('#d9cfc0'), uvs: 2.4, cls: 'shell', ao: 0 }); + if (qi === 0) { + B.geo('stone', new T.CylinderGeometry(0.8, 0.9, 0.9, 8), 6.6, qy + 0.5, -56.4, 0, 1, 1, 1, C('#d9d2c4'), { cls: 'detail', uvs: 1.5 }); + B.geo('dark', new T.CylinderGeometry(0.62, 0.62, 0.04, 8), 6.6, qy + 0.93, -56.4, 0, 1, 1, 1, C('#ffffff'), { cls: 'flat' }); + W.addBox({ x: 6.6, z: -56.4, y0: qy, y1: qy + 0.95, hx: 0.75, hz: 0.75, mat: 'stone', cover: true, kind: 'well' }); + K.bench(7.4, -52.4, qy + 0.05, -Math.PI / 2); K.tree('lemon', 6.4, -50.8, qy); K.planter(0.2, qy + 0.05, -57.6, 0, { pot: true }); K.lamp(7.8, -57.8, qy + 0.05); + } else K.planter(q[0] - (qi === 1 ? 1.9 : -1.6), qy + 0.05, q[1] + 1.5, 0, { pot: true }); + if (qi === 2) { B.box('stone', -8.6, qy, -100, 2.6, 0.78, 1.0, 0, { col: C('#d9d2c4'), uvs: 1.5, cls: 'detail', collide: 'stone', cover: true, kind: 'ledge' }); } + }); + K.frontage(main, MAIN.w, rnd, { shops: 0.6 }); + [3, 4, 5, 6].forEach(function (q) { K.frontage(ROADS[q].pts, ROADS[q].w, rnd, { shops: 0.15, minW: 5.5, varW: 3, minD: 6, minF: 2, varF: 3, to: q === 3 ? 3 : 9 }); }); + for (k = 0; k < main.length - 1; k++) { + var a = main[k], b = main[k + 1], dir = Math.atan2(b[0] - a[0], b[1] - a[1]), nx = Math.cos(dir), nz = -Math.sin(dir); + K.lamp(a[0] + nx * 2.2, a[1] + nz * 2.2, null); + // washing strung across the street, pots and a scooter along the walls + var mx = (a[0] + b[0]) / 2, mz = (a[1] + b[1]) / 2, my = W.terrainH(mx, mz); + if (k < 7) { + var lf = K.faceFrame(mx, mz, Math.cos(dir), Math.sin(dir), 0, 0, 0, 1); lf.fyaw = dir; + K.laundry(lf, 0, my + 6.4 + (k % 2) * 3.2, 4.6); + K.planter(mx - nx * 2.1, my, mz - nz * 2.1, 0, { pot: true }); + if (k % 2) K.scooter(mx + nx * 2.0, mz + nz * 2.0, dir + 0.1, k % 4 === 1 ? '#c7d9d2' : '#e8d9a8', my); + else K.box(mx + nx * 2.05, mz + nz * 2.05, my, dir, null, 2); + } + } + // the head of the valley: the street ends at a closed gate in an old mill wall + K.wall(-12, -246, 16, -246, null, 6, 1.2, '#cfc3ad', { mat: 'rubble', cmat: 'stone', uvs: 2.4 }); + var gF = K.faceFrame(2, -246, 1, 0, 0, 0.62, 0, 1); K.fq('door', gF, -1.6, 1.6, W.terrainH(2, -244), W.terrainH(2, -244) + 3.4, C('#5b4a36'), 0.03, [0, 0, 1, 0, 1, 1, 0, 1]); + // the slopes: rows along the contours, houses facing the sea (or the valley), stepping up the hill + K.fillSlope({ x0: -120, x1: 130, z0: -250, z1: 10, ok: function (xx, zz) { + var ax = Math.abs(xx - valleyX(zz)); + if (ax > 110 || (zz > -20 && ax > 70)) return false; + if (xx < -110 && zz > -30) return false; // keep the villa headland open + return true; + }, core: function (xx, zz) { return Math.abs(xx - valleyX(zz)) <= 70; } }, rnd, { rowStep: 6.6, minStep: 6, varStep: 3.5, gap: 0.5, mark: 0.4 }); + } + + // ---- the coast road east of Amalfi: tunnels, retaining walls, the belvedere, the bus lay-by, the fjord bridge + function buildCoastRoad() { + var P = COAST.pts, i, k; + COAST.tunnels.forEach(function (t) { K.tunnel(LAND, COAST, t); }); + K.bridge(LAND, COAST); + for (k = 6; k < P.length - 1; k++) { + var a = P[k], b = P[k + 1], sg = COAST.segs[k]; if (sg.tunnel || sg.bridge) continue; + var dx = b[0] - a[0], dz = b[1] - a[1], L = Math.hypot(dx, dz), ux = -dz / L, uz = dx / L; + if (uz > 0) { ux = -ux; uz = -uz; } // uphill (inland) side + // a rubble retaining wall where the road is cut into the slope + var mx = (a[0] + b[0]) / 2, mz = (a[1] + b[1]) / 2, off = COAST.w / 2 + 1.1, up = W.terrainH(mx + ux * (off + 2.4), mz + uz * (off + 2.4)) - (a[2] + b[2]) / 2; + var opens = false; // a lane or steps leaving the road on this side: no wall across them + for (i = 0; i <= 6; i++) if (LAND.onRoad(a[0] + dx * i / 6 + ux * off, a[1] + dz * i / 6 + uz * off, 0.9)) opens = true; + if (up > 1.6 && !opens && !(a[0] >= 1340 && a[0] < 1545)) { + var hgt = Math.min(up + 0.3, 4.2), yaw = Math.atan2(dx, dz) + Math.PI / 2, lo = Math.min(a[2], b[2]) - 0.6; + B.box('rubble', mx + ux * off, lo, mz + uz * off, L + 0.3, (a[2] + b[2]) / 2 + hgt - lo, 0.7, yaw, { col: C('#c9bfad'), uvs: 2.4, cls: 'shell', collide: 'stone', kind: 'wall', topMat: 'stone', ao: 0.3 }); + } + // now and then: a cypress or a pine above the road, an agave on the verge + if (k % 3 === 0) { var tx = mx + ux * (off + 3.5), tz = mz + uz * (off + 3.5); if (!K.occAt(tx, tz) && W.terrainN(tx, tz).y > 0.5) K.tree(k % 2 ? 'cypress' : 'pine', tx, tz); } + } + // a closed tunnel mouth ends the road at the map's east edge + var e = P[P.length - 1]; + B.box('rubble', e[0] + 6, e[2] - 2, e[1] + 1, 3, 12, 22, 0.3, { col: C('#c2b8a6'), uvs: 2.4, cls: 'shell', collide: 'stone', kind: 'wall' }); + B.box('dark', e[0] + 4.3, e[2], e[1] + 0.6, 0.1, 5, 8, 0.3, { cls: 'flat' }); + for (i = 0; i < 3; i++) B.box('paint', e[0] - 2, e[2], e[1] - 3 + i * 3.2, 0.5, 1.0, 2.4, 0.3, { col: C(i % 2 ? '#f2efe6' : '#c9402e'), cls: 'detail', collide: 'stone', cover: true, kind: 'barrier' }); + + // ---- the belvedere: a half-round terrace over the sea, a kiosk, benches, a parked scooter, two pines + var bx = 466, bz = 36, by = 33.8; + B.geo('paving', new T.CylinderGeometry(13.2, 13.2, 0.3, 20), bx, by - 0.14, bz, 0, 1, 1, 1, C('#d9d2c5'), { cls: 'shell', uvs: 3 }); + for (i = 0; i <= 8; i++) { + var a0 = Math.PI * (0.06 + 0.88 * i / 9), a1 = Math.PI * (0.06 + 0.88 * (i + 1) / 9); + if (i < 9 - 0) K.parapet(bx + Math.cos(a0) * 12.6, bz + Math.sin(a0) * 12.6, by, bx + Math.cos(a1) * 12.6, bz + Math.sin(a1) * 12.6, by, { deep: 3 }); + } + K.bench(bx - 5, bz + 9, by, Math.PI); K.bench(bx + 5, bz + 9, by, Math.PI); K.bench(bx, bz + 10.6, by, Math.PI); K.bin(bx + 8.5, bz + 6, by); + // the kiosk: granita and lemons (invented name on the sign layer) + B.box('aged', bx - 8.5, by, bz + 1.5, 3.2, 2.5, 2.6, 0.5, { col: C('#f1e4b8'), cls: 'shell', uvs: 3, collide: 'plaster', cover: true, kind: 'kiosk' }); + B.geo('roof', K.hipGeo(4.2, 3.6, 0.9), bx - 8.5, by + 2.5, bz + 1.5, 0.5, 1, 1, 1, C('#ffffff'), { cls: 'shell' }); + var kf = K.faceFrame(bx - 8.5, bz + 1.5, Math.cos(0.5), Math.sin(0.5), 0, 1.3, 0, 1); kf.fyaw = 0.5; + K.fq('dark', kf, -1.2, 1.2, by + 1.0, by + 2.1, C('#ffffff'), 0.03); K.fq('wood', kf, -1.4, 1.4, by + 0.9, by + 1.0, C('#9a7a55'), 0.25); + var su = RP.MapTex.signUV(4); K.fq('sign', kf, -1.2, 1.2, by + 2.12, by + 2.46, C('#ffffff'), 0.05, [su[0], su[1], su[2], su[1], su[2], su[3], su[0], su[3]]); + K.awning(kf, 0, by + 2.0, 3.0, 1.1, 3); + K.box(bx - 6.4, bz + 3.4, by, 0.4, null, 2); K.box(bx - 6.0, bz + 4.1, by, 0.9, '#e9c93a', 1); + K.cafeTable(bx - 3, bz + 4.5, by, { chairs: 2 }); K.cafeTable(bx + 0.5, bz + 5.5, by, { chairs: 2 }); K.umbrella(bx - 1.2, bz + 5.2, by, 3); + K.scooter(bx + 9, bz - 1, 1.2, '#c7d9d2', by); + K.tree('pine', bx - 11, bz - 4); K.tree('pine', bx + 12, bz - 3); + K.lamp(bx - 6, bz - 3.5, by); K.lamp(bx + 7, bz - 3.5, by); + + // ---- the bus lay-by on the headland: shelter, bench, a parked coach (invented livery), parapet + var lx = 1012, lz = 62, ly = 38; + B.geo('asphalt', new T.CylinderGeometry(11.2, 11.2, 0.3, 18), lx, ly - 0.14, lz, 0, 1, 1, 1, C('#b9b6b2'), { cls: 'shell', uvs: 4 }); + for (i = 0; i < 9; i++) { var c0 = Math.PI * (0.05 + 0.9 * i / 9), c1 = Math.PI * (0.05 + 0.9 * (i + 1) / 9); K.parapet(lx + Math.cos(c0) * 10.8, lz + Math.sin(c0) * 10.8, ly, lx + Math.cos(c1) * 10.8, lz + Math.sin(c1) * 10.8, ly, { deep: 3 }); } + // the coach: long box body, band of glass, wheels + var cy = ly + 0.02, cyaw = Math.PI / 2 + 0.06, cc = Math.cos(cyaw), cs = Math.sin(cyaw); + B.box('paint', lx, cy + 0.45, lz + 4.5, 2.5, 2.75, 10.5, cyaw, { col: C('#2f5f8f'), cls: 'shell', ao: 0.15 }); + B.box('paint', lx, cy + 0.45, lz + 4.5, 2.54, 0.9, 10.54, cyaw, { col: C('#e9e4d6'), cls: 'detail', ao: 0, noTop: true }); + B.box('glass', lx, cy + 1.75, lz + 4.5, 2.56, 0.95, 10.0, cyaw, { cls: 'detail', noTop: true }); + [-3.6, 3.4].forEach(function (o) { [-1.1, 1.1].forEach(function (sd) { B.geo('dark', B.geos.cyl8, lx + sd * cc + o * cs, cy + 0.5, lz + 4.5 - sd * cs + o * cc, cyaw, 1.0, 0.3, 1.0, C('#ffffff'), { roll: Math.PI / 2, cls: 'detail' }); }); }); + W.addBox({ x: lx, z: lz + 4.5, y0: ly, y1: ly + 3.2, hx: 1.27, hz: 5.3, yaw: cyaw, mat: 'car', cover: true, kind: 'bus' }); + // the shelter + B.box('metal', lx - 5.5, ly + 2.3, lz - 2.2, 3.6, 0.08, 1.5, 0.15, { col: C('#3a4a55'), cls: 'shell', ao: 0, bottom: true }); + B.box('glass', lx - 5.5 - Math.sin(0.15) * 0.7, ly + 0.2, lz - 2.2 - Math.cos(0.15) * 0.7, 3.5, 2.0, 0.04, 0.15, { cls: 'detail' }); + [-1.7, 1.7].forEach(function (o) { B.box('metal', lx - 5.5 + o * Math.cos(0.15), ly, lz - 2.2 - o * Math.sin(0.15), 0.07, 2.3, 0.07, 0.15, { col: C('#3a4a55'), cls: 'detail', ao: 0 }); }); + K.bench(lx - 5.5, lz - 2.3, ly, 0.15); K.bin(lx - 3, lz - 2.6, ly); + W.addBox({ x: lx - 5.5 - Math.sin(0.15) * 0.7, z: lz - 2.2 - Math.cos(0.15) * 0.7, y0: ly, y1: ly + 2.3, hx: 1.75, hz: 0.06, yaw: 0.15, mat: 'glass', see: true, kind: 'shelter' }); + K.lamp(lx + 6, lz - 3, ly); K.tree('pine', lx - 10, lz - 6); K.scooter(lx + 7.5, lz + 1, 0.4, '#b8433a', ly); + // rock fall and sea stacks at the foot of the cliffs + [[250, 52, 2.2], [300, 78, 3.2], [345, 96, 4], [410, 60, 2.4], [520, 62, 2.6], [600, 66, 2.2], [760, 60, 2.8], [945, 62, 3], [1040, 104, 4.2], [1168, 86, 3.6], [1230, 44, 2.4], [1300, 30, 2.2], [1560, 46, 3], [1640, 98, 4.5], [-232, 70, 3], [-120, 86, 3.4], [96, 70, 2.6]].forEach(function (q) { + K.rocks(q[0], q[1], Math.max(W.terrainH(q[0], q[1]), -1.2), q[2], 4, { tall: 1.5 + M.hash2(q[0], q[1]) }); + }); + } + + // ---- the lemon terraces: pergolas of chestnut poles on the stepped slope, a farmhouse, a roadside stall + function buildTerraces() { + var i, n = new T.Vector3(); + var fy = PADS[PADS.length - 1].y, fx = 640, fz = -16; + K.occMark(fx, fz, 22, 22, 0, 0); + K.house(fx - 2, fz - 3, 11, 8, 0.1, { floors: 2, wall: '#efd9a0', shutter: '#3e6b52', roof: 'tile', base: fy, balc: 0, laundry: 1 }); + K.house(fx + 8, fz + 2, 5, 5, 0.1 + Math.PI / 2, { floors: 1, wall: '#ede2c6', roof: 'vault', base: fy, plain: true, noPlinth: true }); + K.crate(fx - 6, fz + 5, 0.2, 1, null, fy); K.crate(fx - 4.8, fz + 5.3, 0.6, 0.8, null, fy); K.box(fx - 2, fz + 4.4, fy, 0.3, '#e9c93a', 3); K.box(fx - 1.2, fz + 4.6, fy, 0.7, '#e9c93a', 2); + K.car(fx + 3, fz + 6.5, 1.3, '#7d8a5a', 'van', fy); K.tree('olive', fx - 9, fz + 7); K.tree('cypress', fx + 10, fz - 6); + K.pergola(fx + 1, fz + 3.2, 7, 3.2, fy, 0.1, { h: 2.4, lemons: true, noCol: true }); + // pergolas on the terrace treads: wherever a flat strip is wide enough + for (var z = 8; z > -200; z -= 9) for (var x = 566; x < 800; x += 12 + rnd() * 6) { + var xx = x + (rnd() - 0.5) * 5, zz = z + (rnd() - 0.5) * 4, h = W.terrainH(xx, zz); + if (h < 10 || terr(xx) < 0.5 || K.occAt(xx, zz) || LAND.onRoad(xx, zz, 5)) continue; + W.terrainN(xx, zz, n); if (n.y < 0.93) continue; + // line the pergola up with the terrace: along the contour + var e = 3, gx = W.terrainH(xx + e, zz) - W.terrainH(xx - e, zz), gz = W.terrainH(xx, zz + e) - W.terrainH(xx, zz - e), yaw = Math.atan2(gx, gz) + Math.PI / 2; + if (Math.abs(W.terrainH(xx + Math.sin(yaw) * 4, zz + Math.cos(yaw) * 4) - h) > 0.6 || Math.abs(W.terrainH(xx - Math.sin(yaw) * 4, zz - Math.cos(yaw) * 4) - h) > 0.6) continue; + var c = Math.cos(yaw), s = Math.sin(yaw); + // poles and a net roof of leaves, lemon trees under it + for (i = -1; i <= 1; i++) for (var j = -1; j <= 1; j += 2) B.geo('bark', B.geos.cyl6, xx + i * 3.6 * s + j * 1.3 * c, h, zz + i * 3.6 * c - j * 1.3 * s, 0, 0.12, 2.5, 0.12, C('#6d5a45'), { cls: 'detail' }); + B.box('bark', xx + 1.3 * c, h + 2.5, zz - 1.3 * s, 0.08, 0.08, 8, yaw, { col: C('#6d5f50'), cls: 'detail', ao: 0 }); B.box('bark', xx - 1.3 * c, h + 2.5, zz + 1.3 * s, 0.08, 0.08, 8, yaw, { col: C('#6d5f50'), cls: 'detail', ao: 0 }); + B.box('foliage', xx, h + 2.56, zz, 3.0, 0.06, 8.4, yaw, { col: C('#2f4a22'), cls: 'shell', ao: 0, bottom: true }); + for (i = -1; i <= 1; i++) { K.leaf(xx + i * 2.8 * s, h + 2.5, zz + i * 2.8 * c, 3.6, 1.2, 3.6, '#47712e'); K.leaf(xx + i * 2.8 * s + 0.6, h + 1.9, zz + i * 2.8 * c, 0.34, 0.34, 0.34, '#f2d23a'); K.leaf(xx + i * 2.8 * s - 0.5, h + 2.0, zz + i * 2.8 * c + 0.4, 0.34, 0.34, 0.34, '#f2d23a'); } + K.occMark(xx, zz, 4, 9, yaw, 0); + } + // the roadside stall selling lemons, with its sign + var sx = 664, sz = coast0(664) - OFF - 5.4, sy = roadY(664); + B.box('wood', sx, sy, sz, 4.2, 0.95, 1.2, 0, { col: C('#9a7a55'), cls: 'detail', collide: 'wood', cover: true, kind: 'stall' }); + for (i = 0; i < 5; i++) B.box('wood', sx - 1.6 + i * 0.8, sy + 0.95, sz, 0.7, 0.16, 1.0, 0, { col: C('#b99a6e'), cls: 'detail', ao: 0, topCol: C(i % 2 ? '#e9c93a' : '#f0d84a') }); + var sf = K.faceFrame(sx, sz, 1, 0, 0, 0.61, 0, 1); sf.fyaw = 0; var s6 = RP.MapTex.signUV(5); + K.fq('sign', sf, -1.3, 1.3, sy + 0.3, sy + 0.7, C('#ffffff'), 0.02, [s6[0], s6[1], s6[2], s6[1], s6[2], s6[3], s6[0], s6[3]]); + K.umbrella(sx, sz - 0.4, sy, 3, { r: 3.4 }); K.box(sx + 2.8, sz + 0.2, sy, 0.3, '#e9c93a', 3); + } + + // ---- the fjord: steps down from the road, fishermen's houses against the rock, boats on the pocket beach + function buildCove() { + var y = 2.3, i; + K.occMark(880, -53, 26, 24, 0, 0); + B.box('paving', 880.5, y - 0.2, -53, 25, 0.25, 22, 0, { col: C('#cfc8ba'), uvs: 3, cls: 'shell', collide: 'stone', kind: 'floor' }); + // houses at the back and along the east wall, built into the rock + K.house(872, -66, 8, 6, 0, { floors: 2, wall: '#f0e4c8', shutter: '#3a6a72', roof: 'vault', base: y + 0.05, noBack: true, laundry: 1, balc: 0 }); + K.house(881, -67, 7, 6, 0, { floors: 3, wall: '#e8b897', shutter: '#3e6b52', roof: 'flat', base: y + 0.05, noBack: true, shop: 9 }); + K.house(889.5, -66, 7, 6, 0, { floors: 2, wall: '#f4efe6', shutter: '#2f4f6e', roof: 'vault', base: y + 0.05, noBack: true }); + K.house(895, -54, 6, 8, -Math.PI / 2, { floors: 2, wall: '#efd9a0', shutter: '#6b4b33', roof: 'flat', base: y + 0.05, noBack: true, laundry: 1 }); + // a boat shed with an open arch, nets, fish boxes, a hauled-out row of boats, a bench, a lamp + B.box('rubble', 867.6, y, -58, 4, 3.4, 6, 0, { col: C('#c9bfad'), uvs: 2.4, cls: 'shell', collide: 'stone', kind: 'house', topMat: 'paving' }); + var bf = K.faceFrame(867.6, -58, 1, 0, 2, 0, 1, 0); K.fq('dark', bf, -1.6, 1.6, y, y + 2.2, C('#ffffff'), 0.03); var bp = K.fp(bf, 0, y + 2.2, 0.03); B.geo('dark', B.geos.halfDisc, bp.x, bp.y, bp.z, Math.PI / 2, 3.2, 1.6, 1, C('#ffffff'), { cls: 'flat' }); + [[874, -40.5, 0.1, '#f2efe8', 5], [878, -40, -0.05, '#2f6fa8', 4.5], [882, -40.4, 0.08, '#e9e2d0', 5], [886, -40, 0.0, '#c9473b', 4.5]].forEach(function (q) { K.boat(q[0], q[1], q[2], q[3], q[4], W.terrainH(q[0], q[1]) + 0.1, 0.2); }); + K.boat(879, -22, 0.2, '#f2efe8', 5); K.boat(883, -12, -0.3, '#2f6fa8', 4.5); + K.nets(876, -46, y, '#4f7d6a'); K.nets(884.5, -45.5, y, '#a8683a'); K.box(888, -47, y, 0.3, '#6f9aa8', 3); K.box(888.8, -47.4, y, 0.8, '#6f9aa8', 2); + K.crate(870.5, -47, 0.3, 1, null, y); K.crate(891, -59, 0.1, 0.9, '#7d8a8c', y); + K.bench(880, -62.6, y, 0); K.lamp(875, -62.5, y); K.lamp(892, -47, y); + K.cafeTable(884.5, -62, y, { chairs: 2 }); K.cafeTable(887, -61.2, y, { chairs: 2 }); K.umbrella(885.6, -61.4, y, 2); + // a rail along the outside of the cliff steps + var S = ROADS[7].pts; + for (i = 0; i < S.length - 1; i++) K.railing(S[i][0] + 2.25, S[i][1], S[i][2], S[i + 1][0] + 2.25, S[i + 1][1], S[i + 1][2]); + K.lamp(846.2, 12.6, 32); + } + + // ---- the bowl town (in the manner of Positano): church and beach at the bottom, houses stacked to the coast road + function buildBowlTown() { + var i, k, yS = 7.6, yB = 3.4; + PADS.filter(function (p) { return p.n === 'church' || p.n === 'prom'; }).forEach(function (p) { K.occMark((p.x0 + p.x1) / 2, (p.z0 + p.z1) / 2, p.x1 - p.x0, p.z1 - p.z0, 0, 0); }); + K.occMark(1458, -56, 18, 18, 0, 0); + // the church square and the promenade + B.box('paving', 1404, yS - 0.2, -30, 56, 0.2, 28, 0, { col: C('#e2dbcd'), uvs: 3, cls: 'shell', collide: 'stone', kind: 'floor' }); + B.box('tiles', 1388, yS - 0.195, -30, 8, 0.2, 8, Math.PI / 4, { col: C('#ffffff'), uvs: 2, cls: 'shell', noSides: true }); + B.box('paving', 1421, yB - 0.2, -3, 118, 0.2, 12, 0, { col: C('#d6cfc2'), uvs: 3, cls: 'shell', collide: 'stone', kind: 'floor' }); + // retaining wall between the square and the promenade, the steps down, a balustrade on top + K.wall(1376, -15.6, 1396.8, -15.6, yB, yS - yB, 0.8, '#d9cfbd', { mat: 'rubble', cmat: 'stone', uvs: 2.4, noCover: true }); + K.wall(1403.2, -15.6, 1432, -15.6, yB, yS - yB, 0.8, '#d9cfbd', { mat: 'rubble', cmat: 'stone', uvs: 2.4, noCover: true }); + K.stair(1400, -15.9, yS, 1400, -9.2, yB, 6, { base: yB - 1, sideMat: 'rubble' }); + K.balustrade(1376.4, -16.2, 1396.9, -16.2, yS); K.balustrade(1403.1, -16.2, 1431.6, -16.2, yS); + // Santa Maria-style church: nave east-west under a tiled gable roof, a white front to the square with pilasters and + // a band of painted tiles, a majolica dome on a drum over the crossing, a bell tower standing apart + var cx = 1414, cz = -31, cw = 26, cd = 15, ch = 10.5, wall = C('#f6efe0'), white = C('#ffffff'), cream = C('#fbf7ee'); + B.box('stucco', cx, yS, cz, cw, ch, cd, 0, { col: wall, uvs: 3, cls: 'shell', collide: 'plaster', kind: 'church', noTop: true }); + B.box('stucco', cx, yS, cz, cw, ch + 1.5, cd, 0, { col: wall, uvs: 3, cls: 'far', topCol: C('#c98a66') }); + var ev = yS + ch, rdg = ev + 3.2, rx0 = cx - cw / 2 - 0.4, rx1 = cx + cw / 2 + 0.4, zA = cz - cd / 2 - 0.5, zB = cz + cd / 2 + 0.5, rb = B.bucket('roof', cx, cz, 'shell'), rl = Math.hypot(3.2, cd / 2 + 0.5); + B.quad(rb, V3(rx0, ev, zB), V3(rx1, ev, zB), V3(rx1, rdg, cz), V3(rx0, rdg, cz), [0, 0, (rx1 - rx0) / 1.6, 0, (rx1 - rx0) / 1.6, rl / 1.6, 0, rl / 1.6], white); + B.quad(rb, V3(rx1, ev, zA), V3(rx0, ev, zA), V3(rx0, rdg, cz), V3(rx1, rdg, cz), [0, 0, (rx1 - rx0) / 1.6, 0, (rx1 - rx0) / 1.6, rl / 1.6, 0, rl / 1.6], white); + var gb = B.bucket('stucco', cx, cz, 'shell'); + B.tri(gb, V3(cx - cw / 2 - 0.02, ev, cz - cd / 2), V3(cx - cw / 2 - 0.02, ev, cz + cd / 2), V3(cx - cw / 2 - 0.02, rdg - 0.1, cz), [0, 0, 5, 0, 2.5, 1], wall); + B.tri(gb, V3(cx + cw / 2 + 0.02, ev, cz + cd / 2), V3(cx + cw / 2 + 0.02, ev, cz - cd / 2), V3(cx + cw / 2 + 0.02, rdg - 0.1, cz), [0, 0, 5, 0, 2.5, 1], wall); + var wf = K.faceFrame(cx, cz, 1, 0, -cw / 2, 0, -1, 0); wf.fyaw = -Math.PI / 2; + K.fq('stone', wf, -cd / 2 - 0.05, cd / 2 + 0.05, yS, yS + 0.9, C('#d9d0c0'), 0.07, null, 'shell'); + [-6.6, -2.7, 2.7, 6.6].forEach(function (u) { + K.fq('stucco', wf, u - 0.42, u + 0.42, yS + 0.9, ev - 1.5, cream, 0.12, null, 'detail'); + K.fq('stucco', wf, u - 0.58, u + 0.58, ev - 1.9, ev - 1.5, cream, 0.17, null, 'detail'); K.fq('stucco', wf, u - 0.55, u + 0.55, yS + 0.9, yS + 1.25, cream, 0.16, null, 'detail'); + }); + K.fq('tiles', wf, -7.2, 7.2, ev - 1.5, ev - 0.95, white, 0.1, [0, 0, 28.8, 0, 28.8, 1, 0, 1], 'detail'); + K.fq('stucco', wf, -7.6, 7.6, ev - 0.95, ev - 0.35, cream, 0.2, null, 'detail'); K.fq('stucco', wf, -7.8, 7.8, ev - 0.35, ev, cream, 0.3, null, 'detail'); + B.tri(B.bucket('stucco', cx - cw / 2, cz, 'detail'), V3(cx - cw / 2 - 0.2, ev + 0.25, cz - cd / 2 + 1.4), V3(cx - cw / 2 - 0.2, ev + 0.25, cz + cd / 2 - 1.4), V3(cx - cw / 2 - 0.2, rdg - 0.75, cz), [0, 0, 4, 0, 2, 1], cream); + var op = K.fp(wf, 0, ev + 1.15, 0.24); B.geo('dark', new T.CircleGeometry(0.55, 12), op.x, op.y, op.z, -Math.PI / 2, 1, 1, 1, white, { cls: 'flat' }); + // the door in a stone frame with its own little pediment, a round window over it, two arched niches + K.fq('dark', wf, -1.45, 1.45, yS, yS + 4.1, white, 0.03); K.fq('door', wf, -1.35, 1.35, yS, yS + 3.95, C('#4f6a52'), 0.05, [0, 0, 1, 0, 1, 1, 0, 1]); + K.fq('stone', wf, -1.85, -1.4, yS, yS + 4.2, C('#e9e2d2'), 0.16); K.fq('stone', wf, 1.4, 1.85, yS, yS + 4.2, C('#e9e2d2'), 0.16); K.fq('stone', wf, -2.05, 2.05, yS + 4.15, yS + 4.6, C('#e9e2d2'), 0.2); + B.tri(B.bucket('stone', cx - cw / 2, cz, 'detail'), V3(cx - cw / 2 - 0.2, yS + 4.6, cz - 2.05), V3(cx - cw / 2 - 0.2, yS + 4.6, cz + 2.05), V3(cx - cw / 2 - 0.2, yS + 5.5, cz), [0, 0, 2.7, 0, 1.35, 0.6], C('#e9e2d2')); + var rp = K.fp(wf, 0, yS + 7.2, 0.05); B.geo('window', new T.CircleGeometry(1.0, 14), rp.x, rp.y, rp.z, -Math.PI / 2, 1, 1, 1, white, { cls: 'flat' }); + var rr = K.fp(wf, 0, yS + 7.2, 0.04); B.geo('stone', new T.RingGeometry(1.0, 1.28, 16), rr.x, rr.y, rr.z, -Math.PI / 2, 1, 1, 1, C('#e9e2d2'), { cls: 'flat', uvs: 1.5 }); + [-4.65, 4.65].forEach(function (u) { K.fq('dark', wf, u - 0.6, u + 0.6, yS + 2.0, yS + 4.3, white, 0.03); var np = K.fp(wf, u, yS + 4.3, 0.03); B.geo('dark', B.geos.halfDisc, np.x, np.y, np.z, -Math.PI / 2, 1.2, 1.2, 1, white, { cls: 'flat' }); }); + for (i = 0; i < 4; i++) { [1, -1].forEach(function (sd) { var sfF = K.faceFrame(cx, cz, 1, 0, 0, sd * cd / 2, 0, sd); K.fq('window', sfF, -9 + i * 5 - 0.5, -9 + i * 5 + 0.5, yS + 6.0, yS + 8.4, white, 0.04, [0, 0, 1, 0, 1, 1, 0, 1]); var sq = K.fp(sfF, -9 + i * 5, yS + 8.4, 0.04); B.geo('window', B.geos.halfDisc, sq.x, sq.y, sq.z, sd > 0 ? 0 : Math.PI, 1, 1, 1, white, { cls: 'flat', vScale: 0.5 }); }); } + // the dome: an eight-sided drum with windows, the tiled dome, a lantern + var dx = cx + 6, dr = 5.4; + B.geo('stucco', new T.CylinderGeometry(dr, dr, 4.6, 8), dx, yS + ch + 1.5, cz, 0.39, 1, 1, 1, C('#f6efe0'), { cls: 'shell', uvs: 3 }); + for (i = 0; i < 8; i++) { var da = i * Math.PI / 4; B.box('dark', dx + Math.sin(da) * (dr * 0.924 + 0.02), yS + ch + 1.2, cz + Math.cos(da) * (dr * 0.924 + 0.02), 0.9, 1.9, 0.02, da, { cls: 'flat' }); } + B.geo('stucco', new T.CylinderGeometry(dr + 0.3, dr + 0.3, 0.3, 8), dx, yS + ch + 3.95, cz, 0.39, 1, 1, 1, C('#fbf7ee'), { cls: 'shell' }); + B.geo('majolica', B.geos.hemi, dx, yS + ch + 4.1, cz, 0, dr * 2, dr * 1.65, dr * 2, null, { uScale: 6, vScale: 2.4, cls: 'shell' }); + B.geo('stucco', B.geos.cyl8, dx, yS + ch + 4.1 + dr * 0.8, cz, 0, 1.3, 1.5, 1.3, C('#fbf7ee'), { cls: 'shell' }); + B.geo('majolica', B.geos.hemi8, dx, yS + ch + 5.6 + dr * 0.8, cz, 0, 1.5, 1.2, 1.5, null, { uScale: 2, vScale: 1, cls: 'shell' }); + B.box('majolica', dx, yS + ch + 0.4, cz, dr * 1.7, dr * 1.5, dr * 1.7, 0.39, { cls: 'far', uvs: 2 }); + // the bell tower on the west side of the square + var tx = 1384, tz = -41; + B.box('aged', tx, yS, tz, 4.6, 19, 4.6, 0, { col: C('#f3ead8'), uvs: 3, cls: 'shell', collide: 'plaster', kind: 'tower' }); + B.box('aged', tx, yS, tz, 4.6, 22, 4.6, 0, { col: C('#f3ead8'), uvs: 3, cls: 'far' }); + [6.5, 12.5, 18.6].forEach(function (h) { B.box('stucco', tx, yS + h, tz, 5.1, 0.35, 5.1, 0, { col: C('#fbf7ee'), cls: 'shell', ao: 0, uvs: 3 }); }); + for (k = 0; k < 4; k++) { var bF = K.faceFrame(tx, tz, 1, 0, k === 2 ? 2.3 : k === 3 ? -2.3 : 0, k === 0 ? 2.3 : k === 1 ? -2.3 : 0, k === 2 ? 1 : k === 3 ? -1 : 0, k === 0 ? 1 : k === 1 ? -1 : 0); K.fq('dark', bF, -0.7, 0.7, yS + 14, yS + 17, C('#ffffff'), 0.03); var bq = K.fp(bF, 0, yS + 17, 0.03); B.geo('dark', B.geos.halfDisc, bq.x, bq.y, bq.z, Math.atan2(bF.nx, bF.nz), 1.4, 1.4, 1, C('#ffffff'), { cls: 'flat' }); } + B.geo('stucco', B.geos.cyl8, tx, yS + 18.95, tz, 0, 3.4, 1.6, 3.4, C('#f3ead8'), { cls: 'shell' }); + B.geo('majolica', B.geos.hemi8, tx, yS + 20.5, tz, 0, 3.6, 2.6, 3.6, null, { uScale: 3, vScale: 1.5, cls: 'shell' }); + // the square: lamps, benches, pots, a café, bollards at the top of the steps + K.lamp(1380, -20, yS); K.lamp(1396, -40, yS); K.lamp(1428, -20, yS); + K.bench(1386, -19, yS, 0); K.bench(1392, -19, yS, 0); K.bin(1396, -19.5, yS); + [[1378, -24], [1378, -36], [1398, -22], [1398, -38]].forEach(function (p) { K.planter(p[0], yS, p[1], 0, { pot: true }); }); + for (i = 0; i < 3; i++) { K.cafeTable(1381 + i * 2.6, -34.5, yS, { chairs: 2 }); } + K.umbrella(1383.6, -35.4, yS, 0, { r: 3 }); + [1397.4, 1402.6].forEach(function (bxp) { K.bollard(bxp, -17.4, yS); }); + // the promenade: beach clubs, a row of shops under the square's wall, palms, benches + for (i = 0; i < 7; i++) K.tree('palm', 1372 + i * 17, -6.8, yB); + for (i = 0; i < 6; i++) K.lamp(1378 + i * 18, 1.6, yB); + for (i = 0; i < 5; i++) { K.bench(1380 + i * 20, 1.2, yB, 0); if (i % 2) K.bin(1383 + i * 20, 1.4, yB); } + K.house(1444, -13.5, 20, 7, 0, { floors: 2, wall: '#f6f1e8', shutter: '#3a6a72', roof: 'flat', base: yB, shop: 6, noBack: true, balc: 0.8, sides: 'party', frames: true }); + K.house(1463, -13.5, 14, 7, 0, { floors: 3, wall: '#eaa58c', shutter: '#3e6b52', roof: 'vault', base: yB, shop: 11, noBack: true, balc: 0.8, sides: 'party' }); + K.occMark(1451, -13.5, 36, 9, 0, 0); + for (i = 0; i < 6; i++) { K.cafeTable(1437 + i * 3.2, -7.4, yB, { chairs: 2 }); if (i % 2 === 0) K.umbrella(1438.5 + i * 3.2, -7.2, yB, 1, { r: 2.6 }); } + K.scooter(1470.5, -8.4, 1.5, '#c7d9d2', yB); K.scooter(1472, -8.5, 1.6, '#e8d9a8', yB); K.car(1368.5, -3, 0.05, '#e8e2cf', 'van', yB); + // low wall between promenade and sand, three gaps with steps + [[1364, 1388], [1392, 1418], [1422, 1448], [1452, 1478]].forEach(function (s) { B.box('rubble', (s[0] + s[1]) / 2, yB - 1.2, 3.3, s[1] - s[0], 1.9, 0.5, 0, { col: C('#d3c9b7'), uvs: 2, cls: 'shell', collide: 'stone', cover: true, kind: 'wall', topMat: 'stone' }); }); + [1390, 1420, 1450].forEach(function (sx) { K.stair(sx, 3.1, yB, sx, 6.2, W.terrainH(sx, 6.8) + 0.05, 3.6, { base: 0.3 }); }); + // the beach: rows of umbrellas in two colours (two lidos), loungers, boats hauled out in the middle, a rescue chair + for (var r = 0; r < 4; r++) for (i = 0; i < 24; i++) { + var x = 1370 + i * 4.4 + (r % 2) * 2.2, z = 8 + r * 3.6, ty = W.terrainH(x, z); + if (ty < 0.35 || Math.abs(x - 1420) < 9 || Math.abs(x - 1390) < 2.4 || Math.abs(x - 1450) < 2.4) continue; + var lido = x < 1420 ? 0 : 2; + K.umbrella(x, z, ty, lido, { r: 2.5 }); + K.lounger(x + 1, z + 0.5, W.terrainH(x + 1, z + 0.5), 0.05, lido ? '#9fb7c9' : '#f1c9a8'); K.lounger(x - 0.9, z + 0.5, W.terrainH(x - 0.9, z + 0.5), -0.05, lido ? '#9fb7c9' : '#f1c9a8'); + } + [[1414, 9, 0.1, '#f2efe8', 5], [1418, 9.6, -0.1, '#2f6fa8', 5], [1422, 9.2, 0.05, '#c9473b', 4.5], [1426, 9.8, 0.0, '#e9e2d0', 5], [1416, 14, 0.15, '#3a8b6f', 4.5], [1424, 14.4, -0.05, '#f2efe8', 5]].forEach(function (q) { K.boat(q[0], q[1], q[2], q[3], q[4], W.terrainH(q[0], q[1]) + 0.1, 0.2); }); + K.nets(1420, 6.6, null, '#4f7d6a'); K.nets(1411.5, 12, null, '#a8683a'); + B.box('wood', 1436, W.terrainH(1436, 15), 15, 1.2, 2.2, 1.2, 0, { col: C('#f2efe8'), cls: 'detail' }); B.box('paint', 1436, W.terrainH(1436, 15) + 2.2, 15, 1.5, 0.08, 1.5, 0, { col: C('#c9402e'), cls: 'detail', ao: 0 }); + // the ferry pier on the west side, boats moored off it + var py0 = 6, py1 = 56; + B.box('concrete', 1366, -6, (py0 + py1) / 2, 5.5, 7.7, py1 - py0, 0, { col: C('#cbc4b6'), uvs: 3, cls: 'shell', collide: 'stone', kind: 'mole', deck: true, topMat: 'paving' }); + for (i = 0; i < 5; i++) { K.bollard(1368.2, 14 + i * 9, 1.7, 'iron'); } + K.railing(1363.4, py0 + 4, 1.7, 1363.4, py1, 1.7); K.lamp(1366, 54, 1.7); K.nets(1365, 40, 1.7); K.crate(1364.6, 24, 0.2, 0.9, null, 1.7); + for (i = 0; i < 6; i++) K.boat(1374 + (i % 3) * 5, 30 + Math.floor(i / 3) * 12 + (i % 2) * 2, 0.2 * (i % 3) - 0.2, ['#f2efe8', '#2f6fa8', '#e9e2d0'][i % 3], 5 + (i % 2)); + for (i = 0; i < 5; i++) K.boat(1440 + i * 9, 44 + (i % 2) * 9, 1.2 + i * 0.3, ['#f2efe8', '#c9473b', '#e9e2d0', '#f2efe8', '#3a8b6f'][i], 6); + // a watchtower on the rocks west of the beach + var wx = 1338, wz = 20, wy = W.terrainH(wx, wz); + B.geo('rubble', new T.CylinderGeometry(3.4, 4.0, 12, 12), wx, wy + 4, wz, 0, 1, 1, 1, C('#cdbfa6'), { cls: 'shell', uvs: 2.4 }); + B.geo('rubble', new T.CylinderGeometry(3.9, 3.5, 1.2, 12), wx, wy + 10.6, wz, 0, 1, 1, 1, C('#c4b69c'), { cls: 'shell', uvs: 2.4 }); + B.box('rubble', wx, wy, wz, 6, 10, 6, 0, { col: C('#cdbfa6'), cls: 'far' }); + W.addBox({ x: wx, z: wz, y0: wy - 3, y1: wy + 11, hx: 3.2, hz: 3.2, mat: 'stone', kind: 'tower' }); + + // the piazzetta at the foot of the street: a fountain, a bar, parked scooters, the bus turn + var px = 1458, pz = -56, py = 20; + B.geo('basalt', new T.CylinderGeometry(9.4, 9.4, 0.3, 18), px, py - 0.12, pz, 0, 1, 1, 1, C('#cfcac2'), { cls: 'shell', uvs: 2.4 }); + B.geo('stone', new T.CylinderGeometry(1.3, 1.4, 0.7, 8), px + 2.5, py + 0.35, pz + 1.5, 0, 1, 1, 1, C('#e8e2d6'), { cls: 'shell', uvs: 1.5 }); + B.geo('water', new T.CylinderGeometry(1.12, 1.12, 0.04, 10), px + 2.5, py + 0.62, pz + 1.5, 0, 1, 1, 1, C('#ffffff'), { cls: 'flat' }); + B.geo('stone', B.geos.cyl8, px + 2.5, py + 0.6, pz + 1.5, 0, 0.36, 1.1, 0.36, C('#ddd6c8'), { cls: 'detail' }); + W.addBox({ x: px + 2.5, z: pz + 1.5, y0: py, y1: py + 0.75, hx: 1.2, hz: 1.2, mat: 'stone', cover: true, kind: 'fountain' }); + K.scooter(px - 5, pz + 4.6, 0.6, '#c7d9d2', py); K.scooter(px - 3.8, pz + 5.4, 0.7, '#b8433a', py); K.scooter(px - 2.5, pz + 6.1, 0.8, '#e8d9a8', py); + K.lamp(px + 6.5, pz - 3, py); K.lamp(px - 6.5, pz - 2, py); K.bench(px + 5.6, pz + 4.6, py, -2.2); K.bin(px - 7.2, pz + 2.5, py); + for (i = 0; i < 3; i++) { K.cafeTable(px + 2 + i * 2.4, pz - 5.6 + i * 1.2, py, { chairs: 2 }); } + K.umbrella(px + 4.4, pz - 5, py, 1, { r: 2.8 }); + + // houses: tight rows along the three legs of the street, then the whole bowl filled, stacked up the slope + var D = ROADS[8].pts; + K.frontage(D, ROADS[8].w, rnd, { palette: K.PASTEL, minF: 2, varF: 2, shops: 0.45, minW: 5.5, varW: 3.5, minD: 6 }); + K.frontage(COAST.pts.slice(ptIndex(1340), ptIndex(1570) + 1), COAST.w, rnd, { palette: K.PASTEL, minF: 2, varF: 2, shops: 0.2, minW: 6, varW: 4, minD: 6 }); + var laneRoofs = function (r) { var q = r(); return q < 0.4 ? 'flat' : q < 0.7 ? 'vault' : q < 0.9 ? 'dome' : 'tile'; }; + + for (k = 9; k <= 14; k++) K.frontage(ROADS[k].pts, ROADS[k].w, rnd, { palette: K.PASTEL, shops: k === 9 ? 0.6 : 0.2, minW: 5, varW: 3, minD: 5.5, minF: 2, varF: 2, roofs: laneRoofs, balc: 0.5 }); + K.fillSlope({ x0: 1262, x1: 1600, z0: -205, z1: -2, ok: function (xx, zz, h) { + var ax = Math.abs(xx - 1420); if (ax > 168) return false; + if (zz > -18 && ax < 66) return false; // the church, the square, the promenade + if (h < 4.5) return false; + return true; + }, core: function (xx, zz) { return Math.abs(xx - 1420) < 120; } }, rnd, { palette: K.PASTEL, rowStep: 5.6, minStep: 5.2, varStep: 2.5, minW: 5.5, varW: 5, minD: 5.5, varD: 3.5, floors: [2, 3], minNy: 0.36, maxH: 110, gap: 0.15, mark: 0.12, gaps: false, + faceTo: [1420, 30], facePull: 0.35, balc: 0.55, trees: 0.25, + roofs: function (r) { var q = r(); return q < 0.34 ? 'flat' : q < 0.62 ? 'vault' : q < 0.82 ? 'dome' : q < 0.92 ? 'tile' : 'flat'; } }); + // lamps and pots up the stair lanes, a rail on the steep ones + for (k = 9; k <= 14; k++) { + var Lp = ROADS[k].pts; + for (i = 0; i < Lp.length - 1; i++) { + var a = Lp[i], b = Lp[i + 1], mx = (a[0] + b[0]) / 2, mz = (a[1] + b[1]) / 2, dir = Math.atan2(b[0] - a[0], b[1] - a[1]), nx = Math.cos(dir), nz = -Math.sin(dir); + if (i % 2 === 0) K.lamp(a[0] + nx * 1.7, a[1] + nz * 1.7, null); + K.planter(mx - nx * 1.2, W.terrainH(mx - nx * 1.2, mz - nz * 1.2), mz - nz * 1.2, 0, { pot: true, hex: i % 2 ? '#c43d77' : '#3f6b2c' }); + } + } + D.forEach(function (p, q) { if (q % 2 === 0 && q < D.length - 1) { var n2 = D[q + 1], dir = Math.atan2(n2[0] - p[0], n2[1] - p[1]); K.lamp(p[0] + Math.cos(dir) * 3.1, p[1] - Math.sin(dir) * 3.1, null); } }); + } + + // ---- vegetation on the cliffs and hills + function buildNature() { + var area = (BOUNDS.x1 - BOUNDS.x0) * (BOUNDS.z1 - BOUNDS.z0), n = new T.Vector3(); + var tries = Math.round(area / 39); + for (var i = 0; i < tries; i++) { + var x = BOUNDS.x0 + 3 + rnd() * (BOUNDS.x1 - BOUNDS.x0 - 6), z = BOUNDS.z0 + 3 + rnd() * (BOUNDS.z1 - BOUNDS.z0 - 6); + var h = W.terrainH(x, z); if (h < 2) continue; + if (K.occAt(x, z) || LAND.onRoad(x, z, 1.5)) continue; + W.terrainN(x, z, n); if (n.y < 0.45) continue; + var r = rnd(), k = M.noise2(x * 0.02, z * 0.02); + if (k < 0.25) continue; + var te = x > 540 && x < 850 ? terr(x) : 0; + if (te > 0.4 && h > 9) { if (r < 0.3 && n.y > 0.9) K.tree(r < 0.22 ? 'lemon' : 'olive', x, z, h); continue; } + var open = x > 200 && Math.abs(x - 1420) > 175 && Math.abs(x - 880) > 30; // the wild coast: more scrub, fewer garden trees + if (open) K.tree(r < 0.035 ? 'pine' : r < 0.05 ? 'cypress' : r < 0.1 ? 'olive' : r < 0.13 ? 'agave' : 'scrub', x, z, h); + else K.tree(r < 0.05 ? 'pine' : r < 0.1 ? 'cypress' : r < 0.2 ? 'olive' : r < 0.24 && h < 60 ? 'lemon' : 'scrub', x, z, h); + } + } + + RP.maps.register({ + id: 'amalfi', name: 'Amalfi Coast', bounds: BOUNDS, + credit: 'Amalfi Coast map hand-built from public photos and general knowledge of the coast; no map data was downloaded.', + build: function () { + RP._random = RP._random || Math.random; + RP.map = { id: 'amalfi', spots: {} }; + var S = RP.map.spots; + // named places (missions, spawns, free roam) + S.marina = { x: 0, z: 16, y: 2.6, yaw: Math.PI }; + S.gate = { x: 0.5, z: 8, y: 2.6, yaw: Math.PI }; + S.piazza = { x: -3, z: -18, y: 5 }; + S.steps = { x: 19, z: -20, y: 9 }; + S.porch = { x: 30, z: -20, y: 13 }; + S.villaGate = { x: -136, z: 13, y: 24 }; + S.villaTerrace = { x: -168, z: 50, y: 24 }; + S.villaStudy = { x: -177, z: 22, y: 24 }; + S.lemons = { x: -150, z: -10, y: 16.5 }; + S.scalinataTop = { x: -128, z: -12, y: 16 }; + S.harbour = { x: 26, z: 28, y: 1.6 }; + S.tower = { x: 132, z: 40, y: 18 }; + S.mainStreet = { x: -9, z: -82, y: 9.4 }; + // the new coast + S.tunnel1 = { x: 335, z: 20, y: 29 }; + S.belvedere = { x: 466, z: 40, y: 33.8 }; + S.terraces = { x: 640, z: -16, y: 0 }; + S.coveBridge = { x: 880, z: 16, y: 32 }; + S.cove = { x: 880, z: -50, y: 2.3 }; + S.busStop = { x: 1012, z: 60, y: 38 }; + S.tunnel2 = { x: 1160, z: 14, y: 45 }; + S.bowlTop = { x: 1385, z: -146, y: 57.6 }; + S.piazzetta = { x: 1458, z: -56, y: 20 }; + S.churchSquare = { x: 1390, z: -28, y: 7.6 }; + S.bowlBeach = { x: 1420, z: 2, y: 3.4 }; + build(); + S.terraces.y = PADS[PADS.length - 1].y; + // where reinforcements arrive (out of sight of the player, see RP.Alert) + RP.map.spawns = [{ x: -92, z: 35 }, { x: 96, z: 28 }, { x: -12, z: -126 }, { x: 33, z: 62 }, { x: -127, z: 29 }, { x: -80, z: -20 }, { x: 56, z: -26 }, { x: -1, z: -176 }, { x: 150, z: 39.5 }, { x: -150, z: -10 }, + { x: 236, z: coast0(236) - OFF }, { x: 384, z: coast0(384) - OFF }, { x: 506, z: coast0(506) - OFF }, { x: 590, z: coast0(590) - OFF }, { x: 710, z: coast0(710) - OFF }, { x: 800, z: coast0(800) - OFF }, { x: 934, z: coast0(934) - OFF }, + { x: 1060, z: coast0(1060) - OFF }, { x: 1206, z: coast0(1206) - OFF }, { x: 880, z: -56 }, { x: 1300, z: -40 }, { x: 1420, z: -152 }, { x: 1540, z: -96 }, { x: 1458, z: -56 }, { x: 1400, z: -104 }, { x: 1390, z: -28 }, { x: 1470, z: -2 }]; + S.ledger = RP.map.spots.ledger || S.ledger; + // cars and launches to take (RP.Vehicles, main.js): [type, x, z, yaw] + RP.map.vehicles = [['city', -16, 15.5, Math.PI / 2], ['spider', 30, 17.5, Math.PI / 2], ['boat', 30, 52, Math.PI / 2], ['boat', -178, 91, Math.PI / 2], + ['city', 470, 33.6, Math.PI / 2 + 0.1], ['boat', 880, -2, 0], ['city', 1019, 58.6, Math.PI / 2], ['spider', 1393, -149.6, 1.72], ['city', 1457, -61.6, 1.4], ['boat', 1360.6, 40, 0]]; + RP.map.minimap = K.minimap(LAND, { squares: [[-19, -38, 12, -2], [1376, -44, 1432, -16]] }); + RP.map.onRoad = LAND.onRoad; + // the driving line east from Amalfi's waterfront: the coast road, then the bowl town's street down to its piazzetta + var descent = ROADS.filter(function (r) { return r.name === 'descent'; })[0]; + // [x, z, road height, road width] + RP.map.driveLine = coastPts.filter(function (p) { return p[0] <= 1380; }).map(function (p) { return [p[0], p[1], p[2], 7]; }) + .concat((descent ? descent.pts : []).map(function (p) { return [p[0], p[1], p[2], descent.w]; })); + return RP.map; + } + }); +})(); diff --git a/e63334287a3deaa3/blacktie/js/maptex.js b/e63334287a3deaa3/blacktie/js/maptex.js new file mode 100644 index 00000000..ccb2eaf2 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/maptex.js @@ -0,0 +1,610 @@ +/* + * Map materials (RP.MapTex): the town's surfaces as one texture array and one material, and the terrain material. + * + * Every static surface a map builds (walls, paving, roofs, doors, signs, railings...) is drawn with RP.mat.town. Its + * colour texture is a WebGL2 texture array: one code-painted layer per surface kind (LAYERS below). A vertex carries a + * material id (RP.MT.), and the shader looks up that id's layer, roughness, metalness and glow in a small table + * (RP.MTDEF), so a whole chunk of town is one draw call. Normal maps are a second array made from each layer's + * brightness (Medium and High). Low uses 256 px layers, the others 512. + * + * The terrain material (RP.mat.land) reads its normals and its tint from two textures made from the heightfield (one + * texel per 2 m cell), so the three terrain resolutions shade identically and only the silhouette changes; on top it + * paints limestone (triplanar, with strata and stains on steep faces) and scrub on the ledges. + * + * To add a surface: add a painter to PAINT and its name to LAYERS, then a def(...) line. Painters draw on a canvas + * whose bottom edge is v = 0; tiling layers must wrap at the edges (use tile() to draw things that cross them). + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M; + var X = RP.MapTex = {}; + X.glowU = { value: 1 }; // how brightly lamps glow: set from the time of day (RP.Sea.atmos) + var LAYERS = ['white', 'stucco', 'aged', 'facade', 'ashlar', 'rubble', 'basalt', 'slabs', 'asphalt', 'coppi', 'majolica', 'wood', + 'door', 'window', 'louvre', 'rail', 'signs', 'awning', 'rock', 'concrete', 'duomo', 'tiles', 'shop', 'facade2']; + X.LAYERS = LAYERS; + // invented shop names for the sign layer (2 columns x 8 rows); RP.MapTex.SIGNS[i] -> uv rectangle via X.signUV(i) + X.SIGNS = ['CAFFÈ CAMPANILE', 'PASTICCERIA TRE LIMONI', 'TRATTORIA SCOGLIO ROSSO', 'CERAMICHE ONDA BLU', 'GELATERIA NUVOLA', 'ALIMENTARI DONNA ILDE', + 'SANDALI DEL VICOLO', 'LINO E SALE', 'FORNO VECCHIO', 'PESCHERIA L\'ANCORA', 'ALBERGO GINESTRA', 'RISTORANTE IL GOZZO', 'ENOTECA SETTE SCALINI', + 'CARTA E MARE · LIBRI', 'LIDO MEDUSA', 'TABACCHI']; + X.signUV = function (i) { var c = i % 2, r = Math.floor(i / 2) % 8; return [c * 0.5, 1 - (r + 1) / 8, c * 0.5 + 0.5, 1 - r / 8]; }; + + // ------------------------------------------------------------------ material table + var MT = RP.MT = {}, DEF = RP.MTDEF = {}, nId = 0; + // flags: 1 cut-out (alpha test), 2 gloss from alpha (glass in window textures), +4 macro colour variation + function def(name, layer, rough, metal, o) { + o = o || {}; + DEF[name] = { id: nId, layer: LAYERS.indexOf(layer), rough: rough, metal: metal || 0, emis: o.emis || 0, flags: o.flags || 0, ns: o.ns == null ? 1 : o.ns, + macro: o.macro || 0, tint: o.tint ? (o.tint.isColor ? o.tint : RP.col(o.tint)) : null, cls: o.cls || null, dbl: !!o.dbl }; + MT[name] = nId++; + } + def('stucco', 'stucco', 0.92, 0, { macro: 1, ns: 0.7 }); + def('aged', 'aged', 0.93, 0, { macro: 1, ns: 0.7 }); + def('facade', 'facade', 0.9, 0, { macro: 1, ns: 0.6 }); + def('facade2', 'facade2', 0.9, 0, { macro: 1, ns: 0.6 }); + def('stone', 'ashlar', 0.85, 0, { macro: 0.6 }); + def('rubble', 'rubble', 0.95, 0, { macro: 1, ns: 1.4 }); + def('paving', 'slabs', 0.78, 0, { macro: 1 }); + def('basalt', 'basalt', 0.66, 0, { macro: 1, ns: 1.2 }); + def('asphalt', 'asphalt', 0.9, 0, { macro: 1, ns: 0.6 }); + def('roof', 'coppi', 0.8, 0, { macro: 0.7, ns: 1.3 }); + def('majolica', 'majolica', 0.2, 0.05, { ns: 0.4 }); + def('wood', 'wood', 0.75, 0, { ns: 0.8 }); + def('paint', 'white', 0.55, 0, { ns: 0 }); + def('metal', 'white', 0.35, 0.85, { ns: 0 }); + def('glass', 'white', 0.05, 0.9, { ns: 0, tint: '#1d2a33', cls: 'flat' }); + def('dark', 'white', 1, 0, { ns: 0, tint: '#16120f', cls: 'flat' }); + def('sand', 'stucco', 0.95, 0, { macro: 1 }); + def('fabric', 'white', 0.9, 0, { ns: 0, dbl: true }); + def('lamp', 'white', 1, 0, { ns: 0, emis: 5.5, tint: new T.Color(1, 0.78, 0.44), cls: 'flat' }); + def('gold', 'white', 0.3, 1, { ns: 0, tint: '#c9a24a' }); + def('door', 'door', 0.6, 0, { ns: 0.8, cls: 'flat' }); + def('window', 'window', 0.5, 0, { flags: 2, ns: 0.3, cls: 'flat' }); + def('louvre', 'louvre', 0.6, 0, { ns: 1, cls: 'flat' }); + def('rail', 'rail', 0.5, 0.5, { flags: 1, ns: 0, cls: 'flat', dbl: true }); + def('sign', 'signs', 0.6, 0, { ns: 0, cls: 'flat' }); + def('awning', 'awning', 0.9, 0, { ns: 0, dbl: true }); + def('rock', 'rock', 0.95, 0, { macro: 1, ns: 1.5 }); + def('concrete', 'concrete', 0.9, 0, { macro: 1, ns: 0.7 }); + def('duomo', 'duomo', 0.8, 0, { ns: 0.5 }); + def('tiles', 'tiles', 0.28, 0, { ns: 0.3 }); + def('shop', 'shop', 0.4, 0, { flags: 2, ns: 0.3, cls: 'flat' }); + def('water', 'white', 0.04, 0.6, { ns: 0, tint: '#2f8f96', cls: 'flat' }); + def('bark', 'stucco', 0.95, 0, { ns: 1.5 }); + def('foliage', 'white', 1, 0, { ns: 0 }); + + // ------------------------------------------------------------------ painting helpers + function canvas(n) { var c = document.createElement('canvas'); c.width = c.height = n; return c; } + // tileable value noise, summed octaves + function tnoise(n, period, seed) { + var g = new Float32Array(period * period), rnd = M.rng(seed), out = new Float32Array(n * n); + for (var i = 0; i < g.length; i++) g[i] = rnd(); + for (var y = 0; y < n; y++) for (var x = 0; x < n; x++) { + var fx = x / n * period, fy = y / n * period, xi = Math.floor(fx), yi = Math.floor(fy), tx = fx - xi, ty = fy - yi; + tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty); + var a = g[(yi % period) * period + xi % period], b = g[(yi % period) * period + (xi + 1) % period]; + var c = g[((yi + 1) % period) * period + xi % period], d = g[((yi + 1) % period) * period + (xi + 1) % period]; + out[y * n + x] = (a + (b - a) * tx) * (1 - ty) + (c + (d - c) * tx) * ty; + } + return out; + } + function fbm(n, seed, periods, amps) { + var out = new Float32Array(n * n); + for (var k = 0; k < periods.length; k++) { var t = tnoise(n, periods[k], seed + k * 17); for (var i = 0; i < out.length; i++) out[i] += t[i] * amps[k]; } + return out; + } + function paint(c, fn) { + var n = c.width, x = c.getContext('2d'), img = x.createImageData(n, n), d = img.data; + for (var j = 0; j < n; j++) for (var i = 0; i < n; i++) { var o = (j * n + i) * 4, v = fn(i, j); d[o] = v[0]; d[o + 1] = v[1]; d[o + 2] = v[2]; d[o + 3] = 255; } + x.putImageData(img, 0, 0); return x; + } + // draw something nine times, shifted by the canvas size, so strokes that leave one edge come back on the other + function tile(x, n, fn) { for (var dy = -1; dy <= 1; dy++) for (var dx = -1; dx <= 1; dx++) { x.save(); x.translate(dx * n, dy * n); fn(); x.restore(); } } + function grey(v, a) { v = Math.round(M.clamp(v, 0, 255)); return 'rgba(' + v + ',' + v + ',' + v + ',' + (a == null ? 1 : a) + ')'; } + function rgb(r, g, b, a) { return 'rgba(' + Math.round(r) + ',' + Math.round(g) + ',' + Math.round(b) + ',' + (a == null ? 1 : a) + ')'; } + + // ------------------------------------------------------------------ the layers + var PAINT = {}; + PAINT.white = function (c) { var x = c.getContext('2d'); x.fillStyle = '#fff'; x.fillRect(0, 0, c.width, c.width); }; + function stuccoBase(c, seed, contrast) { + var n = c.width, h = fbm(n, seed, [3, 7, 19, 53], [0.4, 0.3, 0.2, 0.1]), rnd = M.rng(seed * 7 + 1); + var x = paint(c, function (i, j) { var v = h[j * n + i], g = 226 + (v - 0.5) * contrast + (M.hash2(i * 1.3, j * 1.7) - 0.5) * 9; return [g + 5, g + 2, g - 5]; }); + // hairline cracks + x.lineWidth = Math.max(1, n / 512); + for (var k = 0; k < 7; k++) { + var px = rnd() * n, py = rnd() * n, a = rnd() * 6.28; + x.strokeStyle = grey(120, 0.28); + tile(x, n, function () { + x.beginPath(); x.moveTo(px, py); var qx = px, qy = py, aa = a; + for (var s = 0; s < 14; s++) { aa += (rnd() - 0.5) * 0.9; qx += Math.cos(aa) * n * 0.025; qy += Math.sin(aa) * n * 0.025 + n * 0.006; x.lineTo(qx, qy); } + x.stroke(); + }); + } + return x; + } + PAINT.stucco = function (c) { stuccoBase(c, 11, 44); }; + // old lime plaster: rain streaks, flaked patches showing the darker render underneath, repaint patches + function agedBase(c, seed) { + var n = c.width, x = stuccoBase(c, seed, 60), rnd = M.rng(seed * 3 + 5), s = n / 512; + for (var k = 0; k < 12; k++) { + var sx = rnd() * n, sy = rnd() * n, len = n * (0.18 + rnd() * 0.5), w = (3 + rnd() * 12) * s, dark = rnd() < 0.75; + tile(x, n, function () { + var g = x.createLinearGradient(0, sy, 0, sy + len); + g.addColorStop(0, dark ? 'rgba(92,84,70,0.17)' : 'rgba(255,252,244,0.2)'); g.addColorStop(1, dark ? 'rgba(92,84,70,0)' : 'rgba(255,252,244,0)'); + x.fillStyle = g; x.fillRect(sx, sy, w, len); + }); + } + for (k = 0; k < 2; k++) { // a patch or two where the plaster has gone thin + var fx = rnd() * n, fy = rnd() * n, fr = n * (0.05 + rnd() * 0.05); + tile(x, n, function () { + var g2 = x.createRadialGradient(fx, fy, fr * 0.2, fx, fy, fr); g2.addColorStop(0, 'rgba(176,160,138,0.3)'); g2.addColorStop(1, 'rgba(176,160,138,0)'); + x.fillStyle = g2; x.save(); x.translate(fx, fy); x.scale(1.6, 0.8); x.translate(-fx, -fy); x.beginPath(); x.arc(fx, fy, fr, 0, 6.283); x.fill(); x.restore(); + }); + } + for (k = 0; k < 3; k++) { // repaint patches + var rx = rnd() * n, ry = rnd() * n; + tile(x, n, function () { x.fillStyle = 'rgba(255,250,240,0.16)'; x.fillRect(rx, ry, n * (0.1 + rnd() * 0.2), n * (0.08 + rnd() * 0.15)); }); + } + return x; + } + PAINT.aged = function (c) { agedBase(c, 12); }; + // One bay of a house front painted flat: plaster with a shuttered window. Houses map one tile per bay and storey + // (3.2 m), so their real windows (drawn only near the camera) sit exactly over these. Window: 0.316 of the tile + // wide, from 1.0 to 2.5 m up; each shutter 0.17 of the tile. + X.BAY = { hw: 0.158, sh: 0.17, y0: 1.0 / 3.2, y1: 2.5 / 3.2 }; + function facadeLayer(c, seed, variant) { + var n = c.width, x = agedBase(c, seed), Bz = X.BAY; + var wl = n * (0.5 - Bz.hw), wr = n * (0.5 + Bz.hw), yt = n * (1 - Bz.y1), yb = n * (1 - Bz.y0), sw = n * Bz.sh; + // stain under the sill, soft shadow under the lintel + var g = x.createLinearGradient(0, yb, 0, yb + n * 0.22); g.addColorStop(0, 'rgba(90,82,70,0.22)'); g.addColorStop(1, 'rgba(90,82,70,0)'); + x.fillStyle = g; x.fillRect(wl - n * 0.02, yb, (wr - wl) + n * 0.04, n * 0.22); + x.fillStyle = '#20262b'; x.fillRect(wl, yt, wr - wl, yb - yt); + x.fillStyle = 'rgba(190,200,205,0.35)'; x.fillRect(wl + n * 0.012, yt + n * 0.012, (wr - wl) / 2 - n * 0.018, yb - yt - n * 0.024); // a pane catching the sky + x.strokeStyle = '#e9e4d8'; x.lineWidth = Math.max(1.5, n / 170); x.strokeRect(wl, yt, wr - wl, yb - yt); + x.beginPath(); x.moveTo(n / 2, yt); x.lineTo(n / 2, yb); x.stroke(); + // shutters, open against the wall (variant 1: closed over the window) + var sc = variant ? '#7c9584' : '#6f8a7a'; + function shutter(x0, w) { + x.fillStyle = sc; x.fillRect(x0, yt, w, yb - yt); + x.strokeStyle = 'rgba(30,45,38,0.35)'; x.lineWidth = Math.max(1, n / 512); + for (var yy = yt + 3; yy < yb; yy += Math.max(3, n / 110)) { x.beginPath(); x.moveTo(x0 + 2, yy); x.lineTo(x0 + w - 2, yy); x.stroke(); } + x.strokeStyle = 'rgba(30,45,38,0.5)'; x.strokeRect(x0, yt, w, yb - yt); + } + if (variant) { shutter(wl, (wr - wl) / 2); shutter(n / 2, (wr - wl) / 2); } + else { shutter(wl - sw - n * 0.012, sw); shutter(wr + n * 0.012, sw); } + x.fillStyle = '#e4ded0'; x.fillRect(wl - n * 0.03, yb, (wr - wl) + n * 0.06, n * 0.035); // sill + x.fillStyle = 'rgba(40,36,30,0.3)'; x.fillRect(wl - n * 0.03, yb + n * 0.035, (wr - wl) + n * 0.06, n * 0.012); + } + PAINT.facade = function (c) { facadeLayer(c, 13, 0); }; + PAINT.facade2 = function (c) { facadeLayer(c, 14, 1); }; + // ashlar: coursed limestone blocks (the cathedral, quays, kerbs) + PAINT.ashlar = function (c) { + var n = c.width, h = fbm(n, 23, [8, 32, 90], [0.5, 0.35, 0.15]), rows = 4, cols = 3; + paint(c, function (i, j) { + var row = Math.floor(j / (n / rows)), off = (row % 2) * n / (cols * 2), bx = (i + off) % (n / cols), by = j % (n / rows); + var e = Math.min(bx, n / cols - bx, by, n / rows - by), m = e < n / 256, v = h[j * n + i], tone = M.hash2(row, Math.floor((i + off) / (n / cols)) % cols); + var g = m ? 138 : 196 + (v - 0.5) * 44 + (tone - 0.5) * 30 - (e < n / 90 ? 10 : 0); + return [g + 10, g + 5, g - 7]; + }); + }; + // rubble: dry-stone and rough masonry (retaining walls, parapets, base courses): uneven courses of rough blocks + PAINT.rubble = function (c) { + var n = c.width, rnd = M.rng(31), h = fbm(n, 37, [9, 30, 90], [0.45, 0.35, 0.2]), wob = fbm(n, 39, [6, 14], [0.6, 0.4]); + // courses: 7 rows of differing height; each row cut into blocks of differing length + var rows = [], y = 0, R = 7, hs = []; + for (var i = 0; i < R; i++) hs.push(0.7 + rnd() * 0.7); + var sum = hs.reduce(function (a, b) { return a + b; }, 0); + for (i = 0; i < R; i++) { var cuts = [], p = rnd() * 0.1; while (p < 1) { cuts.push(p); p += 0.09 + rnd() * 0.13; } rows.push({ y0: y, y1: y + hs[i] / sum, cuts: cuts }); y += hs[i] / sum; } + paint(c, function (px, py) { + var w = (wob[py * n + px] - 0.5) * 0.035, u = px / n + w, v = py / n + (wob[px * n + py] - 0.5) * 0.03; + v -= Math.floor(v); u -= Math.floor(u); + var row = rows[0], ri = 0; for (var q = 0; q < R; q++) if (v >= rows[q].y0) { row = rows[q]; ri = q; } + var e = Math.min(v - row.y0, row.y1 - v), k = 0; + for (q = 0; q < row.cuts.length; q++) { var dc = Math.abs(u - row.cuts[q]); dc = Math.min(dc, 1 - dc); e = Math.min(e, dc); if (u >= row.cuts[q]) k = q; } + var tone = M.hash2(ri * 7.3 + 1, k * 3.1 + 2), nz = h[py * n + px]; + if (e < 0.005) return [122, 113, 99]; + var g = 150 + tone * 62 + (nz - 0.5) * 60 - (e < 0.016 ? 24 : 0), warm = M.hash2(k * 1.7, ri * 5.9); + return [g + 10 + warm * 12, g + 3, g - 12 - warm * 6]; + }); + }; + // basalt setts (lanes, the main street): dark volcanic blocks in running bond, worn lighter in the middle + PAINT.basalt = function (c) { + var n = c.width, h = fbm(n, 41, [12, 48, 128], [0.45, 0.35, 0.2]), rows = 8, cols = 4; + paint(c, function (i, j) { + var row = Math.floor(j / (n / rows)), off = (row % 2) * n / (cols * 2), bx = (i + off) % (n / cols), by = j % (n / rows); + var e = Math.min(bx, n / cols - bx, by, n / rows - by), v = h[j * n + i], tone = M.hash2(row * 3.1, Math.floor((i + off) / (n / cols)) % cols + 0.7); + if (e < n / 220) return [52, 50, 48]; + var g = 104 + (v - 0.5) * 34 + (tone - 0.5) * 34 + Math.min(e / (n / 40), 1) * 8; + return [g + 5, g + 1, g - 6]; + }); + }; + // big pale limestone slabs (piazzas, quays), random lengths + PAINT.slabs = function (c) { + var n = c.width, h = fbm(n, 47, [5, 21, 70], [0.45, 0.35, 0.2]), rows = 4, cuts = []; + var rnd = M.rng(49); + for (var r = 0; r < rows; r++) { var l = [0], p = 0; while (p < 0.8) { p += 0.2 + rnd() * 0.22; if (p < 0.92) l.push(p); } cuts.push(l); } + paint(c, function (i, j) { + var row = Math.floor(j / (n / rows)), by = j % (n / rows), u = i / n, l = cuts[row], k = 0, e = 1; + for (var q = 0; q < l.length; q++) { if (u >= l[q]) k = q; e = Math.min(e, Math.abs(u - l[q]), Math.abs(u - l[q] - 1), Math.abs(u - l[q] + 1)); } + e = Math.min(e * n, by, n / rows - by); + var v = h[j * n + i], tone = M.hash2(row * 5.3, k * 1.9); + if (e < n / 300) return [96, 90, 82]; + var g = 166 + (v - 0.5) * 44 + (tone - 0.5) * 26 - (e < n / 110 ? 9 : 0); + return [g + 5, g, g - 9]; + }); + }; + PAINT.asphalt = function (c) { + var n = c.width, h = fbm(n, 53, [4, 16, 64, 128], [0.3, 0.3, 0.25, 0.15]), rnd = M.rng(57); + var x = paint(c, function (i, j) { var v = h[j * n + i], sp = M.hash2(i * 0.77, j * 1.31); var g = 84 + (v - 0.5) * 30 + (sp > 0.93 ? 26 : sp < 0.06 ? -14 : 0); return [g + 5, g + 1, g - 5]; }); + x.strokeStyle = 'rgba(30,30,32,0.5)'; x.lineWidth = Math.max(1, n / 400); + for (var k = 0; k < 5; k++) { + var px = rnd() * n, py = rnd() * n, a = rnd() * 6.28; + tile(x, n, function () { x.beginPath(); x.moveTo(px, py); var qx = px, qy = py, aa = a; for (var s = 0; s < 12; s++) { aa += (rnd() - 0.5) * 1.1; qx += Math.cos(aa) * n * 0.03; qy += Math.sin(aa) * n * 0.03; x.lineTo(qx, qy); } x.stroke(); }); + } + }; + // terracotta barrel tiles (coppi) running down the slope (v) + PAINT.coppi = function (c) { + var n = c.width, h = fbm(n, 61, [9, 40], [0.6, 0.4]), cols = 8, rows = 6; + paint(c, function (i, j) { + var u = (i / n * cols) % 1, col = Math.floor(i / n * cols), ridge = Math.sin(u * Math.PI); + var course = ((j / n * rows) + (col % 2) * 0.5) % 1, row = Math.floor((j / n * rows) + (col % 2) * 0.5); + var t = M.hash2(col * 1.7, row * 2.3), v = h[j * n + i]; + var g = (0.5 + ridge * 0.5) * (course < 0.07 ? 0.62 : 1 - course * 0.12) * (0.86 + v * 0.28); + var lich = M.hash2(col * 9.1, row * 4.7) > 0.86 ? 0.82 : 1; + return [(176 + t * 52) * g * lich, (96 + t * 30) * g, (62 + t * 18) * g]; + }); + }; + // majolica fish-scale tiles: yellow, green and blue glaze in zigzag bands (the church domes) + PAINT.majolica = function (c) { + var n = c.width, rows = 12, cols = 8, COLS = [[236, 190, 44], [34, 122, 78], [236, 190, 44], [40, 92, 150]]; + paint(c, function (i, j) { + var v = j / n * rows, r = Math.floor(v), fv = v - r, u = i / n * cols + (r % 2) * 0.5, cu = Math.floor(u), fu = u - cu; + // a scale is a disc hanging from the row above; where two discs miss, the scale of the row above shows + var dx = fu - 0.5, dy = fv - 0.15, in1 = dx * dx + dy * dy * 0.55 < 0.26; + var rr = in1 ? r : r - 1, cc = in1 ? cu : Math.floor(u + 0.5); + var k = ((rr + Math.floor(cc / 2) * 0) % 4 + 4) % 4, zig = (Math.floor((cc + (rr % 2 ? 0 : 0)) / 1) + rr) % 4; + var col = COLS[((zig % 4) + 4) % 4]; + var edge = in1 ? Math.abs(Math.sqrt(dx * dx + dy * dy * 0.55) - 0.5) < 0.035 : false; + var sh = edge ? 0.5 : 0.82 + 0.3 * (1 - fv) + (M.hash2(cc * 3.3, rr * 7.7) - 0.5) * 0.14; + return [col[0] * sh, col[1] * sh, col[2] * sh]; + }); + }; + PAINT.wood = function (c) { + var n = c.width, h = fbm(n, 71, [2, 40, 120], [0.3, 0.5, 0.2]); + paint(c, function (i, j) { var v = h[(j * 5 % n) * n + i], plank = (j % (n / 8)) < n / 220 ? 0.5 : 1; var g = (150 + v * 70) * plank * (0.9 + 0.2 * M.hash2(Math.floor(j / (n / 8)), 3)); return [g, g * 0.82, g * 0.63]; }); + }; + // a panelled double door in a stone frame (pale, so the vertex colour paints it brown, green or blue) + PAINT.door = function (c) { + var n = c.width, x = c.getContext('2d'), h = fbm(n, 73, [3, 60], [0.4, 0.6]); + paint(c, function (i, j) { var v = h[j * n + (i * 7 % n)]; var g = 196 + (v - 0.5) * 46; return [g, g, g]; }); + x.strokeStyle = grey(70, 0.9); x.lineWidth = n / 64; x.strokeRect(n / 128, n / 128, n - n / 64, n - n / 64); + x.fillStyle = grey(40, 0.9); x.fillRect(n / 2 - n / 200, 0, n / 100, n); + for (var s = 0; s < 2; s++) for (var p = 0; p < 3; p++) { + var px = n * (0.07 + s * 0.5), pw = n * 0.36, py = n * (0.06 + p * 0.31), ph = n * (p === 2 ? 0.27 : 0.27); + x.fillStyle = grey(120, 0.55); x.fillRect(px, py, pw, ph); + x.fillStyle = grey(232, 0.9); x.fillRect(px + n * 0.02, py + n * 0.02, pw - n * 0.04, ph - n * 0.04); + x.strokeStyle = grey(90, 0.6); x.lineWidth = n / 256; x.strokeRect(px + n * 0.045, py + n * 0.045, pw - n * 0.09, ph - n * 0.09); + } + x.fillStyle = '#b89a52'; x.beginPath(); x.arc(n * 0.455, n * 0.52, n * 0.018, 0, 6.283); x.arc(n * 0.545, n * 0.52, n * 0.018, 0, 6.283); x.fill(); + }; + // a casement window: white frame, six panes of dark glass (alpha 0 = glass for the shader), a curtain behind one side + PAINT.window = function (c, mask) { + var n = c.width, x = c.getContext('2d'), m = mask.getContext('2d'); + x.fillStyle = '#ebe6da'; x.fillRect(0, 0, n, n); + m.fillStyle = '#000'; m.fillRect(0, 0, n, n); + var f = n * 0.07, mw = n * 0.035; + for (var s = 0; s < 2; s++) for (var p = 0; p < 3; p++) { + var px = f + s * (n / 2 - f + mw / 2) + (s ? mw / 2 : 0), pw = n / 2 - f - mw, py = f + p * ((n - 2 * f) / 3) + (p ? mw / 2 : 0), ph = (n - 2 * f) / 3 - (p ? mw / 2 : 0) - (p < 2 ? mw / 2 : 0); + var g = x.createLinearGradient(0, py, 0, py + ph); g.addColorStop(0, '#2b3a45'); g.addColorStop(1, '#141b20'); + x.fillStyle = g; x.fillRect(px, py, pw, ph); + m.fillStyle = '#fff'; m.fillRect(px, py, pw, ph); + } + // curtain + x.fillStyle = 'rgba(232,226,210,0.5)'; x.beginPath(); x.moveTo(f, f); x.lineTo(n * 0.36, f); x.quadraticCurveTo(n * 0.2, n * 0.5, n * 0.14, n - f); x.lineTo(f, n - f); x.fill(); + m.fillStyle = 'rgba(0,0,0,0.6)'; m.beginPath(); m.moveTo(f, f); m.lineTo(n * 0.36, f); m.quadraticCurveTo(n * 0.2, n * 0.5, n * 0.14, n - f); m.lineTo(f, n - f); m.fill(); + x.fillStyle = 'rgba(0,0,0,0.25)'; x.fillRect(0, 0, n, f * 0.5); // shadow of the lintel + }; + // louvred shutter leaf (pale: tinted by the vertex colour) + PAINT.louvre = function (c) { + var n = c.width, x = c.getContext('2d'); + x.fillStyle = grey(215); x.fillRect(0, 0, n, n); + var slat = n / 22; + for (var y = n * 0.06; y < n * 0.94; y += slat) { + var g = x.createLinearGradient(0, y, 0, y + slat); g.addColorStop(0, grey(238)); g.addColorStop(0.7, grey(170)); g.addColorStop(1, grey(96)); + x.fillStyle = g; x.fillRect(n * 0.1, y, n * 0.8, slat); + } + x.fillStyle = grey(205); x.fillRect(n * 0.1, n * 0.47, n * 0.8, n * 0.06); + x.strokeStyle = grey(110, 0.8); x.lineWidth = n / 128; x.strokeRect(n / 256, n / 256, n - n / 128, n - n / 128); + }; + // wrought-iron railing, cut out: 1 tile = 1 m wide and 1 m tall + PAINT.rail = function (c, mask) { + var n = c.width, x = c.getContext('2d'), m = mask.getContext('2d'); + x.fillStyle = '#242220'; x.fillRect(0, 0, n, n); + m.fillStyle = '#000'; m.fillRect(0, 0, n, n); m.fillStyle = '#fff'; m.strokeStyle = '#fff'; + m.fillRect(0, 0, n, n * 0.06); m.fillRect(0, n * 0.84, n, n * 0.045); m.fillRect(0, n * 0.955, n, n * 0.045); + var bars = 8; + for (var i = 0; i < bars; i++) { + var bx = (i + 0.5) / bars * n; + m.fillRect(bx - n * 0.012, n * 0.05, n * 0.024, n * 0.92); + if (i % 2 === 0) { m.lineWidth = n * 0.016; m.beginPath(); m.ellipse(bx, n * 0.47, n * 0.045, n * 0.12, 0, 0, 6.283); m.stroke(); } + } + }; + PAINT.signs = function (c) { + var n = c.width, x = c.getContext('2d'), cw = n / 2, ch = n / 8; + var BG = ['#efe6cf', '#23402f', '#6e1f24', '#1f3350', '#d9b45a', '#f3efe6', '#2b2a28', '#8a3b22'], FG = ['#3a2c1c', '#f0e6c8', '#f3e4c0', '#f2ead8', '#3a2412', '#1f3a5c', '#e9c66a', '#f6ead2']; + X.SIGNS.forEach(function (name, i) { + var cx = (i % 2) * cw, cy = Math.floor(i / 2) * ch, k = (i * 3 + (i >> 1)) % BG.length; + x.fillStyle = BG[k]; x.fillRect(cx, cy, cw, ch); + x.strokeStyle = FG[k]; x.lineWidth = Math.max(1, n / 300); x.strokeRect(cx + ch * 0.1, cy + ch * 0.1, cw - ch * 0.2, ch - ch * 0.2); + x.fillStyle = FG[k]; x.textAlign = 'center'; x.textBaseline = 'middle'; + var fs = ch * 0.44; x.font = '600 ' + fs + 'px Georgia, "Times New Roman", serif'; + var w = x.measureText(name).width, max = cw - ch * 0.5; if (w > max) { fs *= max / w; x.font = '600 ' + fs + 'px Georgia, "Times New Roman", serif'; } + x.fillText(name, cx + cw / 2, cy + ch / 2 + fs * 0.04); + }); + }; + // awnings and umbrellas: four striped cloths side by side (terracotta, green, navy, yellow against cream) + PAINT.awning = function (c) { + var n = c.width, x = c.getContext('2d'), CO = ['#b9502f', '#3f7350', '#2c4f7c', '#e2b23a']; + for (var q = 0; q < 4; q++) for (var s = 0; s < 8; s++) { + x.fillStyle = s % 2 ? '#f4eede' : CO[q]; x.fillRect((q * 8 + s) * n / 32, 0, n / 32 + 1, n); + } + var g = x.createLinearGradient(0, 0, 0, n); g.addColorStop(0, 'rgba(0,0,0,0.0)'); g.addColorStop(1, 'rgba(60,40,20,0.18)'); + x.fillStyle = g; x.fillRect(0, 0, n, n); + }; + PAINT.rock = function (c) { + var n = c.width, h = fbm(n, 83, [3, 8, 21, 55], [0.45, 0.3, 0.17, 0.08]); + paint(c, function (i, j) { var v = h[j * n + i], band = Math.sin(j / n * 37.7 + v * 6) * 0.5 + 0.5; var g = 168 + (v - 0.5) * 96 + band * 20 - (band < 0.08 ? 40 : 0); return [g + 8, g + 2, g - 10]; }); + }; + PAINT.concrete = function (c) { + var n = c.width, h = fbm(n, 89, [4, 18, 70], [0.5, 0.3, 0.2]), rnd = M.rng(91); + var x = paint(c, function (i, j) { var v = h[j * n + i]; var g = 168 + (v - 0.5) * 46 - ((j % (n / 4)) < n / 256 ? 26 : 0) + (M.hash2(i * 1.9, j * 0.7) - 0.5) * 10; return [g + 2, g, g - 4]; }); + for (var k = 0; k < 9; k++) { + var sx = rnd() * n, sy = rnd() * n, len = n * (0.2 + rnd() * 0.4), w = (4 + rnd() * 14) * n / 512; + tile(x, n, function () { var g = x.createLinearGradient(0, sy, 0, sy + len); g.addColorStop(0, 'rgba(70,66,58,0.3)'); g.addColorStop(1, 'rgba(70,66,58,0)'); x.fillStyle = g; x.fillRect(sx, sy, w, len); }); + } + }; + // the cathedral's striped front above the porch: bands of pale and grey stone, a row of interlaced blind arches, + // three windows; the top 36 % is the gable with its gold mosaic field (mapped onto a triangle) + PAINT.duomo = function (c) { + var n = c.width, x = c.getContext('2d'), h = fbm(n, 97, [6, 30, 90], [0.4, 0.4, 0.2]); + paint(c, function (i, j) { + var v = h[j * n + i], band = Math.floor(j / (n / 26)) % 2; + var g = (band ? 150 : 232) + (v - 0.5) * 30; return band ? [g, g - 4, g - 12] : [g + 4, g, g - 10]; + }); + var gy = n * 0.36; // gable above this line (canvas y from the top) + // gable: gold field, a deep-blue roundel, a frame + x.fillStyle = '#f1ead9'; x.fillRect(0, 0, n, gy); + x.beginPath(); x.moveTo(n * 0.06, gy - n * 0.02); x.lineTo(n * 0.5, n * 0.04); x.lineTo(n * 0.94, gy - n * 0.02); x.closePath(); + var gg = x.createLinearGradient(0, 0, 0, gy); gg.addColorStop(0, '#e2bd5c'); gg.addColorStop(1, '#b98a2c'); x.fillStyle = gg; x.fill(); + x.strokeStyle = '#7a5a22'; x.lineWidth = n / 90; x.stroke(); + for (var k = 0; k < 220; k++) { x.fillStyle = k % 3 ? 'rgba(255,236,160,0.35)' : 'rgba(120,80,20,0.25)'; var tx = n * (0.1 + M.hash2(k, 1) * 0.8), ty = n * 0.06 + M.hash2(k, 2) * (gy - n * 0.1); if (Math.abs(tx - n / 2) < (ty - n * 0.04) * 1.35) x.fillRect(tx, ty, n / 90, n / 90); } + x.fillStyle = '#efe6cf'; x.beginPath(); x.arc(n / 2, gy * 0.62, n * 0.075, 0, 6.283); x.fill(); + x.strokeStyle = '#f0d98a'; x.lineWidth = n / 120; x.stroke(); + // a plain rosette in the roundel: petals round a boss (no ring of stars, which would read as a real emblem) + x.fillStyle = '#b9482f'; for (k = 0; k < 6; k++) { var a = k / 6 * 6.283; x.beginPath(); x.ellipse(n / 2 + Math.cos(a) * n * 0.034, gy * 0.62 + Math.sin(a) * n * 0.034, n * 0.026, n * 0.012, a, 0, 6.283); x.fill(); } + x.fillStyle = '#e9d28a'; x.beginPath(); x.arc(n / 2, gy * 0.62, n * 0.014, 0, 6.283); x.fill(); + // cornice between gable and front + x.fillStyle = '#efe9da'; x.fillRect(0, gy - n * 0.02, n, n * 0.035); x.fillStyle = 'rgba(40,30,20,0.35)'; x.fillRect(0, gy + n * 0.015, n, n * 0.012); + // blind arcade: slim columns and interlaced pointed arches + var ay0 = gy + n * 0.07, ay1 = gy + n * 0.36, na = 11, aw = n * 0.86 / na; + for (k = 0; k <= na; k++) { + var ax = n * 0.07 + k * aw; + x.fillStyle = '#f4efe2'; x.fillRect(ax - n * 0.008, ay0 + n * 0.09, n * 0.016, ay1 - ay0 - n * 0.09); + x.fillStyle = 'rgba(30,24,18,0.3)'; x.fillRect(ax + n * 0.008, ay0 + n * 0.09, n * 0.006, ay1 - ay0 - n * 0.09); + } + x.strokeStyle = '#f4efe2'; x.lineWidth = n * 0.014; + for (k = 0; k < na - 1; k++) { var bx = n * 0.07 + k * aw; x.beginPath(); x.moveTo(bx, ay0 + n * 0.1); x.quadraticCurveTo(bx + aw * 0.2, ay0 - n * 0.02, bx + aw, ay0 + n * 0.005); x.quadraticCurveTo(bx + aw * 1.8, ay0 - n * 0.02, bx + aw * 2, ay0 + n * 0.1); x.stroke(); } + // three tall windows + for (k = -1; k <= 1; k++) { + var wx = n / 2 + k * n * 0.27, wy = gy + n * 0.42, ww = n * (k ? 0.07 : 0.1), wh = n * 0.17; + x.fillStyle = '#efe9da'; x.fillRect(wx - ww / 2 - n * 0.012, wy - n * 0.012 - ww / 2, ww + n * 0.024, wh + n * 0.024 + ww / 2); + x.fillStyle = '#1b2228'; x.beginPath(); x.moveTo(wx - ww / 2, wy + wh); x.lineTo(wx - ww / 2, wy); x.arc(wx, wy, ww / 2, Math.PI, 0); x.lineTo(wx + ww / 2, wy + wh); x.fill(); + } + }; + // riggiole: hand-painted blue, yellow and white tiles (stair risers, benches, the dome drum) + PAINT.tiles = function (c) { + var n = c.width, x = c.getContext('2d'), k = 4, s = n / k; + x.fillStyle = '#f2efe4'; x.fillRect(0, 0, n, n); + for (var j = 0; j < k; j++) for (var i = 0; i < k; i++) { + var cx = i * s + s / 2, cy = j * s + s / 2; + x.fillStyle = '#2a5a9a'; x.beginPath(); x.moveTo(cx, cy - s * 0.42); x.lineTo(cx + s * 0.42, cy); x.lineTo(cx, cy + s * 0.42); x.lineTo(cx - s * 0.42, cy); x.fill(); + x.fillStyle = '#e8b93a'; x.beginPath(); x.arc(cx, cy, s * 0.17, 0, 6.283); x.fill(); + x.fillStyle = '#f2efe4'; x.beginPath(); x.arc(cx, cy, s * 0.07, 0, 6.283); x.fill(); + x.fillStyle = '#3f8a5e'; for (var q = 0; q < 4; q++) { x.beginPath(); x.arc(i * s + (q % 2) * s, j * s + (q >> 1) * s, s * 0.1, 0, 6.283); x.fill(); } + x.strokeStyle = 'rgba(120,112,96,0.7)'; x.lineWidth = Math.max(1, n / 300); x.strokeRect(i * s, j * s, s, s); + } + }; + // a shop front: dark wood frame, big glass with goods as soft shapes behind it, a stall-riser at the bottom + PAINT.shop = function (c, mask) { + var n = c.width, x = c.getContext('2d'), m = mask.getContext('2d'), rnd = M.rng(101); + x.fillStyle = '#d9d2c2'; x.fillRect(0, 0, n, n); m.fillStyle = '#000'; m.fillRect(0, 0, n, n); + var gx = n * 0.07, gy = n * 0.08, gw = n * 0.86, gh = n * 0.74; + var g = x.createLinearGradient(0, gy, 0, gy + gh); g.addColorStop(0, '#3a4a55'); g.addColorStop(0.5, '#1c242a'); g.addColorStop(1, '#2a2622'); + x.fillStyle = g; x.fillRect(gx, gy, gw, gh); + for (var k = 0; k < 14; k++) { // goods on shelves + x.fillStyle = ['rgba(232,190,70,0.75)', 'rgba(210,90,60,0.7)', 'rgba(240,236,220,0.7)', 'rgba(70,130,150,0.7)'][k % 4]; + var sx = gx + gw * (0.06 + (k % 7) * 0.13), sy = gy + gh * (k < 7 ? 0.5 : 0.78); + x.beginPath(); x.ellipse(sx, sy, gw * 0.04, gh * (0.05 + rnd() * 0.06), 0, 0, 6.283); x.fill(); + } + x.fillStyle = 'rgba(220,200,160,0.5)'; x.fillRect(gx, gy + gh * 0.58, gw, gh * 0.015); x.fillRect(gx, gy + gh * 0.86, gw, gh * 0.015); + m.fillStyle = '#fff'; m.fillRect(gx, gy, gw, gh); + x.fillStyle = '#d9d2c2'; x.fillRect(n * 0.5 - n * 0.012, gy, n * 0.024, gh); m.fillStyle = '#000'; m.fillRect(n * 0.5 - n * 0.012, gy, n * 0.024, gh); + x.fillStyle = 'rgba(0,0,0,0.3)'; x.fillRect(gx, gy, gw, n * 0.03); + x.strokeStyle = 'rgba(60,50,40,0.6)'; x.lineWidth = n / 128; x.strokeRect(gx, gy, gw, gh); + x.fillStyle = 'rgba(80,70,60,0.35)'; x.fillRect(n * 0.04, gy + gh + n * 0.03, n * 0.92, n * 0.1); + }; + + // ------------------------------------------------------------------ build the arrays and the materials + X.build = function () { + if (RP.mat.town) return; + var R = RP.R, low = R.qname === 'low', high = R.qname === 'high'; + var N = low ? 256 : 512, NN = low ? 0 : high ? 512 : 256, L = LAYERS.length; + var data = new Uint8Array(N * N * 4 * L), ndata = NN ? new Uint8Array(NN * NN * 4 * L) : null; + var nsOf = {}; for (var k in DEF) { var d = DEF[k]; nsOf[d.layer] = Math.max(nsOf[d.layer] || 0, d.ns); } + X.canvases = {}; + for (var l = 0; l < L; l++) { + var c = canvas(N), mask = canvas(N), name = LAYERS[l]; + PAINT[name](c, mask); + if (RP.test) X.canvases[name] = c; + var px = c.getContext('2d').getImageData(0, 0, N, N).data, usesMask = PAINT[name].length > 1, mk = usesMask ? mask.getContext('2d').getImageData(0, 0, N, N).data : null; + var cut = name === 'rail', off = l * N * N * 4; + for (var j = 0; j < N; j++) { + var src = (N - 1 - j) * N * 4, dst = off + j * N * 4; // flip rows: v = 0 is the bottom of the canvas + for (var i = 0; i < N * 4; i += 4) { + data[dst + i] = px[src + i]; data[dst + i + 1] = px[src + i + 1]; data[dst + i + 2] = px[src + i + 2]; + data[dst + i + 3] = mk ? (cut ? mk[src + i] : 255 - mk[src + i]) : 255; + } + } + if (ndata && nsOf[l] > 0) { + // normals from brightness (joints and cracks are dark, so they read as recessed) + var s = N / NN, lum = new Float32Array(NN * NN), o; + for (j = 0; j < NN; j++) for (i = 0; i < NN; i++) { o = off + ((j * s) * N + i * s) * 4; lum[j * NN + i] = (data[o] * 0.3 + data[o + 1] * 0.59 + data[o + 2] * 0.11) / 255; } + var no = l * NN * NN * 4, st = 2.2 * (NN / 256); + for (j = 0; j < NN; j++) for (i = 0; i < NN; i++) { + var hl = lum[j * NN + (i + NN - 1) % NN], hr = lum[j * NN + (i + 1) % NN], hd = lum[((j + NN - 1) % NN) * NN + i], hu = lum[((j + 1) % NN) * NN + i]; + var nx = (hl - hr) * st, ny = (hd - hu) * st, il = 1 / Math.sqrt(nx * nx + ny * ny + 1); + o = no + (j * NN + i) * 4; ndata[o] = (nx * il * 0.5 + 0.5) * 255; ndata[o + 1] = (ny * il * 0.5 + 0.5) * 255; ndata[o + 2] = il * 255; ndata[o + 3] = 255; + } + } else if (ndata) { var n0 = l * NN * NN * 4; for (i = 0; i < NN * NN * 4; i += 4) { ndata[n0 + i] = 128; ndata[n0 + i + 1] = 128; ndata[n0 + i + 2] = 255; ndata[n0 + i + 3] = 255; } } + } + function arr(d, n, srgb) { + var t = new T.DataArrayTexture(d, n, n, L); + t.format = T.RGBAFormat; t.type = T.UnsignedByteType; t.wrapS = t.wrapT = T.RepeatWrapping; + t.minFilter = T.LinearMipmapLinearFilter; t.magFilter = T.LinearFilter; t.generateMipmaps = true; t.anisotropy = low ? 2 : 4; + if (srgb) t.encoding = T.sRGBEncoding; + t.needsUpdate = true; return t; + } + var tArr = X.tArr = arr(data, N, true), tArrN = ndata ? arr(ndata, NN, false) : null; + var props = [], props2 = []; + for (var q = 0; q < 40; q++) { props.push(new T.Vector4(0, 1, 0, 0)); props2.push(new T.Vector4(0, 0, 0, 0)); } + for (k in DEF) { d = DEF[k]; props[d.id].set(d.layer, d.rough, d.metal, d.emis); props2[d.id].set(d.flags, d.ns, d.macro, 0); } + + var town = new T.MeshStandardMaterial({ roughness: 1, metalness: 0 }); + if (tArrN) town.defines = Object.assign({}, town.defines, { TOWN_NORMALS: '' }); + town.onBeforeCompile = function (sh) { + sh.uniforms.tArr = { value: tArr }; sh.uniforms.tArrN = { value: tArrN }; sh.uniforms.uProps = { value: props }; sh.uniforms.uProps2 = { value: props2 }; sh.uniforms.uGlow = X.glowU; + sh.vertexShader = 'attribute vec4 aCol; varying vec3 vCol; varying float vMt; varying vec2 vUvm; varying vec3 vWP;\n' + sh.vertexShader + .replace('#include ', '#include \n vCol = aCol.rgb * aCol.rgb; vMt = aCol.a * 255.0 + 0.5; vUvm = uv; vWP = (modelMatrix * vec4(transformed, 1.0)).xyz;'); + sh.fragmentShader = [ + 'uniform highp sampler2DArray tArr; uniform vec4 uProps[40]; uniform vec4 uProps2[40]; uniform float uGlow;', + '#ifdef TOWN_NORMALS', 'uniform highp sampler2DArray tArrN;', '#endif', + 'varying vec3 vCol; varying float vMt; varying vec2 vUvm; varying vec3 vWP;', + 'float tHash(vec2 p){ return fract(sin(dot(p, vec2(127.1,311.7)))*43758.5453); }', + 'float tNoise(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*f); return mix(mix(tHash(i), tHash(i+vec2(1.,0.)), f.x), mix(tHash(i+vec2(0.,1.)), tHash(i+vec2(1.,1.)), f.x), f.y); }', + 'float tRough = 1.0; float tMetal = 0.0; float tEmis = 0.0; vec4 tP = vec4(0.0); vec4 tP2 = vec4(0.0);' + ].join('\n') + '\n' + sh.fragmentShader + .replace('#include ', [ + 'int tMi = int(vMt); tP = uProps[tMi]; tP2 = uProps2[tMi];', + 'vec4 tTx = texture(tArr, vec3(vUvm, tP.x));', + 'if (tP2.x == 1.0 && tTx.a < 0.5) discard;', + 'float tGl = tP2.x == 2.0 ? 1.0 - tTx.a : 0.0;', + 'tRough = mix(tP.y, 0.06, tGl); tMetal = mix(tP.z, 0.9, tGl); tEmis = tP.w;', + // macro variation: slow drifts of tone across walls and paving so the tiling never reads + 'float tMac = 1.0;', + 'if (tP2.z > 0.0) { vec2 mp = vWP.xz * 0.045 + vWP.y * vec2(0.071, 0.043); float mn = tNoise(mp) * 0.6 + tNoise(mp * 3.7 + 11.0) * 0.4; tMac = 1.0 + (mn - 0.5) * 0.34 * tP2.z; }', + 'diffuseColor.rgb *= tTx.rgb * vCol * tMac;' + ].join('\n')) + .replace('#include ', 'float roughnessFactor = tRough;') + .replace('#include ', 'float metalnessFactor = tMetal;') + .replace('#include ', [ + '#include ', + '#ifdef TOWN_NORMALS', + 'if (tP2.y > 0.0) {', + ' vec3 tN = texture(tArrN, vec3(vUvm, tP.x)).xyz * 2.0 - 1.0; tN.xy *= tP2.y;', + ' vec3 q0 = dFdx(-vViewPosition), q1 = dFdy(-vViewPosition); vec2 st0 = dFdx(vUvm), st1 = dFdy(vUvm);', + ' vec3 q1p = cross(q1, normal), q0p = cross(normal, q0);', + ' vec3 tT = q1p * st0.x + q0p * st1.x, tB = q1p * st0.y + q0p * st1.y;', + ' float tDet = max(dot(tT, tT), dot(tB, tB)); float tSc = tDet == 0.0 ? 0.0 : inversesqrt(tDet);', + ' normal = normalize(tT * (tN.x * tSc) + tB * (tN.y * tSc) + normal * tN.z);', + '}', + '#endif' + ].join('\n')) + .replace('#include ', '#include \n totalEmissiveRadiance += diffuseColor.rgb * tEmis * uGlow;'); + }; + town.customProgramCacheKey = function () { return 'town' + (tArrN ? 'N' : ''); }; + RP.mat.town = town; + + // ---- the terrain + var land = new T.MeshStandardMaterial({ roughness: 0.95, map: RP.tex.rock, normalMap: low ? null : RP.tex.rockN }), LOW = !!low; + X.landU = { tLandN: { value: null }, tLandC: { value: null }, tScrub: { value: RP.tex.ground }, uLB: { value: new T.Vector4(0, 0, 1, 1) } }; + land.onBeforeCompile = function (sh) { + for (var u in X.landU) sh.uniforms[u] = X.landU[u]; + sh.vertexShader = 'attribute vec4 aCol; varying vec3 vWP; varying vec4 vVC; varying vec3 vVN;\n' + sh.vertexShader + .replace('#include ', '#include \n vWP = (modelMatrix * vec4(transformed, 1.0)).xyz; vVC = aCol; vVN = normal;'); + sh.fragmentShader = [ + 'uniform sampler2D tLandN; uniform sampler2D tLandC; uniform sampler2D tScrub; uniform vec4 uLB;', + 'varying vec3 vWP; varying vec4 vVC; varying vec3 vVN;', + 'float lHash(vec2 p){ return fract(sin(dot(p, vec2(127.1,311.7)))*43758.5453); }', + 'float lNoise(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*f); return mix(mix(lHash(i), lHash(i+vec2(1.,0.)), f.x), mix(lHash(i+vec2(0.,1.)), lHash(i+vec2(1.,1.)), f.x), f.y); }', + 'vec3 lWN = vec3(0.0, 1.0, 0.0);' + ].join('\n') + '\n' + sh.fragmentShader + .replace('#include ', [ + 'vec2 luv = (vWP.xz - uLB.xy) / uLB.zw;', + 'float inB = step(0.0, luv.x) * step(luv.x, 1.0) * step(0.0, luv.y) * step(luv.y, 1.0) * (1.0 - step(0.99, vVC.a));', // alpha 1: a mesh that brings its own normals and tint (tunnel lids) + 'vec4 lc = texture2D(tLandC, luv); vec3 lnn = texture2D(tLandN, luv).xyz * 2.0 - 1.0;', + 'lWN = normalize(mix(normalize(vVN), lnn, inB));', + 'vec3 lTint = mix(vVC.rgb * vVC.rgb, lc.rgb, inB) * 2.0; float lVeg = mix(vVC.a > 0.99 ? 0.6 : vVC.a, lc.a, inB);', + 'float slp = 1.0 - lWN.y;', + 'vec3 bw = pow(abs(lWN), vec3(4.0)); bw /= (bw.x + bw.y + bw.z);', + 'vec3 tx = texture2D(map, vWP.zy * 0.11).rgb, ty = texture2D(map, vWP.xz * 0.09).rgb, tz = texture2D(map, vWP.xy * 0.11).rgb;', + 'vec3 tri = tx * bw.x + ty * bw.y + tz * bw.z;', + 'float big = lNoise(vWP.xz * 0.011) * 0.6 + lNoise(vWP.xz * 0.037 + 7.0) * 0.4;', + 'float steep = smoothstep(0.26, 0.48, slp + (tri.g - 0.3) * 0.3);', + // limestone: beds a couple of metres thick, each its own tone, a dark seam between them, ochre and grey stains + 'float sy = vWP.y * 0.4 + (tri.r - 0.3) * 2.2 + big * 3.0 + sin(vWP.x * 0.021 + vWP.z * 0.017) * 1.2;', + 'float seam = 1.0 - smoothstep(0.0, 0.16, abs(fract(sy) - 0.5));', + 'float bed = lHash(vec2(floor(sy + 0.5), 3.7));', + // fine grain, triplanar like the rest (a top-down lookup smeared into streaks down the cliffs) + 'float fineD = texture2D(map, vWP.zy * 0.61).g * bw.x + texture2D(map, vWP.xz * 0.61).g * bw.y + texture2D(map, vWP.xy * 0.61).g * bw.z;', + 'vec3 rock = vec3(0.19, 0.172, 0.142) * (0.25 + 2.4 * tri) * (0.88 + 0.24 * bed) * (0.62 + 1.2 * fineD);', + 'rock *= 1.0 - 0.3 * seam * smoothstep(0.42, 0.7, slp);', + // close up: a third, finer octave (60 cm) so a cliff you stand against has grit and pits, not a blur + 'float camD = length(vWP - cameraPosition), nearK = 1.0 - smoothstep(6.0, 30.0, camD);', + LOW ? '' : 'float det = texture2D(map, vWP.zy * 1.7).b * bw.x + texture2D(map, vWP.xz * 1.7).b * bw.y + texture2D(map, vWP.xy * 1.7).b * bw.z;', + LOW ? '' : 'rock *= 1.0 + clamp((det - 0.58) * 2.6, -0.35, 0.35) * nearK;', + 'float streak = lNoise(vec2(dot(vWP.xz, vec2(0.8, 0.6)) * 0.33, vWP.y * 0.035 + 3.0));', + 'rock = mix(rock, rock * vec3(0.48, 0.45, 0.42), smoothstep(0.5, 0.8, streak) * 0.7);', + 'rock = mix(rock, rock * vec3(1.25, 0.96, 0.66), smoothstep(0.55, 0.9, lNoise(vWP.xz * 0.043 + vWP.y * 0.09)) * 0.6);', + // the ground between the crags: bare earth and scree where little grows, macchia and dry grass elsewhere + 'vec3 sc = texture2D(tScrub, vWP.xz * 0.19).rgb; float pat = lNoise(vWP.xz * 0.13 + 2.0);', + 'vec3 earth = vec3(0.2, 0.172, 0.128) * (0.45 + 1.7 * tri.g) * (0.85 + 0.3 * pat) * (0.62 + 1.2 * fineD);', + 'vec3 vegc = mix(vec3(0.058, 0.082, 0.036), vec3(0.155, 0.15, 0.068), smoothstep(0.3, 0.85, big * 0.75 + pat * 0.35 + (sc.g - 0.2) * 0.8)) * (0.5 + 2.6 * sc.g);', + 'float vm = smoothstep(0.1, 0.45, pat * 0.55 + lVeg * 0.95 - 0.3);', + 'vec3 ground = mix(earth, vegc, vm);', + 'diffuseColor.rgb *= mix(ground, rock, steep) * lTint;' + ].join('\n')) + .replace('#include ', [ + 'vec3 lwn = lWN;', + '#ifdef USE_NORMALMAP', + ' vec3 nmA = texture2D(normalMap, vWP.zy*0.11).xyz*2.0-1.0; vec3 nmB = texture2D(normalMap, vWP.xz*0.09).xyz*2.0-1.0; vec3 nmC = texture2D(normalMap, vWP.xy*0.11).xyz*2.0-1.0;', + ' vec3 bwn = pow(abs(lWN), vec3(4.0)); bwn /= (bwn.x+bwn.y+bwn.z);', + ' vec3 nfA = texture2D(normalMap, vWP.zy*0.61).xyz*2.0-1.0; vec3 nfB = texture2D(normalMap, vWP.xz*0.61).xyz*2.0-1.0; vec3 nfC = texture2D(normalMap, vWP.xy*0.61).xyz*2.0-1.0;', + ' float nk = 1.0 - smoothstep(8.0, 40.0, length(vWP - cameraPosition));', + ' lwn = normalize(lWN + (vec3(0.0, nmA.y, nmA.x)*bwn.x + vec3(nmB.x, 0.0, nmB.y)*bwn.y + vec3(nmC.x, nmC.y, 0.0)*bwn.z) * 0.55', + ' + (vec3(0.0, nfA.y, nfA.x)*bwn.x + vec3(nfB.x, 0.0, nfB.y)*bwn.y + vec3(nfC.x, nfC.y, 0.0)*bwn.z) * 0.6 * nk);', + '#endif', + 'normal = normalize((viewMatrix * vec4(lwn, 0.0)).xyz);' + ].join('\n')); + }; + land.customProgramCacheKey = function () { return 'land3' + (LOW ? 'l' : ''); }; + RP.mat.land = land; + }; + + // land textures from the heightfield: normals (rgb) and tint (rgb, x0.5) + vegetation amount (alpha) + X.land = function (land) { + var hf = land.hf, nx = hf.nx, nz = hf.nz, W = RP.W; + var nd = new Uint8Array(nx * nz * 4), cd = new Uint8Array(nx * nz * 4), n = new T.Vector3(), out = [1, 1, 1, 1], h = hf.h, c = hf.cell; + for (var j = 0; j < nz; j++) for (var i = 0; i < nx; i++) { + var o = (j * nx + i) * 4, x = hf.x0 + i * c, z = hf.z0 + j * c; + var h0 = h[j * nx + i], xa = h[j * nx + Math.min(nx - 1, i + 1)] - h0, xb = h0 - h[j * nx + Math.max(0, i - 1)], za = h[Math.min(nz - 1, j + 1) * nx + i] - h0, zb = h0 - h[Math.max(0, j - 1) * nx + i]; + var hx = Math.abs(xa) > Math.abs(xb) ? xa : xb, hz = Math.abs(za) > Math.abs(zb) ? za : zb; // the steeper one-cell step: narrow cliffs and terrace walls stay steep + n.set(-hx, c, -hz).normalize(); + nd[o] = (n.x * 0.5 + 0.5) * 255; nd[o + 1] = (n.y * 0.5 + 0.5) * 255; nd[o + 2] = (n.z * 0.5 + 0.5) * 255; nd[o + 3] = 255; + land.colour(x, z, h0, 1 - n.y, out, false); + cd[o] = M.clamp(out[0] * 127.5, 0, 255); cd[o + 1] = M.clamp(out[1] * 127.5, 0, 255); cd[o + 2] = M.clamp(out[2] * 127.5, 0, 255); cd[o + 3] = M.clamp(out[3] * 250, 0, 250); + } + function dt(d) { var t = new T.DataTexture(d, nx, nz, T.RGBAFormat, T.UnsignedByteType); t.magFilter = t.minFilter = T.LinearFilter; t.wrapS = t.wrapT = T.ClampToEdgeWrapping; t.needsUpdate = true; return t; } + if (X.landU.tLandN.value) { X.landU.tLandN.value.dispose(); X.landU.tLandC.value.dispose(); } + X.landU.tLandN.value = dt(nd); X.landU.tLandC.value = dt(cd); + X.landU.uLB.value.set(hf.x0 - c / 2, hf.z0 - c / 2, nx * c, nz * c); + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/missions.js b/e63334287a3deaa3/blacktie/js/missions.js new file mode 100644 index 00000000..abbdcf90 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/missions.js @@ -0,0 +1,164 @@ +/* + * Missions (RP.missions): each is data plus a few functions, registered with RP.missions.register({...}): + * id, title, blurb, atmos, start (spot), loadout {weaponId: reserve rounds}, armour, alert (true: alert level runs, + * false: locked), reinforce, spawns, setup(m) (place guards, guests, pickups), steps: [{ text, sub, at (objective + * position), check(m, dt) -> true when done, enter(m) }], checkpoints (step indexes to restart from), rate(m). + * The mission runner (RP.Run) handles objectives, checkpoints, failure and the results screen. + * Mission 3 (the chase down the coast road) comes with vehicles in phase 2. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W; + var V = function (x, z, y) { return { x: x, z: z, y: y }; }; + function near(p, s, r) { return Math.hypot(p.pos.x - s.x, p.pos.z - s.z) < r && (s.y == null || Math.abs(p.pos.y - s.y) < 4); } + function guard(type, x, z, yaw, opts) { return RP.AI.spawnGuard(type, { x: x, z: z, yaw: yaw || 0 }, opts); } + function pickup(kind, x, z, y) { RP.Run.pickup(kind, x, z, y); } + + // ------------------------------------------------------------------ 1. Lemon Light: the villa party + RP.missions.register({ + id: 'villa', num: 1, title: 'Lemon Light', where: 'Villa Calcara, Amalfi · dusk', + blurb: 'Halcyon Group\'s fixer is hosting a party on the terrace of Villa Calcara. His ledger of payments sits in the study. Slip in from the lemon terraces, take it, and leave by the cliff steps. Going unseen earns the Ghost rating.', + atmos: 'dusk', night: true, start: { x: -146, z: -14, y: 16.5, yaw: -0.65 }, alert: true, + loadout: { knife: 0, corsa: 45, vespa: 96, smoke: 2, frag: 1, _start: 'corsa' }, + spawns: [{ x: -128, z: 31 }, { x: -150, z: -10 }, { x: -92, z: 35 }, { x: -176, z: 2 }], + setup: function (m) { + // gate + guard('sentry', -134, 11, Math.PI / 2); guard('sentry', -134, 15.5, Math.PI / 2); + // garden patrols + guard('sentry', -186, 10, 0, { patrol: [V(-186, 10), V(-160, 10), V(-155.5, 22), V(-186, 14)] }); + guard('sentry', -192, 30, 0, { patrol: [V(-192, 30), V(-192, 12), V(-176, 12, null)] }); + // service gate on the north wall + guard('sentry', -165, 3.5, Math.PI); + // terrace: enforcers among the guests, one walking the balustrade + guard('enforcer', -152, 46, -Math.PI / 2); + guard('enforcer', -184, 58, 0, { patrol: [V(-184, 58), V(-154, 60), V(-150, 48), V(-184, 46)] }); + // inside: an elite by the study door, a marksman on the roof terrace + guard('elite', -173, 29, Math.PI); + guard('marksman', -160, 22, 2.4, {}); + RP.G.guards[RP.G.guards.length - 1].pos.y = 24 + 7.2; // on the roof + // guests on the terrace, in little groups + var groups = [[-178, 48], [-170, 54], [-160, 50], [-182, 58], [-166, 60]]; + groups.forEach(function (g, i) { for (var k = 0; k < 3; k++) { var a = k / 3 * 6.28 + i; RP.AI.spawnCiv({ x: g[0] + Math.cos(a) * 0.9, z: g[1] + Math.sin(a) * 0.9, yaw: a + Math.PI }, { talk: k !== 1, wander: 0 }); } }); + for (var i = 0; i < 4; i++) RP.AI.spawnCiv({ x: -186 + i * 7, z: 42 }, { wander: 5 }); + pickup('armour', -150, -6, 16.5); pickup('health', -176, 6, 20); pickup('mod:suppressor', -144.5, -11.5, 16.5); + m.unseen = true; + RP.on('alert', function (l) { if (l > 0 && RP.G.mission === m) m.unseen = false; }); + }, + steps: [ + { text: 'Get into Villa Calcara', sub: 'Climb the low garden wall or use the service gate. Ctrl: stealth.', at: V(-176, 14, 24), + check: function (m) { var p = RP.G.player; return p.pos.y > 22 && p.pos.x < -138 && p.pos.x > -196 && p.pos.z > 6 && p.pos.z < 64; } }, + { text: 'Find the ledger in the study', sub: 'The study is in the north-west corner of the house.', at: V(-178, 20.2, 24), checkpoint: true, + enter: function (m) { RP.Run.interactable('Take the ledger', RP.map.spots.ledger, 1.8, function () { m.hasLedger = true; RP.Audio.ui('objective'); }); }, + check: function (m) { return m.hasLedger; } }, + { text: 'Get out by the cliff steps', sub: 'The steps go down from the west end of the terrace to the landing.', at: V(-178, 84, 3), checkpoint: true, + check: function (m) { var p = RP.G.player; return p.pos.z > 74 && Math.abs(p.pos.x + 178) < 5; } } + ], + rate: function (m) { return [['Ghost (never seen)', m.unseen], ['Takedowns', RP.Run.stats.takedowns], ['Time', RP.Run.time()]]; } + }); + + // ------------------------------------------------------------------ 2. Piazza Duomo: the firefight + RP.missions.register({ + id: 'piazza', num: 2, title: 'Saint\'s Square', where: 'Piazza Duomo, Amalfi · late afternoon', + blurb: 'Your contact is pinned down in the cathedral porch at the top of the steps, and Halcyon\'s men hold the square. Come in through the Porta della Marina, clear the piazza, and get to the porch. Use the fountain, the stall and the van for cover.', + atmos: 'golden', start: { x: 0.5, z: 11, y: 2.6, yaw: Math.PI }, alert: true, reinforce: false, armour: 100, + loadout: { corsa: 60, tern: 150, breaker: 30, frag: 3, smoke: 1, _start: 'tern' }, + setup: function (m) { + // the café is full; everybody runs when it starts + for (var i = 0; i < 9; i++) RP.AI.spawnCiv({ x: -13 + (i % 2) * 2.5, z: -32 + i * 3 }, { talk: true, wander: 0 }); + for (i = 0; i < 4; i++) RP.AI.spawnCiv({ x: -2 + i * 2, z: -10 }, { wander: 6 }); + m.wave = 0; m.waves = [ + [['sentry', -3, -27], ['sentry', 6, -29], ['enforcer', 2, -34], ['sentry', -10, -36], ['enforcer', 8, -14], ['sentry', -15, -16]], + [['enforcer', -6, -52], ['shotgunner', -2, -50], ['enforcer', 4, -54], ['sentry', -9, -58], ['marksman', 30, -27, 13]], + [['elite', 28, -14, 13], ['elite', 28, -26, 13], ['gunner', 32, -20, 13], ['elite', 20, -12, 9.5]] + ]; + pickup('armour', -14, 12, 2.6); pickup('mod:grip', 3.2, 12.5, 2.6); pickup('mod:extmag', -2.4, 12.5, 2.6); pickup('ammo', -16, -10, 5); pickup('health', 9, -40, 5); pickup('ammo', 12, -6, 5); + }, + steps: [ + { text: 'Go through the Porta della Marina', sub: 'Halcyon\'s men are waiting in the piazza.', at: V(0.5, -2, 5), + check: function (m) { return RP.G.player.pos.z < 1; } }, + { text: 'Clear the piazza', sub: 'Wave 1 of 3', at: null, checkpoint: true, + enter: function (m) { spawnWave(m, 0); }, + check: function (m) { return waveDone(m, 0); } }, + { text: 'More of them from the main street', sub: 'Wave 2 of 3 · watch the cathedral roof', at: null, checkpoint: true, + enter: function (m) { spawnWave(m, 1); RP.AI.say(RP.G.guards[RP.G.guards.length - 1], 'flank'); }, + check: function (m) { return waveDone(m, 1); } }, + { text: 'The elite squad holds the steps', sub: 'Wave 3 of 3', at: V(19, -20, 9), checkpoint: true, + enter: function (m) { spawnWave(m, 2); }, + check: function (m) { return waveDone(m, 2); } }, + { text: 'Reach your contact in the cathedral porch', at: V(30, -20, 13), + check: function (m) { return near(RP.G.player, { x: 30, z: -20, y: 13 }, 3.5); } } + ], + rate: function (m) { var p = RP.G.player; return [['Accuracy', p.shots ? Math.round(p.hits / p.shots * 100) + '%' : '—'], ['Defeated', p.kills], ['Time', RP.Run.time()]]; } + }); + function spawnWave(m, i) { + m.waveGuards = m.waveGuards || []; + m.waveGuards[i] = m.waves[i].map(function (w) { + var g = RP.AI.spawnGuard(w[0], { x: w[1], z: w[2], y: w[3], yaw: 0 }); + if (w[0] === 'marksman') { g.post = { x: w[1], z: w[2], yaw: -Math.PI / 2 }; } + RP.AI.alertGuard(g, RP.G.player.pos, false); g.react = 0.6 + Math.random() * 0.8; + return g; + }); + RP.Alert.set(Math.max(RP.Alert.level, 2 + i)); + } + function waveDone(m, i) { return m.waveGuards && m.waveGuards[i] && m.waveGuards[i].every(function (g) { return !g.alive; }); } + + // ------------------------------------------------------------------ mission 3: the coast road + function chasers() { return RP.Vehicles.list.filter(function (v) { return v.ai && !v.dead && !v.ai.out; }).length; } + function pursuit(m, dt, want, level) { + // keep Halcyon on your tail: up to `want` cars, a new one every so often from behind; the alert stays up + m.chT = (m.chT == null ? 4 : m.chT) - dt; + if (m.chT <= 0 && chasers() < want && RP.G.player.vehicle) { RP.Vehicles.chaser(75 + Math.random() * 30); m.chT = 11 + Math.random() * 6; RP.AI.line && RP.emit('sub', 'Radio: ' + ['He is on the coast road, heading east!', 'Second car, close up on him!', 'Run him off the road!'][Math.floor(Math.random() * 3)], 3); } + m.alT = (m.alT || 0) - dt; if (m.alT <= 0) { m.alT = 2; if (RP.Alert.level < level) RP.Alert.set(level); RP.Alert.seen(RP.G.player.pos); } + } + function ensureCar(yaw) { var p = RP.G.player; if (!p.vehicle && !RP.Vehicles.near(p)) RP.Vehicles.spawn('spider', p.pos.x + 3, p.pos.z + 1, yaw || Math.PI / 2, '#8f1d22'); } + RP.missions.register({ + id: 'chase', num: 3, title: 'Coast Road', where: 'Amalfi to the far town · early evening', + blurb: 'You have the ledger and Halcyon knows it. A Brezza Spider is waiting on the waterfront: take the coast road east, through the tunnels and over the viaduct, down into the next town, and out to sea on the launch at its pier. Their saloons will be on your tail and they have a helicopter.', + atmos: 'golden', start: { x: 24, z: 20.5, y: 2.6, yaw: 0.9 }, alert: true, reinforce: false, armour: 100, traffic: true, + loadout: { corsa: 90, vespa: 192, frag: 2, _start: 'corsa' }, + setup: function (m) { + pickup('mod:extmag', 22, 22, 2.6); pickup('health', 468, 39, 33.8); pickup('armour', 1456, -58, 20); pickup('health', 1392, -27, 7.6); pickup('ammo', 1420, 0, 3.4); + for (var i = 0; i < 5; i++) RP.AI.spawnCiv({ x: 4 + i * 3, z: 24 + (i % 2) * 2 }, { wander: 6 }); + }, + steps: [ + { text: 'Get in the Brezza Spider', sub: 'F by the door. W/S drive, A/D steer, Space handbrake.', at: V(30, 17.5, 2.9), + check: function (m) { return !!RP.G.player.vehicle; } }, + { text: 'Take the coast road east', sub: 'Through the first tunnel to the belvedere', at: V(466, 36, 33.8), checkpoint: true, + enter: function (m) { ensureCar(); m.chT = 9; }, + check: function (m, dt) { pursuit(m, dt, 1, 2); return RP.G.player.pos.x > 440; } }, + { text: 'Keep going: over the viaduct', sub: 'They have called in the helicopter', at: V(880, 16, 32), checkpoint: true, + enter: function (m) { ensureCar(); m.chT = 3; }, + check: function (m, dt) { pursuit(m, dt, 2, 4); return RP.G.player.pos.x > 870; } }, + { text: 'Through the second tunnel and down into the town', sub: 'Follow the street down to the piazzetta', at: V(1458, -56, 20), checkpoint: true, + enter: function (m) { ensureCar(); m.chT = 3; }, + check: function (m, dt) { pursuit(m, dt, 2, 4); return near(RP.G.player, { x: 1458, z: -56 }, 16); } }, + { text: 'Get down to the pier', sub: 'The stair lane by the piazzetta leads to the church and the beach', at: V(1360.6, 36, 1), checkpoint: true, + enter: function (m) { RP.Alert.set(Math.max(RP.Alert.level, 3)); }, + check: function (m) { var p = RP.G.player; return !!(p.vehicle && p.vehicle.ty.water); } }, + { text: 'Head out to sea', sub: 'South, away from the coast', at: V(1360, 210, 0), + check: function (m) { return RP.G.player.pos.z > 190; } } + ], + rate: function (m) { var p = RP.G.player; return [['Defeated', p.kills], ['Time', RP.Run.time()]]; } + }); + + // ------------------------------------------------------------------ free roam + RP.missions.register({ + id: 'free', num: 0, title: 'Free Roam', where: 'Amalfi · afternoon', free: true, + blurb: 'The whole town, no objectives. Halcyon\'s guards hold the villa, the harbour, the piazza and the coast road. Start trouble and the alert level climbs; break line of sight and stay out of the search circle to shake them off.', + atmos: 'afternoon', start: { x: -4, z: 16, y: 2.6, yaw: Math.PI }, alert: true, armour: 50, traffic: true, + loadout: { knife: 0, bat: 0, crowbar: 0, hammer: 0, club: 0, machete: 0, corsa: 90, bastion: 36, vespa: 192, tern: 180, gale: 150, breaker: 42, twinbore: 30, longreach: 30, mauler: 200, thumper: 8, hornet: 4, frag: 4, sticky: 3, smoke: 3, _start: 'corsa' }, + setup: function (m) { + guard('sentry', 8, -30, -2.4); guard('sentry', -12, -8, 2.6, { patrol: [V(-12, -8), V(6, -8), V(6, -34), V(-12, -34)] }); + guard('sentry', 30, 27, Math.PI); guard('enforcer', 18, 30, 2.8, { patrol: [V(18, 30), V(34, 30), V(35, 70), V(18, 30)] }); + guard('sentry', -134, 11, Math.PI / 2); guard('sentry', -134, 15.5, Math.PI / 2); guard('enforcer', -168, 50, 0, { patrol: [V(-180, 50), V(-155, 52)] }); guard('elite', -170, 30, Math.PI); + guard('enforcer', 96, 27, -1.6); guard('sentry', 92, 25, -1.6); + guard('marksman', 134, 46, -2.2); RP.G.guards[RP.G.guards.length - 1].pos.y = W.terrainH(140, 54) + 13; + guard('sentry', -9, -84, 0, { patrol: [V(-9, -84), V(-12, -118), V(-9, -84)] }); + for (var i = 0; i < 8; i++) RP.AI.spawnCiv({ x: -13 + (i % 2) * 2.5, z: -32 + i * 3 }, { talk: i % 3 !== 0, wander: 4 }); + for (i = 0; i < 8; i++) RP.AI.spawnCiv({ x: -30 + i * 7, z: 18 + (i % 2) * 4 }, { wander: 10 }); + for (i = 0; i < 5; i++) RP.AI.spawnCiv({ x: -6 - i * 1.5, z: -60 - i * 12 }, { wander: 8 }); + pickup('armour', 12, 20, 2.6); pickup('mod:suppressor', -7, 19, 2.6); pickup('mod:scope', -3, 19.5, 2.6); pickup('mod:grip', 1, 19.5, 2.6); pickup('mod:extmag', 5, 19, 2.6); pickup('health', -16, -10, 5); pickup('ammo', 26, 27, 1.6); pickup('health', -150, -6, 16.5); pickup('armour', 28, -20, 13); pickup('ammo', -9, -100, 13); + }, + steps: [{ text: 'Free roam', sub: 'Tab: weapons · Esc: menu', at: null, check: function () { return false; } }] + }); +})(); diff --git a/e63334287a3deaa3/blacktie/js/player.js b/e63334287a3deaa3/blacktie/js/player.js new file mode 100644 index 00000000..e5bcd422 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/player.js @@ -0,0 +1,894 @@ +/* + * The player (RP.Player): one controller for walking, jogging, sprinting, stealth, cover, aiming and firing, + * reloading, switching weapons, melee and fist fights, jumping, vaulting, climbing, rolling, dodging, throwing, + * takedowns, damage, ragdoll and getting up. Runs in the fixed 60 Hz step (step) and once per rendered frame + * (frame: animation and aim pose). + * + * States: move | air | vault | climb | roll | dodge | cover | takedown | ragdoll | getup | dead + * Things that overlap a state (aiming, firing, reloading, switching weapon, a melee swing, a throw) are flags and + * timers, so the upper body can do them while the legs keep doing whatever they were doing: e.g. reload while + * jogging into cover, aim around a corner from cover, fire from the hip while strafing. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W, TU = RP.TUNING, WP = RP.Weapons; + var D2R = Math.PI / 180; + var P = RP.Player = {}; + + P.create = function (spot, loadout) { + var a = RP.Chars.spawn('agent'); a.isPlayer = true; + RP.R.scene.add(a.root); + var p = { + actor: a, team: 'player', alive: true, radius: TU.radius, height: 1.8, + pos: new T.Vector3(spot.x, spot.y, spot.z), vel: new T.Vector3(), yaw: spot.yaw || 0, onGround: true, gy: spot.y, gmat: 'stone', + state: 'move', st: 0, stealth: false, sprinting: false, stamina: 1, speed: 0, turnRate: 0, accel: 0, lastSpeed: 0, + hp: TU.maxHealth, armour: 0, lastHit: -99, inv: {}, cur: 'fists', prevW: 'fists', throwId: 'frag', + aiming: false, aimW: 0, fireCd: 0, recoilP: 0, recoilY: 0, bloom: 0, hipT: 0, reload: null, swap: null, + melee: null, combo: 0, comboT: 0, guardT: 0, dodgeCd: 0, rollCd: 0, counterT: 0, + cover: null, fallStart: spot.y, noise: 0, vis: 1, lock: null, takedown: null, kills: 0, shots: 0, hits: 0, wheelOpen: false + }; + // loadout: {id: rounds in reserve} (mag fills first) + Object.keys(loadout || {}).forEach(function (id) { giveWeapon(p, id, loadout[id]); }); + giveWeapon(p, 'fists', 0); + p.takeDamage = function (amt, info) { takeDamage(p, amt, info); }; + p.suppress = function (k) { p.suppressT = Math.max(p.suppressT || 0, k); }; + a.root.position.copy(p.pos); a.root.rotation.y = p.yaw; + RP.G.player = p; RP.G.ents.push(p); + equip(p, loadout && loadout._start ? loadout._start : bestWeapon(p), true); + return p; + }; + function giveWeapon(p, id, reserve) { + if (id[0] === '_') return; + var d = WP.DEFS[id]; if (!d) return; + var e = p.inv[id]; + if (!e) e = p.inv[id] = { mag: d.mag || 0, reserve: 0 }; + e.reserve = Math.min((d.reserve || 0) * 2, e.reserve + (reserve == null ? d.reserve || 0 : reserve)); + if (d.cat === 'throw') { e.mag = 0; e.reserve = Math.max(e.reserve, 0); } + } + P.give = giveWeapon; + function bestWeapon(p) { var pref = ['tern', 'vespa', 'corsa', 'knife', 'fists']; for (var i = 0; i < pref.length; i++) if (p.inv[pref[i]]) return pref[i]; return 'fists'; } + function def(p) { var e = p.inv[p.cur]; return e && e.mods ? WP.eff(p.cur, e.mods) : WP.DEFS[p.cur]; } + P.def = def; + + // ------------------------------------------------------------------ equip / holster + function equip(p, id, instant) { + if (!p.inv[id] || WP.DEFS[id].cat === 'throw') return; + if (id === p.cur && !instant) return; + if (p.reload) p.reload = null; + if (!instant) { p.prevW = p.cur; p.swap = { to: id, t: 0, out: p.cur === 'fists' ? 0.05 : 0.24, inn: 0.32 * (WP.DEFS[id].aimTime ? 1 + WP.DEFS[id].aimTime : 1) }; if (p.cur !== 'fists') p.actor.move(stowMove(p.cur, false)); RP.Audio.mech('holster', p.pos); return; } + setHeld(p, id); + } + // where each weapon is carried: pistols in a shoulder holster under the jacket, long guns slung on the back, + // knives and throwables in pockets + function stowMove(id, draw) { + var d = WP.DEFS[id], m = d.cat === 'pistol' ? 'Chest' : (d.cat === 'melee' || d.cat === 'throw') ? '' : 'Back'; + return (draw ? 'draw' : 'holster') + m; + } + P.stowMove = stowMove; + function setHeld(p, id) { + p.cur = id; + var m = id === 'fists' ? null : WP.dress(WP.model(id), p.inv[id] && p.inv[id].mods); + p.actor.hold(m); p.model = m; + RP.emit('weapon', p); + } + P.equip = equip; + P.refit = function (p) { if (p.cur !== 'fists') setHeld(p, p.cur); }; + + // ------------------------------------------------------------------ helpers + function camYaw() { return RP.Cam.yaw; } + function fwdOf(y, out) { return (out || new T.Vector3()).set(Math.sin(y), 0, Math.cos(y)); } + var _v = new T.Vector3(), _v2 = new T.Vector3(), _g = {}; + function wishDir(out) { + var I = RP.In, cy = camYaw(), fx = Math.sin(cy), fz = Math.cos(cy), rx = -Math.cos(cy), rz = Math.sin(cy); + out.set(fx * I.move.y + rx * I.move.x, 0, fz * I.move.y + rz * I.move.x); + return out; + } + // a wall in front of the feet: returns {box, top (above feet), dist, nx, nz, depth} + function probeAhead(p, dir, reach) { + var best = null, l = W.near(p.pos.x, p.pos.z, reach + 2, []); + for (var i = 0; i < l.length; i++) { + var b = l[i]; if (b.nocol || b.y0 > p.pos.y + 1.2) continue; + for (var hh = 0.35; hh <= 1.2; hh += 0.42) { + var h = rayBoxH(b, p.pos.x, p.pos.y + hh, p.pos.z, dir.x, dir.z, reach); + if (h && (!best || h.t < best.dist)) { + var lx = W.toLocal(b, p.pos.x + dir.x * (h.t + 0.05), p.pos.z + dir.z * (h.t + 0.05), {}); + var top = W.topAt(b, M.clamp(lx.z, -b.hz, b.hz)) - p.pos.y; + if (top > TU.stepUp) best = { box: b, top: top, dist: h.t, nx: h.nx, nz: h.nz }; + } + } + } + return best; + } + // horizontal ray vs box sides + function rayBoxH(b, ox, oy, oz, dx, dz, maxT) { + if (oy < b.y0 || oy > b.y1 + 0.05) return null; + var px = ox - b.x, pz = oz - b.z, lx = px * b.c - pz * b.s, lz = px * b.s + pz * b.c, ldx = dx * b.c - dz * b.s, ldz = dx * b.s + dz * b.c; + var t0 = 0, t1 = maxT, n = -1, sg = 0, o = [lx, lz], d = [ldx, ldz], hh = [b.hx, b.hz]; + for (var a = 0; a < 2; a++) { + if (Math.abs(d[a]) < 1e-9) { if (o[a] < -hh[a] || o[a] > hh[a]) return null; continue; } + var inv = 1 / d[a], ta = (-hh[a] - o[a]) * inv, tb = (hh[a] - o[a]) * inv, s = -1; + if (ta > tb) { var tt = ta; ta = tb; tb = tt; s = 1; } + if (ta > t0) { t0 = ta; n = a; sg = s; } if (tb < t1) t1 = tb; if (t0 > t1) return null; + } + if (n < 0 || t0 <= 0) return null; + var w = W.toWorldDir(b, n === 0 ? sg : 0, n === 1 ? sg : 0, {}); + if (oy > W.topAt(b, M.clamp(lz + ldz * t0, -b.hz, b.hz))) return null; + return { t: t0, nx: w.x, nz: w.z }; + } + P.rayBoxH = rayBoxH; + + // ------------------------------------------------------------------ the fixed step + P.step = function (p, dt) { + var I = RP.In; + if (!p.alive) { stepDead(p, dt); return; } + p.st += dt; + p.fireCd = Math.max(0, p.fireCd - dt); p.dodgeCd = Math.max(0, p.dodgeCd - dt); p.rollCd = Math.max(0, p.rollCd - dt); + p.counterT = Math.max(0, p.counterT - dt); p.comboT = Math.max(0, p.comboT - dt); p.guardT = Math.max(0, p.guardT - dt); + p.suppressT = Math.max(0, (p.suppressT || 0) - dt * 0.8); + var d = def(p), busy = p.state !== 'move' && p.state !== 'cover' && p.state !== 'air'; + // ---- toggles + if (I.pressed('stealth') && (p.state === 'move' || p.state === 'cover')) { p.stealth = !p.stealth; RP.emit('stealth', p.stealth); } + if (I.pressed('prev') && !busy) equip(p, p.inv[p.prevW] ? p.prevW : 'fists'); + // ---- aim (hold); assisted lock-on handled in camera/aim + var wantAim = I.down('aim') && !p.wheelOpen && p.state !== 'roll' && p.state !== 'vault' && p.state !== 'climb' && p.state !== 'ragdoll' && p.state !== 'getup' && p.state !== 'takedown' && !p.swap; + if (d.melee) wantAim = wantAim && p.state === 'move'; + p.aiming = wantAim; + p.aimW = M.approach(p.aimW, p.aiming ? 1 : 0, 1 / Math.max(0.08, d.aimTime || 0.15), dt); + // ---- weapon switching (holster -> draw) + if (p.swap) { + p.swap.t += dt; + if (p.swap.t >= p.swap.out && !p.swap.drawn) { p.swap.drawn = true; setHeld(p, p.swap.to); p.actor.move(stowMove(p.swap.to, true)); } + if (p.swap.t >= p.swap.out + p.swap.inn) p.swap = null; + } + // ---- states + switch (p.state) { + case 'move': stepMove(p, dt); break; + case 'air': stepAir(p, dt); break; + case 'vault': case 'climb': stepTraverse(p, dt); break; + case 'roll': case 'dodge': stepRoll(p, dt); break; + case 'cover': stepCover(p, dt); break; + case 'takedown': stepTakedown(p, dt); break; + case 'ragdoll': stepRagdoll(p, dt); break; + case 'drive': RP.Vehicles.stepDriver(p, dt); break; + case 'swim': stepSwim(p, dt); break; + case 'getup': if (p.st > 0.95) setState(p, 'move'); groundSnap(p, dt); break; + } + // ---- weapons, melee, throwing (any state that allows the upper body) + var upperFree = p.state === 'move' || p.state === 'cover' || (p.state === 'air' && !d.melee) || (p.state === 'drive' && !d.melee); + if (upperFree && !p.wheelOpen) { stepWeapon(p, dt); stepThrow(p, dt); } + if (p.melee) stepMelee(p, dt); + // ---- health regen, stamina, noise, visibility + if (RP.G.time - p.lastHit > TU.regenDelay && p.hp < TU.maxHealth * TU.regenTo) p.hp = Math.min(TU.maxHealth * TU.regenTo, p.hp + TU.regenRate * dt); + p.recoilP = M.approach(p.recoilP, 0, (d.recover || 15) * D2R * (p.fireHeld ? 0.25 : 1), dt); + p.recoilY = M.approach(p.recoilY, 0, (d.recover || 15) * D2R, dt); + p.bloom = M.approach(p.bloom, 0, 3, dt); + p.hipT = Math.max(0, p.hipT - dt); + var sp = p.speed; + p.noise = p.stealth ? (sp > 0.3 ? TU.noiseStealth : 0) : sp > 5 ? TU.noiseSprint : sp > 2.5 ? TU.noiseJog : sp > 0.4 ? TU.noiseWalk : 0; + footsteps(p, dt); + p.vis = (p.stealth ? 0.55 : 1) * (RP.G.night ? 0.7 : 1) * (p.state === 'cover' && !p.aiming ? 0.6 : 1); + // interact (objectives, weapon swaps), drop the weapon in hand + if (I.pressed('interact')) RP.emit('interact', p); + if (I.pressed('enter') && p.state === 'move' && !p.swap) RP.Vehicles.interact(p); + if (I.pressed('drop') && p.state === 'move' && !p.swap && !p.reload) RP.Items.playerDrop(p); + }; + + function setState(p, s) { p.state = s; p.st = 0; } + P.setState = setState; + + // ---- ground + function groundSnap(p, dt) { + var g = W.ground(p.pos.x, p.pos.z, p.pos.y + 0.05, TU.stepUp + 0.05, _g); + p.gmat = g.mat; + // out of your depth: swim + if (g.y < W.water - SWIM_DEPTH && p.pos.y < W.water + 0.6 && (p.state === 'move' || p.state === 'cover')) { startSwim(p); return false; } + if (p.pos.y - g.y > 0.45) { if (p.state === 'move' || p.state === 'cover') { setState(p, 'air'); p.fallStart = p.pos.y; p.vel.y = 0; p.actor.move('jump', { w: 0.6 }); } return false; } + // smooth stepping up and down stairs + p.pos.y = g.y > p.pos.y ? M.approach(p.pos.y, g.y, 4.5, dt) : M.damp(p.pos.y, g.y, 30, dt); + if (Math.abs(p.pos.y - g.y) < 0.002) p.pos.y = g.y; + if (g.water && p.pos.y < W.water - 1.0) { p.pos.y = W.water - 1.0; } + return true; + } + + // ---- locomotion (walk, jog, sprint, stealth, strafing when aiming) + function stepMove(p, dt) { + var I = RP.In, d = def(p), wish = wishDir(_v), mag = Math.min(1, wish.length()); + if (mag > 0.01) wish.divideScalar(Math.max(mag, 1e-3)); + var strafe = p.aiming || p.hipT > 0 || (d.melee && p.guardT > 0 && p.lockT); + // sprint: stamina, not while aiming or reloading heavy, not in stealth (stealth + sprint = stealth jog) + var wantSprint = I.down('sprint') && mag > 0.3 && !p.aiming && p.stamina > 0.02 && !p.melee; + if (wantSprint && p.reload) p.reload = null; // sprinting cancels a reload (start it again after) + p.sprinting = wantSprint && !p.stealth; + if (p.sprinting) p.stamina = Math.max(0, p.stamina - dt / TU.stamina); + else p.stamina = Math.min(1, p.stamina + dt / TU.stamina * TU.staminaRegen); + var target; + if (p.stealth) target = (wantSprint ? TU.stealthJog : TU.stealthWalk) * (mag > 0.55 && !I.down('walk') ? 1 : 0.7); + else if (p.aiming) target = (I.down('walk') || mag < 0.55 ? TU.aimWalk : TU.aimJog); + else if (p.sprinting) target = TU.sprint; + else target = I.down('walk') || mag < 0.55 ? TU.walk : TU.jog; + target *= (d.weight || 1) * mag; + if (p.melee && p.melee.def && !p.melee.def.push) target *= 0.35; + if (p.reload && p.reload.heavy) target = Math.min(target, TU.walk); + // facing + var face = p.yaw, turnR = TU.turnRate; + if (strafe) { face = camYaw(); turnR = 14; } + else if (mag > 0.05) { + face = Math.atan2(wish.x, wish.z); + if (p.sprinting) turnR = TU.sprintTurnRate; + if (p.speed < 0.6) turnR = 7; // turning from standing: a quick step round + // sharp turn at a sprint: momentum, lose speed + if (p.sprinting && Math.abs(M.wrap(face - p.yaw)) > 1.75 && p.speed > 5) { p.speed *= TU.sharpTurnSlow; p.actor.move('stumble', { w: 0.35 }); } + } + var prevYaw = p.yaw; + p.yaw = M.approachAngle(p.yaw, face, turnR, dt); + p.turnRate = M.wrap(p.yaw - prevYaw) / dt; + // speed with weight: accelerate and stop over a short distance + var acc = target > p.speed ? (p.sprinting ? TU.sprintAccel : TU.accel) : (p.speed > TU.jog + 0.5 ? TU.sprintDecel : TU.decel); + var prevSpeed = p.speed; + p.speed = M.approach(p.speed, target, acc, dt); + p.accel = (p.speed - prevSpeed) / dt; + // move direction: forward when free, the wish direction when strafing + var dir = strafe && mag > 0.05 ? wish : fwdOf(p.yaw, _v2); + if (strafe && mag <= 0.05) dir = p.lastDir || fwdOf(p.yaw, _v2); + p.lastDir = (p.lastDir || new T.Vector3()).copy(dir); + p.moveDir = Math.atan2(dir.x, dir.z) - p.yaw; + var ox = p.pos.x, oz = p.pos.z; + W.move(p.pos, dir.x * p.speed * dt, dir.z * p.speed * dt, p.radius, 1.7); + // walking into a wall: slow down (no running on the spot) + var moved = Math.hypot(p.pos.x - ox, p.pos.z - oz) / dt; + if (moved < p.speed * 0.3 && p.speed > 1) p.speed = Math.max(moved, p.speed * 0.6); + p.vel.set((p.pos.x - ox) / dt, 0, (p.pos.z - oz) / dt); + groundSnap(p, dt); + // Space: roll (aiming + direction), dodge (fist fight), vault / climb / jump + if (I.pressed('jump')) { + if (p.aiming && mag > 0.3 && p.rollCd <= 0 && !d.melee) startRoll(p, wish); + else if ((d.melee) && (p.guardT > 0 || p.aiming) && p.dodgeCd <= 0) startDodge(p, mag > 0.3 ? wish : fwdOf(p.yaw + Math.PI)); + else traverseOrJump(p, mag > 0.2 ? wish : fwdOf(p.yaw)); + } + // Q: cover + if (I.pressed('cover')) tryCover(p); + } + + // ---- jump / vault / climb decision + function traverseOrJump(p, dir) { + // reach further the faster you're going (running at a wall and pressing jump a stride away still vaults it) + if (tryTraverse(p, dir, 0.95 + M.clamp(p.speed, 0, 6) * 0.22, TU.climbMax)) return; + // a plain jump, keeping momentum + setState(p, 'air'); p.fallStart = p.pos.y; + var f = fwdOf(p.yaw); + p.vel.set(p.vel.x, TU.jumpV, p.vel.z); + if (p.speed < 0.5) p.vel.set(0, TU.jumpV, 0); + p.actor.move('jump'); + RP.Audio.step(p.gmat, p.pos, 1.5); + } + // vault over or climb onto what is in front, if it is in reach and there's room: true if it started + function tryTraverse(p, dir, reach, maxTop) { + var ob = probeAhead(p, dir, reach); + if (ob && ob.top <= maxTop) { + // where would we end up? + var n = new T.Vector3(-ob.nx, 0, -ob.nz); // into the obstacle + var topY = p.pos.y + ob.top; + // depth of the obstacle along the move: vault over if there's floor within ~1.6 m on the other side at a lower level + var over = p.pos.clone().addScaledVector(n, ob.dist + 1.4); + var gOver = W.ground(over.x, over.z, topY + 0.1, 0.1); + var onTop = p.pos.clone().addScaledVector(n, ob.dist + 0.45); + if (ob.top <= TU.vaultMax && gOver.y < topY - 0.3 && !W.blocked(over.x, gOver.y, over.z, 0.3, 1.6)) { + startTraverse(p, 'vault', n, over, gOver.y, 1.0, topY); return true; + } + if (!W.blocked(onTop.x, topY, onTop.z, 0.28, 1.6)) { startTraverse(p, ob.top <= TU.vaultMax ? 'climbLow' : 'climb', n, onTop, topY, ob.top <= TU.vaultMax ? 0.6 : 0.95); return true; } + } + return false; + } + function startTraverse(p, kind, n, to, toY, dur, overY) { + setState(p, kind === 'vault' ? 'vault' : 'climb'); + // a vault's feet clear the obstacle's top (overY) at the middle of the move + p.trav = { kind: kind, from: p.pos.clone(), to: new T.Vector3(to.x, toY, to.z), dur: dur, top: Math.max(p.pos.y, toY, overY == null ? -1e9 : overY - 0.55) }; + p.yaw = Math.atan2(n.x, n.z); + if (kind === 'vault') p.actor.playFull('vault', { fade: 0.08, speed: 1.1 / dur }); + else p.actor.move(kind === 'climb' ? 'climb' : 'land', { speed: kind === 'climb' ? 1 : 1.6 }); + p.reload = null; + RP.Audio.step('stone', p.pos, 1.4); RP.Audio.mech('holster', p.pos); + } + function stepTraverse(p, dt) { + var t = p.trav, u = Math.min(1, p.st / t.dur); + var hx = M.smooth(M.clamp((u - (t.kind === 'climb' ? 0.45 : 0.1)) / (t.kind === 'climb' ? 0.55 : 0.8), 0, 1)); + var hy = t.kind === 'climb' ? M.smooth(Math.min(1, u / 0.7)) : M.smooth(Math.min(1, u / 0.35)); + p.pos.x = t.from.x + (t.to.x - t.from.x) * hx; p.pos.z = t.from.z + (t.to.z - t.from.z) * hx; + if (t.kind === 'vault') { + // up and over the top, then down to the far ground + var arc = Math.sin(Math.min(1, u) * Math.PI) * 0.12; + var topY = t.top; // (the vault clip lifts the legs over; the root rides the obstacle's top less the hip clearance) + p.pos.y = (u < 0.5 ? M.lerp(t.from.y, topY, hy) : M.lerp(topY, t.to.y, M.smooth((u - 0.5) / 0.5))) + arc; + } else p.pos.y = M.lerp(t.from.y, t.to.y, hy); + p.speed = 0; + if (u >= 1) { + p.pos.copy(t.to); setState(p, 'move'); p.speed = t.kind === 'vault' ? 2.5 : 0; + RP.Audio.step(p.gmat, p.pos, 1.2); + } + } + + // ---- swimming: the head above water, slow, no weapons; out again where it is shallow enough to stand + var SWIM_DEPTH = 1.3, SWIM_Y = 1.32; // water deeper than this is swum; the feet hang this far below the surface + function startSwim(p) { + setState(p, 'swim'); p.cover = null; p.reload = null; p.melee = null; p.aiming = false; p.sprinting = false; p.stealth = false; + p.vel.y = 0; p.speed = Math.min(p.speed, 2); + if (p.cur !== 'fists') { p.swimHeld = p.cur; equip(p, 'fists', true); } + RP.FX.splash(p.pos.x, W.water, p.pos.z, 1.2); RP.Audio.impact('water', p.pos, 1); + } + P.startSwim = startSwim; + function stepSwim(p, dt) { + var I = RP.In, wish = wishDir(_v), mag = Math.min(1, wish.length()); + if (mag > 0.01) wish.divideScalar(Math.max(mag, 1e-3)); + var target = (I.down('sprint') ? 2.7 : 1.7) * mag; + p.speed = M.approach(p.speed, target, 2.2, dt); + if (mag > 0.05) p.yaw = M.approachAngle(p.yaw, Math.atan2(wish.x, wish.z), 3.5, dt); + var dir = fwdOf(p.yaw, _v2), ox = p.pos.x, oz = p.pos.z; + W.move(p.pos, dir.x * p.speed * dt, dir.z * p.speed * dt, p.radius, 1.2, 0.1); + p.vel.set((p.pos.x - ox) / dt, 0, (p.pos.z - oz) / dt); + p.pos.y = M.damp(p.pos.y, W.water - SWIM_Y + M.clamp(p.speed / 1.7, 0, 1) * 0.3 + Math.sin(RP.G.time * 2.2) * 0.04, 6, dt); // a swimmer moving forward rides higher + p.noise = p.speed > 2 ? 8 : 3; p.vis = 0.75; + // splashes now and then while swimming + p._swT = (p._swT || 0) - dt; if (p.speed > 0.6 && p._swT <= 0) { p._swT = 0.55; RP.FX.splash(p.pos.x + dir.x * 0.6, W.water, p.pos.z + dir.z * 0.6, 0.4); } + // shallow enough to stand: walk out + var g = W.ground(p.pos.x, p.pos.z, W.water + 0.5, 0.3, _g); + if (g.y > W.water - SWIM_DEPTH + 0.12) { + p.pos.y = Math.max(p.pos.y, g.y); setState(p, 'move'); p.vel.set(0, 0, 0); + if (p.swimHeld && p.inv[p.swimHeld]) equip(p, p.swimHeld); p.swimHeld = null; + return; + } + // a quay or a boat side in front: climb out (Space), as on land + if (I.pressed('jump')) traverseOrJump(p, mag > 0.2 ? wish : fwdOf(p.yaw)); + // get into a boat alongside + if (I.pressed('enter') || I.pressed('interact')) { var bt = RP.Vehicles.near(p); if (bt) { p.state = 'move'; p.st = 1; if (!RP.Vehicles.enter(p, bt)) setState(p, 'swim'); } } + } + + // ---- in the air: gravity, keep momentum, land by height + function stepAir(p, dt) { + p.vel.y -= TU.gravity * dt; + var I = RP.In, wish = wishDir(_v); + // a little air control + p.vel.x += wish.x * 2.5 * dt; p.vel.z += wish.z * 2.5 * dt; + var ox = p.pos.x, oz = p.pos.z; + W.move(p.pos, p.vel.x * dt, p.vel.z * dt, p.radius, 1.7, 0.1); + if (Math.abs(p.pos.x - ox - p.vel.x * dt) > 0.001) p.vel.x *= 0.3; + if (Math.abs(p.pos.z - oz - p.vel.z * dt) > 0.001) p.vel.z *= 0.3; + p.pos.y += p.vel.y * dt; + p.fallStart = Math.max(p.fallStart, p.pos.y); + // jumped into a low wall while pushing toward it: go over it (a mantle), as on the ground + if (p.st > 0.06 && wish.lengthSq() > 0.09 && p.pos.y - p.fallStart > -0.6 && tryTraverse(p, fwdOf(p.yaw), 0.9, TU.vaultMax + 0.25)) { p.actor.endMove('jump'); return; } + // grab a ledge in front while falling or near the top of a jump + if (I.down('jump') && p.vel.y < 2 && p.st > 0.12) { + var ob = probeAhead(p, fwdOf(p.yaw), 0.6); + if (ob && ob.top > 0.4 && ob.top < 1.9) { var n = new T.Vector3(-ob.nx, 0, -ob.nz), to = p.pos.clone().addScaledVector(n, ob.dist + 0.45); if (!W.blocked(to.x, p.pos.y + ob.top, to.z, 0.28, 1.6)) { p.actor.endMove('jump'); startTraverse(p, 'climb', n, to, p.pos.y + ob.top, 0.8); return; } } + } + var g = W.ground(p.pos.x, p.pos.z, p.pos.y + 0.3, 0.3, _g); + if (g.y < W.water - SWIM_DEPTH && p.pos.y <= W.water - SWIM_Y && p.vel.y <= 0) { RP.FX.splash(p.pos.x, W.water, p.pos.z, 1.5); RP.Audio.impact('water', p.pos, 1.5); startSwim(p); return; } + if (p.pos.y <= g.y && p.vel.y <= 0) { + p.pos.y = g.y; var h = p.fallStart - g.y; + p.actor.endMove('jump'); + p.speed = Math.hypot(p.vel.x, p.vel.z) * 0.7; p.vel.set(0, 0, 0); + if (g.water) { RP.FX.splash(p.pos.x, W.water, p.pos.z, 1.5); RP.Audio.impact('water', p.pos, 1.5); } + if (g.y < W.water - SWIM_DEPTH) { startSwim(p); return; } // into deep water: no landing, no fall damage + if (h > TU.fallLethal) { takeDamage(p, 999, { fall: true }); return; } + if (h > TU.fallRagdoll) { takeDamage(p, (h - TU.fallRagdoll) * 9 + 15, { fall: true }); startRagdoll(p, new T.Vector3(0, -2, 0)); return; } + if (h > TU.fallStagger) { p.actor.move('hardLand'); setState(p, 'getup'); p.st = 0.35; takeDamage(p, (h - TU.fallStagger) * 4, { fall: true }); RP.Audio.thud(p.pos, 1); RP.Cam.shake(0.4); return; } + p.actor.move('land', { w: M.clamp(h / 2, 0.3, 1) }); + RP.Audio.step(p.gmat, p.pos, 1.6); + setState(p, 'move'); + } + } + + // ---- combat roll and dodge + function startRoll(p, dir) { + setState(p, 'roll'); p.rollDir = dir.clone().normalize(); p.rollCd = TU.rollCooldown + TU.rollTime; + p.actor.move('roll', { speed: 0.62 / TU.rollTime }); + p.reload = null; + RP.Audio.mech('swing', p.pos); + } + function startDodge(p, dir) { + setState(p, 'dodge'); p.rollDir = dir.clone().normalize(); p.dodgeCd = TU.dodgeCooldown + TU.dodgeTime; + p.counterT = TU.dodgeTime + 0.25; // an attack that misses during the dodge opens a counter + p.actor.move('dodge', { speed: 0.42 / TU.dodgeTime }); + } + function stepRoll(p, dt) { + var dur = p.state === 'roll' ? TU.rollTime : TU.dodgeTime, sp = p.state === 'roll' ? TU.rollSpeed : TU.dodgeSpeed; + var u = p.st / dur, k = u < 0.75 ? 1 : 1 - (u - 0.75) / 0.25 * 0.8; // recovery: slow down at the end + W.move(p.pos, p.rollDir.x * sp * k * dt, p.rollDir.z * sp * k * dt, p.radius, 1.0); + groundSnap(p, dt); + if (p.state === 'roll') p.yaw = M.approachAngle(p.yaw, Math.atan2(p.rollDir.x, p.rollDir.z), 12, dt); + p.speed = sp * k * 0.6; + if (u >= 1) { setState(p, 'move'); p.speed = p.state === 'roll' ? 1.5 : 0; } + } + + // ---- cover + function tryCover(p) { + var cy = camYaw(), best = null; + var wish = wishDir(_v); var wl = wish.length(); + // search a fan of directions, preferring the camera's forward and the stick direction + for (var i = 0; i < 16; i++) { + var a = cy + (i / 16) * Math.PI * 2, dir = fwdOf(a); + var pref = 1 - Math.abs(M.wrap(a - cy)) / Math.PI * 0.5 + (wl > 0.2 ? dir.dot(wish.clone().normalize()) * 0.4 : 0); + var l = W.near(p.pos.x, p.pos.z, 3.5, []); + for (var k = 0; k < l.length; k++) { + var b = l[k]; if (b.nocol || b.see && b.kind !== 'balustrade') continue; + var h = rayBoxH(b, p.pos.x, p.pos.y + 0.6, p.pos.z, dir.x, dir.z, 3.2); + if (!h) continue; + var hit = p.pos.clone().addScaledVector(dir, h.t); + var lx = W.toLocal(b, hit.x - h.nx * 0.05, hit.z - h.nz * 0.05, {}); + var top = W.topAt(b, M.clamp(lx.z, -b.hz, b.hz)) - p.pos.y; + if (top < 0.75) continue; + var score = pref - h.t * 0.35; + if (!best || score > best.score) best = { score: score, box: b, nx: h.nx, nz: h.nz, t: h.t, hit: hit, top: top }; + } + } + if (!best) { RP.emit('toast', 'No cover nearby'); return; } + var c = p.cover = { box: best.box, n: new T.Vector3(best.nx, 0, best.nz), low: best.top < 1.45, top: best.top, side: 1, edge: 0, enterFrom: p.pos.clone(), entering: true, out: 0, peek: 0, blind: false }; + c.target = best.hit.clone().addScaledVector(c.n, p.radius + 0.06); c.target.y = p.pos.y; + // face along the wall toward the camera's side + var t = new T.Vector3(-c.n.z, 0, c.n.x); // tangent (to the character's left when facing the wall) + c.side = t.dot(fwdOf(cy)) > 0 ? 1 : -1; + setState(p, 'cover'); p.sprinting = false; + c.dur = Math.max(0.18, best.t / 6.5); + RP.Audio.step(p.gmat, p.pos, 1.3); + } + P.tryCover = tryCover; + function stepCover(p, dt) { + var I = RP.In, c = p.cover, d = def(p); + if (c.entering) { + var u = Math.min(1, p.st / c.dur); + p.pos.x = M.lerp(c.enterFrom.x, c.target.x, M.smooth(u)); p.pos.z = M.lerp(c.enterFrom.z, c.target.z, M.smooth(u)); + p.speed = c.enterFrom.distanceTo(c.target) / c.dur * (1 - u); + p.yaw = M.approachAngle(p.yaw, Math.atan2(-c.n.x, -c.n.z), 14, dt); + groundSnap(p, dt); + if (u >= 1) { c.entering = false; if (u >= 1 && c.dur > 0.3) { p.actor.move('land', { w: 0.4 }); RP.Audio.impact('cloth', p.pos, 0.6); } } + return; + } + var tan = new T.Vector3(-c.n.z, 0, c.n.x); // +tan is the character's left when facing the wall + // stick: along the wall relative to the camera + var wish = wishDir(_v), along = wish.dot(tan), away = wish.dot(c.n); + var I2 = RP.In; + // just swung round a corner: finish turning the camera, and don't read the held stick as "leave" + if (c.camTurn) { var ct = c.camTurn * Math.min(1, dt * 6); if (Math.abs(c.camTurn) < 0.01) ct = c.camTurn; RP.Cam.yaw += ct; c.camTurn -= ct; } + if (c.swingT > 0) c.swingT -= dt; + // leave cover: Q, sprint away, or holding away from the wall + if (away > 0.6 && !(c.swingT > 0)) c.out += dt; else c.out = 0; + if (I2.pressed('cover') || c.out > 0.22 || (I2.down('sprint') && away > 0.3)) { exitCover(p); return; } + if (Math.abs(along) > 0.2) c.side = along > 0 ? 1 : -1; + // slide along the wall while there's wall behind the new spot + var sp = (c.low || p.stealth ? 1.5 : 1.9) * Math.min(1, Math.abs(along)); + var aimingOut = p.aiming && (c.low || c.edge); + if (aimingOut) sp = 0; + var step = tan.clone().multiplyScalar(Math.sign(along) * sp * dt); + var np = p.pos.clone().add(step); + var wall = coverCheck(p, np, c); + if (Math.abs(along) > 0.2 && sp > 0) { + if (wall) { W.move(p.pos, step.x, step.z, p.radius, 1.2); c.edge = 0; c.edgeT = 0; } + else { + c.edge = c.side; // at the end of the wall: can aim round it + c.edgeT = (c.edgeT || 0) + dt; + // keep pushing past the edge: a corner of the same box round the side -> swing round it + if (c.edgeT > 0.35) cornerSwing(p, c, tan); + } + } else if (!wall) c.edge = c.side; + p.speed = sp > 0 && wall ? sp : 0; p.moveDir = c.side > 0 ? Math.PI / 2 : -Math.PI / 2; + // facing: along the wall toward the side we look; when aiming, toward the aim + var faceWall = Math.atan2(-c.n.x, -c.n.z); + p.yaw = M.approachAngle(p.yaw, p.aiming ? camYaw() : faceWall + c.side * 0.5, 10, dt); + // pop out to aim: over low cover (stand), round the edge of high cover (lean out sideways) + var peekT = aimingOut ? 1 : 0; + c.peek = M.approach(c.peek, peekT, 6, dt); + if (!c.low && c.edge && c.peek > 0) { + var base = c.anchor || (c.anchor = p.pos.clone()); + p.pos.x = base.x + tan.x * c.edge * 0.55 * c.peek + c.n.x * 0.15 * c.peek; p.pos.z = base.z + tan.z * c.edge * 0.55 * c.peek + c.n.z * 0.15 * c.peek; + } else if (c.peek <= 0) c.anchor = null; + // blind fire: firing without aiming from cover + c.blind = I.down('fire') && !p.aiming && !d.melee && !d.throw; + groundSnap(p, dt); + if (I.pressed('jump') && c.low) { // vault over low cover + var n = c.n.clone().negate(); exitCover(p, true); traverseOrJump(p, n); + } + } + function coverCheck(p, np, c) { + // still wall behind the new position (a short ray into the wall at hip height) + var dir = c.n.clone().negate(); + var l = W.near(np.x, np.z, 1.5, []); + for (var i = 0; i < l.length; i++) { + var b = l[i]; if (b.nocol) continue; + var h = rayBoxH(b, np.x, p.pos.y + 0.6, np.z, dir.x, dir.z, 0.8); + if (h) { var lx = W.toLocal(b, np.x + dir.x * (h.t + 0.05), np.z + dir.z * (h.t + 0.05), {}); if (W.topAt(b, M.clamp(lx.z, -b.hz, b.hz)) - p.pos.y > 0.75) return b; } + } + return null; + } + function cornerSwing(p, c, tan) { + // try the side face round the corner: new normal = the tangent direction + var newN = tan.clone().multiplyScalar(c.side); + // a point just past the corner and half a metre along the side face, then a ray back toward that face + // (the old probe started ~1.5 m out with a 1.2 m ray, so it never reached the face and the swing never happened) + var from = p.pos.clone().addScaledVector(tan, c.side * 0.95).addScaledVector(c.n, -0.5); + var dir = newN.clone().negate(); + var l = W.near(from.x, from.z, 1.5, []); + for (var i = 0; i < l.length; i++) { + var b = l[i]; if (b.nocol) continue; + var h = rayBoxH(b, from.x, p.pos.y + 0.6, from.z, dir.x, dir.z, 1.6); + if (h) { + c.enterFrom = p.pos.clone(); c.target = from.clone().addScaledVector(dir, h.t - p.radius - 0.06); c.target.y = p.pos.y; + var oldFace = Math.atan2(-c.n.x, -c.n.z); + c.n = new T.Vector3(h.nx, 0, h.nz); c.entering = true; c.dur = 0.35; c.edge = 0; c.edgeT = 0; c.box = b; p.st = 0; + // the camera turns with you round the corner, so the stick held the same way keeps you moving along the new face + c.camTurn = M.wrap(Math.atan2(-c.n.x, -c.n.z) - oldFace); c.swingT = 0.8; + return true; + } + } + c.edgeT = 0; + return false; + } + function exitCover(p, quiet) { p.cover = null; setState(p, 'move'); if (!quiet) RP.Audio.step(p.gmat, p.pos, 0.8); } + + // ---- stealth takedown + P.takedownTarget = function (p) { + if (!p.stealth || p.state !== 'move' || def(p).cat === 'heavy') return null; + var best = null; + RP.G.guards.forEach(function (g) { + if (!g.alive || g.ko || g.aware > 0.7) return; + var to = g.pos.clone().sub(p.pos); if (Math.abs(to.y) > 0.6) return; to.y = 0; + var d = to.length(); if (d > 1.6) return; + var gf = fwdOf(g.yaw), behind = to.clone().normalize().dot(gf); // > 0: we're behind them + if (behind < 0.35) return; + if (!best || d < best.d) best = { g: g, d: d }; + }); + return best && best.g; + }; + function startTakedown(p, g) { + setState(p, 'takedown'); + p.takedown = { g: g }; + var gy = g.yaw; p.yaw = gy; + var tp = g.pos.clone().addScaledVector(fwdOf(gy), -0.42); p.tdFrom = p.pos.clone(); p.tdTo = tp; + p.actor.playFull('takedown', { fade: 0.15 }); + RP.AI.takenDown(g, p); + RP.Combat.noise(p.pos, 3, 'fight', p); + } + function stepTakedown(p, dt) { + var u = Math.min(1, p.st / 0.25); p.pos.lerpVectors(p.tdFrom, p.tdTo, M.smooth(u)); + p.speed = 0; + if (p.st > 2.5) { setState(p, 'move'); p.actor.stopFull(0.3); p.takedown = null; } + } + + // ---- weapons + function stepWeapon(p, dt) { + var I = RP.In, d = def(p), inv = p.inv[p.cur]; + p.fireHeld = I.down('fire'); + if (p.swap) return; + // takedown takes over the attack button when one is available + var td = P.takedownTarget(p); + p.tdTarget = td; + if (td && (I.pressed('fire') || I.pressed('reload') || I.pressed('melee'))) { startTakedown(p, td); return; } + if (d.melee) { + if (I.pressed('fire') || I.pressed('melee') || I.pressed('reload')) startMelee(p); + return; + } + // R with a full magazine (or nothing to load): melee with the gun + if (I.pressed('melee') || (I.pressed('reload') && (inv.mag >= d.mag || inv.reserve <= 0))) { if (p.state === 'move') startMelee(p, true); return; } + if (I.pressed('reload') && inv.mag < d.mag && inv.reserve > 0) startReload(p); + // reloading + if (p.reload) { + stepReload(p, dt); + // shell-by-shell and single loads can be interrupted by firing + if (p.reload && I.pressed('fire') && (p.reload.type === 'shell') && inv.mag > 0) { p.reload = null; p.actor.endMove('shellLoad'); } + else if (p.reload) return; + } + if (p.sprinting && I.down('fire')) { p.sprinting = false; } + var c = p.cover; + var canFire = !p.sprinting && (p.state === 'move' || p.state === 'air' || p.state === 'drive' || (p.state === 'cover' && !c.entering && (p.aiming ? c.peek > 0.7 || c.low && c.peek > 0.5 : c.blind))); + var trig = d.auto ? I.down('fire') : I.pressed('fire'); + if (trig && canFire && p.fireCd <= 0) { + if (inv.mag <= 0) { + RP.Audio.dry(p.pos); p.fireCd = 0.3; + if (inv.reserve > 0) startReload(p); + return; + } + shoot(p, d, inv); + } + } + var _o = new T.Vector3(), _dir = new T.Vector3(); + function shoot(p, d, inv) { + inv.mag--; p.fireCd = 60 / d.rpm; p.shots++; + if (!p.aiming) p.hipT = 1.2; // hip fire turns the body to the crosshair for a moment + // the sight line: from the camera through the crosshair, to whatever it meets + var aim = RP.Cam.aimRay(); + var aimPoint = RP.Cam.aimPoint(aim, 300); + // muzzle (from the model if held, else the chest) + var mz = p.model && p.model.userData.muzzle ? p.model.userData.muzzle.getWorldPosition(_o) : p.actor.chest(_o).add(new T.Vector3(0, 0.2, 0)); + var dir = _dir.subVectors(aimPoint, mz).normalize(); + // spread: hip/aimed, moving, stealth, bloom, blind fire + var c = p.cover, blind = c && c.blind && !p.aiming; + var spread = M.lerp(d.spread[0], d.spread[1], p.aimW) + p.bloom + Math.min(1.5, p.speed * 0.35) * (1 - p.aimW * 0.6); + if (p.stealth) spread *= 0.8; + if (blind) { spread = d.spread[0] * 2.2 + 3; if (c.low) dir.y += 0.04; } + if (p.state === 'air') spread += 3; + if (d.proj) { + var v = dir.clone().multiplyScalar(d.vel); if (d.proj === 'grenade') v.y += 3.5; + RP.Combat.throwProj(d.proj, p, mz.clone().addScaledVector(dir, 0.3), v, d); + RP.Combat.noise(p.pos, 60, 'shot', p); + } else { + var res = RP.Combat.fire(p, mz.clone(), dir, d, { spread: spread, suppressed: d.suppressed }); + if (res && res.ent) { p.hits++; RP.emit('hitmark', res.ent.alive ? 'hit' : 'kill'); } + } + // feedback + var big = d.dmg > 50 || d.pellets || d.cat === 'heavy'; + if (!d.suppressed || Math.random() < 0.3) RP.FX.muzzle(mz, dir, big && !d.suppressed); + RP.Audio.shot(d.snd, mz.clone(), { suppressed: d.suppressed }); + if (d.rtype !== 'shell' && d.rtype !== 'break' && d.rtype !== 'revolver' && !d.proj) RP.FX.shell(p.model ? p.model.userData.eject.getWorldPosition(new T.Vector3()) : mz, dir, new T.Vector3(-dir.z, 0, dir.x).negate()); + // recoil: the first rounds of a burst climb hard, then the muzzle settles into a smaller, weaving pattern + // (a learnable spray, not noise); a pause of a quarter second starts a new burst with a new weave + var nowT = RP.G.time || 0; + if (nowT - (p.lastShotT || -9) > 0.25) { p.burstN = 0; p.burstPh = Math.random() * 6.28; } + p.lastShotT = nowT; var bn = p.burstN++; + var kick = d.recoil[0] * (p.aiming ? 0.75 : 1) * (p.stealth ? 0.85 : 1) * (bn < 7 ? 1 : 0.5) * (0.85 + Math.random() * 0.3); + var side = (bn < 3 ? (Math.random() - 0.5) * 0.6 : Math.sin(bn * 0.57 + p.burstPh)) * d.recoil[1]; + p.recoilP += kick * D2R; p.recoilY += side * D2R; + RP.Cam.kick(kick * D2R, side * 0.5 * D2R); + p.bloom = Math.min(6, p.bloom + d.recoil[0] * 0.5); + p.actor.playUpper(p.aiming && /pistol/.test(d.cat) ? 'firePistol' : d.oneHand ? 'firePistol' : (p.stealth ? 'fireCrouch' : 'fire'), { fade: 0.03, speed: 1.4 }); + if (d.pump) { setTimeout(function () { RP.Audio.mech('pump', p.pos); }, 250); p.fireCd = Math.max(p.fireCd, d.pump); } + if (d.bolt) { setTimeout(function () { RP.Audio.mech('bolt', p.pos); }, 300); p.actor.playUpper('boltCycle', { fade: 0.1, speed: 1.2 }); } + if (inv.mag === 0 && inv.reserve > 0 && !d.proj) setTimeout(function () { if (p.cur === d.id && !p.reload && p.alive) startReload(p); }, 200); + if (d.proj && inv.reserve > 0) setTimeout(function () { if (p.cur === d.id && !p.reload) startReload(p); }, 300); + RP.emit('shot', p); + } + // reload: per type. Events are fractions of the reload time. + function startReload(p) { + var d = def(p), inv = p.inv[p.cur]; if (!d.mag || inv.mag >= d.mag || inv.reserve <= 0 || p.reload) return; + var r = p.reload = { type: d.rtype, t: 0, dur: d.reload, ev: 0, heavy: d.rtype === 'belt' }; + if (r.type === 'shell') { r.per = d.reload; p.actor.move('shellLoad', { speed: 0.48 / r.per }); } + else if (r.type === 'revolver') r.dur = d.reload; // the hands are driven by the actor's reload path (chars.js) + RP.emit('reload', p); + } + function stepReload(p, dt) { + var r = p.reload, d = def(p), inv = p.inv[p.cur]; + r.t += dt; + if (r.type === 'shell') { + if (r.t >= r.per) { + inv.mag++; inv.reserve--; RP.Audio.mech('shell', p.pos); r.t = 0; + if (inv.mag >= d.mag || inv.reserve <= 0) { p.reload = null; RP.Audio.mech('pump', p.pos); return; } + p.actor.move('shellLoad', { speed: 0.48 / r.per }); + } + return; + } + var u = r.t / r.dur; + var ev = [[0.2, r.type === 'revolver' ? 'open' : r.type === 'break' ? 'open' : 'magOut'], [0.62, r.type === 'revolver' ? 'shell' : r.type === 'break' ? 'shell' : 'magIn'], [0.85, r.type === 'mag' ? (d.cat === 'pistol' ? 'slide' : 'bolt') : 'close']]; + while (r.ev < ev.length && u >= ev[r.ev][0]) { RP.Audio.mech(ev[r.ev][1], p.pos); r.ev++; } + if (u >= 1) { + var need = d.mag - inv.mag, take = Math.min(need, inv.reserve); + inv.mag += take; inv.reserve -= take; p.reload = null; + } + } + P.reloadFrac = function (p) { var r = p.reload; if (!r) return 0; return r.type === 'shell' ? r.t / r.per : r.t / r.dur; }; + + // ---- melee: combos with fists, swings with weapons, gun butt with firearms + function startMelee(p, withGun) { + if (p.melee && p.melee.t < p.melee.def.dur * 0.62 / p.melee.speed) { p.melee.queued = true; return; } + var d = def(p), move, dmg, reach, knock = 1, speed = 1; + var I = RP.In; + // a target on the ground nearby: stomp + var down = null; + RP.G.guards.forEach(function (g) { if (g.alive && (g.down || g.actor.rag) && g.pos.distanceTo(p.pos) < 1.6) down = g; }); + if (withGun) { move = 'gunWhip'; dmg = 22; reach = 1.15; knock = 1.2; } + else if (d.unarmed) { + if (down) { move = 'stomp'; dmg = 26; reach = 1.4; } + else if (p.speed > 4.5) { move = 'runPunch'; dmg = 26; reach = 1.4; knock = 2.2; } + else if (p.aiming) { move = 'kick'; dmg = 24; reach = 1.35; knock = 1.8; } + else { + var seq = ['jab', 'cross', 'hook', 'uppercut']; + p.combo = p.comboT > 0 ? (p.combo + 1) % seq.length : 0; + move = seq[p.combo]; dmg = [12, 15, 20, 26][p.combo]; reach = 1.05; knock = p.combo === 3 ? 2.6 : p.combo === 2 ? 1.3 : 0.8; + } + } else if (d.move && RP.Chars.MOVES[d.move]) { move = d.move; dmg = d.dmg; reach = d.reach; knock = d.knock || 1; speed = d.speed || 1; } + else { withGun = true; move = 'gunWhip'; dmg = 22; reach = 1.15; knock = 1.2; } // a gun with no strike of its own: the butt + var md = RP.Chars.MOVES[move]; + p.melee = { move: move, def: md, t: 0, speed: speed, dmg: dmg, reach: reach, knock: knock, hit: false, blade: !!(d.id === 'knife' || d.id === 'machete'), weapon: d, withGun: !!withGun }; + p.actor.move(move, { speed: speed, side: 1 }); + p.guardT = 3; p.comboT = md.dur / speed + 0.45; + // soft lock: turn to the nearest enemy in front + var tgt = nearestEnemy(p, 3.2, 120); + if (tgt) p.yaw = Math.atan2(tgt.pos.x - p.pos.x, tgt.pos.z - p.pos.z); + p.melee.tgt = tgt && tgt.pos.distanceTo(p.pos) < 2 ? tgt : null; + // step in so the blow lands: close most of the gap beyond arm's length + if (tgt && move !== 'runPunch') { var gap = tgt.pos.distanceTo(p.pos) - 0.78; if (gap > 0.05 && gap < 1.6) p.lunge = Math.max(p.lunge || 0, Math.min(1, gap * 0.9)); } + if (move === 'runPunch') p.lunge = 1.6; + RP.Audio.mech('swing', p.pos); + } + function nearestEnemy(p, r, cone) { + var best = null, bd = r, f = fwdOf(p.yaw); + RP.G.guards.forEach(function (g) { + if (!g.alive) return; var to = g.pos.clone().sub(p.pos); to.y = 0; var d = to.length(); if (d > bd) return; + if (Math.acos(M.clamp(to.normalize().dot(f), -1, 1)) > cone * D2R / 2) return; + bd = d; best = g; + }); + return best; + } + P.nearestEnemy = nearestEnemy; + function stepMelee(p, dt) { + var m = p.melee; m.t += dt * m.speed; + var hw = m.def.hit; + // where the blow should land: the victim's head for punches (chest for a body shot), tracked while it flies + if (m.tgt && m.tgt.actor && !m.tgt.actor.rag) { p.actor.strikeAt = (p.actor.strikeAt || new T.Vector3()); (m.move === 'hook' || m.move === 'kick' || m.move === 'stab' ? m.tgt.actor.chest(p.actor.strikeAt) : m.tgt.actor.head(p.actor.strikeAt)); } + else p.actor.strikeAt = null; + if (p.lunge) { var k = Math.max(0, p.lunge); W.move(p.pos, Math.sin(p.yaw) * k * 4 * dt, Math.cos(p.yaw) * k * 4 * dt, p.radius, 1.7); p.lunge -= dt * 4; if (p.lunge <= 0) p.lunge = 0; } + if (hw && !m.hit && m.t >= hw[0] && m.t <= hw[1] + 0.02) { + var bonus = p.counterT > 0 && p.countered ? 2 : 1; + var e = RP.Combat.melee(p, m.reach, 100, m.dmg * bonus, { knock: m.knock * bonus, blade: m.blade, quiet: m.weapon.quiet, weapon: m.weapon }); + if (e) { m.hit = true; RP.Cam.shake(0.12 * m.knock); RP.G.hitstop = 0.05; RP.emit('hitmark', e.alive ? 'hit' : 'kill'); p.countered = false; } + } + if (m.t >= m.def.dur) { + var q = m.queued; p.melee = null; p.actor.strikeAt = null; + if (q) startMelee(p, m.withGun); + } + } + + // ---- throwing (G): the selected throwable; with a sticky charge out, G sets it off + function stepThrow(p, dt) { + var I = RP.In; + if (!I.pressed('throw')) return; + var id = p.throwId, inv = p.inv[id]; + if (id === 'sticky' && RP.Combat.detonateSticky(p)) { RP.Audio.ui('tick'); return; } + if (!inv || inv.reserve <= 0) { RP.emit('toast', 'No ' + (WP.DEFS[id] ? WP.DEFS[id].name.toLowerCase() + 's' : 'throwables') + ' left'); return; } + inv.reserve--; + p.actor.playUpper('throw', { fade: 0.08, speed: 1.6 }); + p.reload = null; + var d = WP.DEFS[id]; + setTimeout(function () { + if (!p.alive) return; + var aim = RP.Cam.aimRay(), hand = p.actor.bones.hand_r.getWorldPosition(new T.Vector3()); + var dir = aim.dir.clone(); dir.y += 0.28; dir.normalize(); + var v = dir.multiplyScalar(id === 'sticky' ? 13 : 15).add(p.vel.clone().multiplyScalar(0.5)); + RP.Combat.throwProj(id, p, hand, v, d); + RP.Audio.mech('pin', p.pos); + }, 380); + } + + // ------------------------------------------------------------------ damage, ragdoll, death + function takeDamage(p, amt, info) { + if (!p.alive || p.godT > 0) return; + if (p.state === 'roll' && info && info.bullet) amt *= 0.5; // rolling is harder to hit cleanly + if (info && info.from && info.from !== p && !info.fall) amt *= RP.diff().dmgTaken; + // a melee attack during a dodge misses and opens a counter + if (info && info.melee && p.state === 'dodge') { p.countered = true; p.counterT = 0.9; RP.emit('toast', 'Counter!'); return; } + if (p.armour > 0 && info && info.region === 'torso' && !info.fall) { var ab = Math.min(p.armour, amt * 0.66); p.armour -= ab; amt -= ab; } + p.hp -= amt; p.lastHit = RP.G.time; + RP.emit('hurt', p, info); + if (info && info.dir) p.actor.flinch(-info.dir.x, -info.dir.z, Math.min(1, amt / 25)); + if (RP.Cam) RP.Cam.shake(Math.min(0.5, amt / 60)); + if (p.hp <= 0) { p.hp = 0; die(p, info); return; } + // big hits knock you over + if (info && (info.explosion || (info.melee && info.force > 2.4) || info.car) && p.state !== 'ragdoll') startRagdoll(p, info.dir ? info.dir.clone().multiplyScalar(info.force || 4).setY(info.explosion ? 4 : 1.5) : null); + else if (info && info.melee && info.force > 1.2 && p.state === 'move') { p.actor.playFull('stagger', { fade: 0.08, speed: 1.4 }); p.speed = 0; } + } + P.tumble = function (p, imp) { startRagdoll(p, imp); }; + function startRagdoll(p, imp) { + if (p.cover) p.cover = null; + p.melee = null; p.reload = null; + p.actor._vel = p.vel.clone().add(fwdOf(p.yaw).multiplyScalar(p.speed)); + RP.Rag.start(p.actor, imp || new T.Vector3(), p.actor.chest()); + setState(p, 'ragdoll'); + RP.Audio.thud(p.pos, 1); + } + P.ragdoll = startRagdoll; + function stepRagdoll(p, dt) { + var rag = p.actor.rag; if (!rag) { setState(p, 'move'); return; } + p.pos.set(rag.p.pelvis.x, W.ground(rag.p.pelvis.x, rag.p.pelvis.z, rag.p.pelvis.y).y, rag.p.pelvis.z); + if (p.alive && RP.Rag.settled(p.actor)) { + var r = RP.Rag.release(p.actor); + p.pos.set(r.x, W.ground(r.x, r.z, p.pos.y + 1).y, r.z); p.yaw = r.yaw; + p.actor.root.position.copy(p.pos); p.actor.root.rotation.y = p.yaw; + p.actor.move('getUp'); setState(p, 'getup'); p.speed = 0; + } + } + function die(p, info) { + p.alive = false; p.cover = null; p.melee = null; + var imp = info && info.dir ? info.dir.clone().multiplyScalar(info.force || 2) : new T.Vector3(); + if (!p.actor.rag) { p.actor._vel = p.vel.clone(); RP.Rag.start(p.actor, imp, info && info.point, { dead: true }); } + setState(p, 'dead'); + RP.emit('playerDead', p); + } + function stepDead(p, dt) { if (p.actor.rag) { var r = p.actor.rag.p.pelvis; p.pos.set(r.x, r.y, r.z); } } + + // ------------------------------------------------------------------ footsteps (sound + noise for the AI) + function footsteps(p, dt) { + if (p.state !== 'move' && p.state !== 'cover') return; + if (p.speed < 0.4) return; + p.stepAcc = (p.stepAcc || 0) + dt * p.speed / (p.speed > 5 ? 1.7 : p.speed > 2.5 ? 1.4 : 0.85); + if (p.stepAcc >= 1) { + p.stepAcc -= 1; + RP.Audio.step(p.gmat, p.pos, p.stealth ? 0.35 : p.speed > 5 ? 1.3 : 1); + if (p.noise > 0) RP.Combat.noise(p.pos, p.noise, 'step', p); + } + } + + // ------------------------------------------------------------------ per rendered frame: pose + // the long gun you are not holding hangs on its sling across your back (rifle first, then SMG, shotgun, sniper) + function backGun(p) { + var order = ['rifle', 'smg', 'shotgun', 'sniper', 'heavy']; + for (var i = 0; i < order.length; i++) { var id = RP.Items.slotOf(p, order[i]); if (id && id !== p.cur && !(p.swap && !p.swap.drawn && p.swap.to === id)) return id; } + return null; + } + P.frame = function (p, dt) { + var a = p.actor, d = def(p); + a.setBack(backGun(p)); + a.root.position.copy(p.pos); a.root.rotation.y = p.yaw; + if (p.state === 'dead' || p.state === 'ragdoll') { a.update(dt); return; } + if (p.state === 'swim') { + // breaststroke when moving (body tipped forward, arms and legs sweeping), treading water when still + var sw = M.clamp(p.speed / 1.7, 0, 1); + a.setUpper(null, 0.2); a.weaponAim = 0; a.reloadU = -1; a.airborne = true; + if (!a.moveOf('swim')) a.move('swim', { stack: true }); + var mv = a.moveOf('swim'); mv.w = 1; mv.speed = 0.8 + sw * 0.6; mv.pitch = sw; + a.drive({ speed: 0, dir: 0, strafe: 0, stealth: 0, sprint: 0, turnRate: 0, accel: 0 }); + a.setAim(0, 0); a.update(dt); + return; + } + if (a.moveOf('swim')) a.endMove('swim'); + if (p.state === 'drive' && p.vehicle) { + // at the wheel: seated, hands on the wheel; a one-handed gun comes up over the door when aimed or fired + var shooting = p.aiming || p.hipT > 0; + a.setUpper(shooting && p.model ? 'aimPistol' : null, 0.15); + a.weaponAim = shooting ? 1 : 0; a.weaponPitch = RP.Cam.pitch; a.reloadU = -1; a.airborne = true; a.setBack(null); + a.drive({ speed: 0, dir: 0, strafe: 0, stealth: 0, sprint: 0, turnRate: 0, accel: 0 }); + a.setAim(shooting ? RP.Cam.pitch : 0, shooting ? M.clamp(M.wrap(RP.Cam.yaw - p.yaw), -1.5, 1.5) : M.clamp(M.wrap(RP.Cam.yaw - p.yaw), -1, 1) * 0.4); + a.update(dt); RP.Vehicles.pose(p); + return; + } + var aimingPose = p.aiming || p.hipT > 0 || (p.cover && (p.cover.peek > 0.3 || p.cover.blind)); + // upper body: held weapon pose, aim pose, fight guard, cover lean + var up = null, cv = p.cover && !p.cover.entering; + var long = p.model && !p.model.userData.oneHand, pistol = p.model && p.model.userData.oneHand && !d.melee && !d.throw; + if (d.melee) up = null; + else if (aimingPose) up = long ? (p.stealth || (cv && p.cover.low && p.cover.peek < 0.5) ? 'crouchAim' : 'aimIdle') : 'aimPistol'; + else if (p.sprinting) up = long ? 'sprintRifle' : null; + else up = long ? 'holdRifle' : pistol ? 'holdPistol' : null; + if (p.swap && !p.swap.drawn) up = null; + a.setUpper(up, 0.18); + // fist fight guard stance + var fighting = d.unarmed && (p.guardT > 0 || p.aiming); + if (fighting && !a.moveOf('guard')) a.move('guard', { stack: true, w: 1 }); + if (!fighting && a.moveOf('guard')) a.endMove('guard'); + // cover body: low cover crouched; high cover stand pressed to the wall; blind fire + var stealthW = p.stealth ? 1 : 0; + if (cv) { + if (p.cover.low) stealthW = 1 - p.cover.peek; + if (p.cover.blind && !a.moveOf('blindFire')) a.move('blindFire', { stack: true }); + } + if (!(cv && p.cover.blind) && a.moveOf('blindFire')) a.endMove('blindFire'); + a.weaponAim = aimingPose ? 1 : 0; a.weaponPitch = RP.Cam.pitch; + a.reloadU = p.reload && !p.swap ? (p.reload.type === 'shell' ? p.reload.t / p.reload.per : p.reload.t / p.reload.dur) : -1; + a.airborne = p.state === 'air' || p.state === 'vault' || p.state === 'climb' || p.state === 'roll'; + // braking: letting go of the stick at a run plants a foot and leans back + var moving = p.speed > 3.2 && p.state === 'move'; + if (p._wasFast && p.state === 'move' && p.accel < -6 && p.speed < 3 && !a.moveOf('brake') && !p.melee) a.move('brake', { stack: true }); + p._wasFast = moving; + a.drive({ speed: p.speed, dir: p.moveDir || 0, strafe: (p.aiming || p.hipT > 0 || cv || fighting) ? 1 : 0, stealth: stealthW, + sprint: p.sprinting ? 1 : 0, turnRate: p.turnRate || 0, accel: p.accel || 0 }); + // aim offsets: pitch from the camera, yaw from the gap between body and crosshair + if (aimingPose || fighting) a.setAim(RP.Cam.pitch + (p.recoilP || 0) * 0.5, M.clamp(M.wrap(RP.Cam.yaw - p.yaw), -0.9, 0.9) * (aimingPose ? 1 : 0.3)); + else a.setAim(RP.Cam.pitch * 0.35, M.clamp(M.wrap(RP.Cam.yaw - p.yaw), -1, 1) * 0.35); // head follows the camera a little + a.update(dt); + if (RP.Cam.fp && !RP.Cam.scoped && !aimingPose && !fighting && !p.melee && !p.reload) fpArms(p, a); + }; + // first person: the run and sprint clips pump the hands up to face height, right in front of the eye; keep them + // below the chest (arm IK onto the same point, lowered) so the view stays clear. Aiming, fighting and reloads are left alone. + var _fh = new T.Vector3(), _fc = new T.Vector3(), _fp = new T.Vector3(), _ff = new T.Vector3(); + function fpArms(p, a) { + var b = a.bones; if (!b.hand_l || !RP.Chars.ikPole) return; + a.chest(_fc); _ff.set(Math.sin(p.yaw), 0, Math.cos(p.yaw)); + var lim = _fc.y - 0.12; + ['l', 'r'].forEach(function (sd) { + var hand = b['hand_' + sd]; hand.getWorldPosition(_fh); + var ahead = (_fh.x - _fc.x) * _ff.x + (_fh.z - _fc.z) * _ff.z; + if (_fh.y <= lim || ahead < 0.05) return; + _fh.y = lim - Math.min(0.12, (_fh.y - lim) * 0.5); // down, keeping some of the swing + _fh.addScaledVector(_ff, -Math.min(0.12, ahead * 0.4)); // and a little back toward the body + b['upperarm_' + sd].getWorldPosition(_fp); + _fp.add(_ff.clone().multiplyScalar(-0.3)); _fp.y -= 0.4; _fp.x += (sd === 'l' ? 1 : -1) * Math.cos(p.yaw) * 0.25; _fp.z -= (sd === 'l' ? 1 : -1) * Math.sin(p.yaw) * 0.25; + RP.Chars.ikPole(b['upperarm_' + sd], b['lowerarm_' + sd], hand, _fh, _fp, 1); + }); + } +})(); diff --git a/e63334287a3deaa3/blacktie/js/ragdoll.js b/e63334287a3deaa3/blacktie/js/ragdoll.js new file mode 100644 index 00000000..1d335664 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/ragdoll.js @@ -0,0 +1,174 @@ +/* + * Ragdolls (RP.Rag): a Verlet particle body on the character's joints (pelvis, chest, head, shoulders, elbows, + * hands, hips, knees, feet, toes) held by distance constraints with cross-braces for the torso, colliding with the + * ground and the world's boxes. The skeleton is posed from the particles each frame by swinging each bone from its + * pose at the moment the ragdoll started. Used for deaths, explosions, car hits, strong melee and big falls; a living + * character gets up again (RP.Rag.release blends the bones back into animation). + * No physics library: the Verlet step is a few dozen lines and plenty for a body falling over on stairs and walls. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W; + var Rg = RP.Rag = { list: [] }; + var J = ['pelvis', 'chest', 'head', 'shL', 'elL', 'haL', 'shR', 'elR', 'haR', 'hiL', 'knL', 'ftL', 'toL', 'hiR', 'knR', 'ftR', 'toR']; + var SRC = { pelvis: 'pelvis', chest: 'spine_03', head: 'Head', shL: 'upperarm_l', elL: 'lowerarm_l', haL: 'hand_l', shR: 'upperarm_r', elR: 'lowerarm_r', haR: 'hand_r', + hiL: 'thigh_l', knL: 'calf_l', ftL: 'foot_l', toL: 'ball_l', hiR: 'thigh_r', knR: 'calf_r', ftR: 'foot_r', toR: 'ball_r' }; + var LINKS = [['pelvis', 'chest'], ['chest', 'head'], ['chest', 'shL'], ['chest', 'shR'], ['shL', 'shR'], ['shL', 'elL'], ['elL', 'haL'], ['shR', 'elR'], ['elR', 'haR'], + ['pelvis', 'hiL'], ['pelvis', 'hiR'], ['hiL', 'hiR'], ['hiL', 'knL'], ['knL', 'ftL'], ['ftL', 'toL'], ['hiR', 'knR'], ['knR', 'ftR'], ['ftR', 'toR'], + // braces (keep the torso rigid) + ['hiL', 'shL'], ['hiR', 'shR'], ['hiL', 'shR'], ['hiR', 'shL'], ['hiL', 'chest'], ['hiR', 'chest'], ['pelvis', 'shL'], ['pelvis', 'shR'], ['head', 'shL'], ['head', 'shR'], + ['knL', 'toL'], ['knR', 'toR']]; + var MINL = [['hiL', 'ftL', 0.32], ['hiR', 'ftR', 0.32], ['shL', 'haL', 0.2], ['shR', 'haR', 0.2], ['head', 'pelvis', 0.45], ['knL', 'knR', 0.12], ['ftL', 'ftR', 0.1]]; + // bone -> [joint at its origin, joint it points to] + var SWING = [['upperarm_l', 'shL', 'elL'], ['lowerarm_l', 'elL', 'haL'], ['upperarm_r', 'shR', 'elR'], ['lowerarm_r', 'elR', 'haR'], + ['thigh_l', 'hiL', 'knL'], ['calf_l', 'knL', 'ftL'], ['foot_l', 'ftL', 'toL'], ['thigh_r', 'hiR', 'knR'], ['calf_r', 'knR', 'ftR'], ['foot_r', 'ftR', 'toR'], ['neck_01', 'chest', 'head']]; + var _v = new T.Vector3(), _v2 = new T.Vector3(), _q = new T.Quaternion(), _q2 = new T.Quaternion(), _m = new T.Matrix4(); + + function frame(a, b, c, out) { // orthonormal basis: up = a->b, right = c (left-right), as a quaternion + var up = _v.subVectors(b, a).normalize(), rt = _v2.copy(c).normalize(); + var fw = new T.Vector3().crossVectors(rt, up).normalize(); rt.crossVectors(up, fw).normalize(); + _m.makeBasis(rt, up, fw); return out.setFromRotationMatrix(_m); + } + Rg.start = function (actor, impulse, at, opts) { + if (actor.rag) { Rg.push(actor, impulse, at); return actor.rag; } + actor.root.updateMatrixWorld(true); + var b = actor.bones, rag = { actor: actor, p: {}, o: {}, q0: {}, d0: {}, t: 0, still: 0, alive: !(opts && opts.dead), frozen: false }; + J.forEach(function (j) { + var bn = b[SRC[j]], p = bn.getWorldPosition(new T.Vector3()); + if (j === 'head') p.addScaledVector(new T.Vector3(0, 1, 0).applyQuaternion(actor.root.quaternion), 0.1); + rag.p[j] = p; rag.o[j] = p.clone().sub(actor._vel ? actor._vel.clone().multiplyScalar(1 / 60) : new T.Vector3()); + }); + rag.len = LINKS.map(function (l) { return rag.p[l[0]].distanceTo(rag.p[l[1]]); }); + // start pose: world rotations and swing directions + for (var k in b) rag.q0[k] = b[k].getWorldQuaternion(new T.Quaternion()); + SWING.forEach(function (s) { rag.d0[s[0]] = rag.p[s[2]].clone().sub(rag.p[s[1]]).normalize(); }); + rag.fPel0 = frame(rag.p.pelvis, rag.p.chest, rag.p.hiL.clone().sub(rag.p.hiR), new T.Quaternion()); + rag.fChe0 = frame(rag.p.pelvis, rag.p.chest, rag.p.shL.clone().sub(rag.p.shR), new T.Quaternion()); + rag.root0 = actor.root.position.clone(); + actor.rag = rag; + actor.mixer.stopAllAction(); actor.nodes = {}; actor.upper = []; actor.fulls = []; actor.moves = []; actor._upperName = undefined; + Rg.push(actor, impulse, at); + Rg.list.push(rag); + rag.pose = function (a) { pose(rag, a); }; + return rag; + }; + // add velocity (m/s) to the joints, most near the point `at` + Rg.push = function (actor, imp, at) { + var rag = actor.rag; if (!rag || !imp) return; + J.forEach(function (j) { + var k = at ? Math.max(0.25, 1 - rag.p[j].distanceTo(at) / 1.2) : 1; + rag.o[j].addScaledVector(imp, -k / 60); + }); + }; + var _nb = []; + function collide(p, o) { + var g = W.ground(p.x, p.z, p.y + 0.3, 0.6); + var floor = g.y + 0.06; + if (p.y < floor) { + p.y = floor; + // friction: kill most horizontal motion on contact + o.x = p.x - (p.x - o.x) * 0.55; o.z = p.z - (p.z - o.z) * 0.55; if (o.y < p.y) o.y = p.y + (p.y - o.y) * 0.2; + } + var l = W.near(p.x, p.z, 0.4, _nb), loc = { x: 0, z: 0 }; + for (var i = 0; i < l.length; i++) { + var b = l[i]; if (b.nocol || p.y > W.topAt(b, 0) + 0.06 || p.y < b.y0) continue; + W.toLocal(b, p.x, p.z, loc); + var r = 0.08, ex = b.hx + r - Math.abs(loc.x), ez = b.hz + r - Math.abs(loc.z), top = W.topAt(b, loc.z); + if (ex <= 0 || ez <= 0) continue; + var ey = top + 0.06 - p.y; + if (ey < ex && ey < ez && ey < 0.4) { p.y = top + 0.06; continue; } + var w = { x: 0, z: 0 }; + if (ex < ez) W.toWorldDir(b, Math.sign(loc.x) * ex, 0, w); else W.toWorldDir(b, 0, Math.sign(loc.z) * ez, w); + p.x += w.x; p.z += w.z; + } + } + function step(rag, dt) { + var g = RP.TUNING.gravity * 0.75 * dt * dt, k, p, o, vx, vy, vz; + var moving = 0; + for (var i = 0; i < J.length; i++) { + k = J[i]; p = rag.p[k]; o = rag.o[k]; + vx = (p.x - o.x) * 0.995; vy = (p.y - o.y) * 0.995; vz = (p.z - o.z) * 0.995; + o.copy(p); p.x += vx; p.y += vy - g; p.z += vz; + moving += vx * vx + vy * vy + vz * vz; + } + for (var it = 0; it < 6; it++) { + for (i = 0; i < LINKS.length; i++) { + var a = rag.p[LINKS[i][0]], b = rag.p[LINKS[i][1]], L0 = rag.len[i]; + _v.subVectors(b, a); var L = _v.length() || 1e-4, diff = (L - L0) / L * 0.5; + var wa = LINKS[i][0] === 'pelvis' || LINKS[i][0] === 'chest' ? 0.6 : 0.5; + a.addScaledVector(_v, diff * 2 * wa); b.addScaledVector(_v, -diff * 2 * (1 - wa)); + } + for (i = 0; i < MINL.length; i++) { + a = rag.p[MINL[i][0]]; b = rag.p[MINL[i][1]]; + _v.subVectors(b, a); L = _v.length() || 1e-4; + if (L < MINL[i][2]) { diff = (L - MINL[i][2]) / L * 0.5; a.addScaledVector(_v, diff); b.addScaledVector(_v, -diff); } + } + for (i = 0; i < J.length; i++) collide(rag.p[J[i]], rag.o[J[i]]); + } + rag.still = moving < 1e-6 * J.length ? rag.still + dt : 0; + } + function setWorldQuat(bone, q) { + var pq = bone.parent.getWorldQuaternion(_q2); + bone.quaternion.copy(pq.invert().multiply(q)); + bone.updateMatrixWorld(true); + } + function pose(rag, a) { + var b = a.bones, p = rag.p; + // the root follows the pelvis on the ground so culling, LOD and the shadow stay with the body + a.root.position.set(p.pelvis.x, W.ground(p.pelvis.x, p.pelvis.z, p.pelvis.y).y, p.pelvis.z); + a.root.updateMatrixWorld(true); + // pelvis: position + full rotation from the hip frame + var fP = frame(p.pelvis, p.chest, p.hiL.clone().sub(p.hiR), new T.Quaternion()); + var rotP = fP.clone().multiply(rag.fPel0.clone().invert()); + b.pelvis.position.copy(b.pelvis.parent.worldToLocal(p.pelvis.clone())); + setWorldQuat(b.pelvis, rotP.clone().multiply(rag.q0.pelvis)); + var fC = frame(p.pelvis, p.chest, p.shL.clone().sub(p.shR), new T.Quaternion()); + var rotC = fC.clone().multiply(rag.fChe0.clone().invert()); + ['spine_01', 'spine_02'].forEach(function (n, i) { var r = rotP.clone().slerp(rotC, (i + 1) / 3); setWorldQuat(b[n], r.multiply(rag.q0[n])); }); + setWorldQuat(b.spine_03, rotC.clone().multiply(rag.q0.spine_03)); + ['clavicle_l', 'clavicle_r'].forEach(function (n) { if (b[n]) setWorldQuat(b[n], rotC.clone().multiply(rag.q0[n])); }); + for (var i = 0; i < SWING.length; i++) { + var s = SWING[i], bn = b[s[0]]; if (!bn) continue; + var d = _v.subVectors(p[s[2]], p[s[1]]).normalize(); + // the swing is applied on top of the parent's change, so use the bone's start direction carried by its parent + var par = s[0].indexOf('upperarm') === 0 ? rotC : s[0].indexOf('thigh') === 0 ? rotP : s[0] === 'neck_01' ? rotC : null; + var d0 = rag.d0[s[0]].clone(); + var base = rag.q0[s[0]].clone(); + if (par) { d0.applyQuaternion(par); base.premultiply(par); } + else { + // child of a swung bone: its start direction moves with the parent's swing + var pn = bn.parent.name, pq = bn.parent.getWorldQuaternion(new T.Quaternion()), pq0 = rag.q0[pn]; + var rel = pq.clone().multiply(pq0.clone().invert()); + d0.applyQuaternion(rel); base.premultiply(rel); + } + _q.setFromUnitVectors(d0, d); + setWorldQuat(bn, _q.multiply(base)); + if (s[0] === 'neck_01' && b.Head) setWorldQuat(b.Head, b.neck_01.getWorldQuaternion(new T.Quaternion()).multiply(rag.q0.neck_01.clone().invert()).multiply(rag.q0.Head)); + } + } + // blend a living character back into animation (call when it should get up) + Rg.release = function (actor) { + var rag = actor.rag; if (!rag) return; + var snap = {}; for (var k in actor.bones) snap[k] = actor.bones[k].quaternion.clone(); + var pelPos = actor.bones.pelvis.position.clone(); + // face along the body (from feet to head) so the get-up turns the right way + var dir = rag.p.chest.clone().sub(rag.p.pelvis); dir.y = 0; + var face = Math.atan2(dir.x, dir.z); + actor.rag = null; + Rg.list = Rg.list.filter(function (r) { return r !== rag; }); + actor._blendFrom = snap; actor._blendPel = pelPos; actor._blendT = 0.55; actor._blendMax = 0.55; + return { yaw: face, x: rag.p.pelvis.x, z: rag.p.pelvis.z }; + }; + Rg.update = function (dt) { + for (var i = 0; i < Rg.list.length; i++) { + var r = Rg.list[i]; r.t += dt; + if (r.frozen) continue; + var sub = dt > 0.02 ? 2 : 1; + for (var s = 0; s < sub; s++) step(r, dt / sub); + // a dead body that has stopped is frozen (no more work) + if (!r.alive && r.still > 1.2) r.frozen = true; + if (r.t > 12 && !r.alive) r.frozen = true; + } + }; + Rg.settled = function (actor) { return actor.rag && (actor.rag.still > 0.5 || actor.rag.t > 3.5) && actor.rag.t > 0.8; }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/render.js b/e63334287a3deaa3/blacktie/js/render.js new file mode 100644 index 00000000..fe8a1f84 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/render.js @@ -0,0 +1,478 @@ +/* + * Rendering: renderer, quality presets, sky and sun, environment light, the post stack (bloom, SSAO on High, + * ACES tone mapping, colour grade, vignette) and the code-made textures every map uses (RP.tex, RP.mat). + * + * The page runs three.js r187 through the site's r128 compatibility layer (/lib/three/README.md): colour management + * off, light colours as in r128. So every authored hex colour goes through RP.col() (sRGB -> linear) and colour + * textures are tagged sRGB. There is exactly one place that tone maps: the composite pass on Medium/High, or the + * renderer itself on Low. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M; + + var Q = RP.QUALITY = { + // pixel ratio cap, canvas AA, shadow map, post, msaa, ssao, bloom, sea detail, draw distance, char LOD (mid, far), foliage density + low: { pr: 0.85, aa: false, shadow: 0, post: false, msaa: 0, ssao: false, sea: 0, far: 420, lod: [8, 22], fol: 0.45, decals: 40, particles: 0.5 }, + medium: { pr: 1.0, aa: true, shadow: 1024, post: true, msaa: 0, ssao: false, sea: 1, far: 650, lod: [10, 28], fol: 0.75, decals: 90, particles: 0.8 }, + high: { pr: 1.5, aa: true, shadow: 2048, post: true, msaa: 4, ssao: true, sea: 2, far: 900, lod: [14, 40], fol: 1.0, decals: 160, particles: 1 } + }; + + var R = RP.R = { q: null, qname: null, sunDir: new T.Vector3(0.4, 0.6, 0.6).normalize(), atmos: null, frame: 0, stats: { calls: 0, tris: 0 } }; + + // ------------------------------------------------------------------ renderer + R.init = function (canvas) { + var name = RP.settings.quality, qm = /[?&]q=(low|medium|high)/.exec(location.search); + if (qm) name = qm[1]; + if (!Q[name]) name = RP.touch ? 'low' : 'medium'; + R.qname = name; R.q = Q[name]; + var r = R.renderer = new T.WebGLRenderer({ canvas: canvas, antialias: R.q.aa, powerPreference: 'high-performance', stencil: false, preserveDrawingBuffer: !!RP.test }); + r.setPixelRatio(Math.min(window.devicePixelRatio || 1, R.q.pr)); + r.outputEncoding = T.sRGBEncoding; + r.toneMapping = T.ACESFilmicToneMapping; + r.toneMappingExposure = 1.0; + r.shadowMap.enabled = R.q.shadow > 0; + r.shadowMap.type = T.PCFSoftShadowMap; + r.info.autoReset = false; + R.scene = new T.Scene(); + R.camera = new T.PerspectiveCamera(RP.TUNING.camFov, 1, 0.08, R.q.far); + R.scene.add(R.camera); + // sun + sky fill + var sun = R.sun = new T.DirectionalLight(0xffffff, 2.4); + sun.castShadow = R.q.shadow > 0; + if (sun.castShadow) { + sun.shadow.mapSize.set(R.q.shadow, R.q.shadow); + var c = sun.shadow.camera; c.left = -34; c.right = 34; c.top = 34; c.bottom = -34; c.near = 1; c.far = 260; + sun.shadow.bias = -0.00035; sun.shadow.normalBias = 0.035; + } + R.scene.add(sun); R.scene.add(sun.target); + R.hemi = new T.HemisphereLight(0xbfd8ff, 0x8a7a62, 0.55); + R.scene.add(R.hemi); + R.fog = R.scene.fog = new T.FogExp2(0xc9d6e0, 0.0021); + buildSky(); + R.pmrem = new T.PMREMGenerator(r); + if (R.q.post) buildPost(); + R.resize(); + window.addEventListener('resize', R.resize); + }; + + R.setQuality = function (name) { + // a quality change rebuilds shaders and targets: the simplest correct way is a reload with the new setting + RP.settings.quality = name; RP.saveSettings(); + location.reload(); + }; + + R.resize = function () { + var w = window.innerWidth, h = window.innerHeight; + R.renderer.setSize(w, h, false); + R.camera.aspect = w / h; R.camera.updateProjectionMatrix(); + if (R.post) R.post.size(); + }; + + // ------------------------------------------------------------------ sky (one GLSL function shared with the sea) + R.SKY_GLSL = [ + 'uniform vec3 uSunDir; uniform vec3 uZenith; uniform vec3 uHorizon; uniform vec3 uSunCol; uniform vec3 uGround; uniform float uHaze;', + 'vec3 skyCol(vec3 d){', + ' float y = d.y;', + ' float h = pow(1.0 - clamp(y, 0.0, 1.0), 4.0);', + ' vec3 c = mix(uZenith, uHorizon, h);', + ' float sd = max(dot(d, uSunDir), 0.0);', + ' c += uSunCol * (pow(sd, 6.0) * 0.28 * uHaze + pow(sd, 64.0) * 0.6);', // Mie glow round the sun + ' c += uSunCol * smoothstep(0.9993, 0.99965, sd) * 14.0;', // the disc (HDR, blooms) + ' c = mix(c, uGround, smoothstep(0.0, -0.08, y));', + ' return c;', + '}' + ].join('\n'); + + function buildSky() { + R.skyU = { + uSunDir: { value: R.sunDir.clone() }, uZenith: { value: new T.Color() }, uHorizon: { value: new T.Color() }, + uSunCol: { value: new T.Color() }, uGround: { value: new T.Color() }, uHaze: { value: 1 } + }; + var mat = new T.ShaderMaterial({ + uniforms: R.skyU, side: T.BackSide, depthWrite: false, fog: false, toneMapped: true, + vertexShader: 'varying vec3 vD; void main(){ vD = normalize(position); vec4 p = modelViewMatrix*vec4(position,1.0); gl_Position = projectionMatrix*p; gl_Position.z = gl_Position.w*0.99999; }', + fragmentShader: R.SKY_GLSL + '\nvarying vec3 vD;\nvoid main(){ gl_FragColor = vec4(skyCol(normalize(vD)), 1.0);\n#include \n#include \n}' + }); + var g = new T.SphereGeometry(1, 32, 16); + R.sky = new T.Mesh(g, mat); + R.sky.scale.setScalar(1000); R.sky.frustumCulled = false; R.sky.renderOrder = -10; + R.scene.add(R.sky); + } + + // atmosphere presets: colours authored in sRGB + R.ATMOS = { + afternoon: { sun: [0.55, 0.42, 0.62], sunCol: '#fff0d6', sunI: 2.6, zenith: '#3f7fd1', horizon: '#cfe0ee', ground: '#6d7b86', + hemiSky: '#d2e0f5', hemiGround: '#b89b78', hemiI: 0.95, fog: '#c3d3e2', fogD: 0.0017, haze: 1, exposure: 0.82, + grade: { sat: 1.14, warm: 0.04, cool: 0.04, lift: 0.008, contrast: 1.08 } }, + golden: { sun: [-0.62, 0.2, 0.56], sunCol: '#ffc98e', sunI: 2.5, zenith: '#4a78bf', horizon: '#f3d2ad', ground: '#6b6058', + hemiSky: '#d6dbe8', hemiGround: '#c29a72', hemiI: 0.95, fog: '#e9cfb2', fogD: 0.0022, haze: 1.5, exposure: 1.02, + grade: { sat: 1.12, warm: 0.08, cool: 0.05, lift: 0.015, contrast: 1.06 } }, + // dusk: the sun is just above the sea in the west, most of the town is in the hills' shadow, so the sky does the + // lighting: a strong lavender-to-peach fill from above, warm bounce from below, lamps and windows carry the rest + dusk: { sun: [-0.74, 0.17, 0.44], sunCol: '#ffb27c', sunI: 2.3, zenith: '#34508f', horizon: '#f4ad82', ground: '#5a4c52', + hemiSky: '#c3c0e6', hemiGround: '#b98a66', hemiI: 1.75, fog: '#c7a9a2', fogD: 0.0019, haze: 2, exposure: 1.42, + grade: { sat: 1.12, warm: 0.07, cool: 0.07, lift: 0.022, contrast: 1.04 } } + }; + + R.setAtmos = function (name) { + var a = R.ATMOS[name] || R.ATMOS.afternoon; R.atmos = a; R.atmosName = name; + R.sunDir.set(a.sun[0], a.sun[1], a.sun[2]).normalize(); + var u = R.skyU; + u.uSunDir.value.copy(R.sunDir); + u.uZenith.value.copy(RP.col(a.zenith)); u.uHorizon.value.copy(RP.col(a.horizon)); + u.uSunCol.value.copy(RP.col(a.sunCol)); u.uGround.value.copy(RP.col(a.ground)); u.uHaze.value = a.haze; + R.sun.color.copy(RP.col(a.sunCol)); R.sun.intensity = a.sunI; + R.hemi.color.copy(RP.col(a.hemiSky)); R.hemi.groundColor.copy(RP.col(a.hemiGround)); R.hemi.intensity = a.hemiI; + R.fog.color.copy(RP.col(a.fog)); R.fog.density = a.fogD; + R.renderer.toneMappingExposure = a.exposure; + if (R.post) R.post.setGrade(a.grade, a.exposure); + // environment map from the sky alone (reflections on glass, sea, metal, wet stone) + var envScene = new T.Scene(); + var sky2 = new T.Mesh(R.sky.geometry, R.sky.material.clone()); sky2.material.uniforms = R.skyU; sky2.scale.setScalar(100); + // the sky material tone maps for the screen; the env map wants linear HDR, which a render target gives (r187 skips tone mapping off-screen) + envScene.add(sky2); + if (R.envRT) R.envRT.dispose(); + R.envRT = R.pmrem.fromScene(envScene, 0.02); + R.scene.environment = R.envRT.texture; + if (RP.Sea) RP.Sea.atmos(); + }; + + // sun shadow camera follows a point, snapped to shadow texels so edges don't swim + var _sv = new T.Vector3(); + R.followSun = function (p) { + var s = R.sun, d = 120; + if (s.castShadow) { + var size = (s.shadow.camera.right - s.shadow.camera.left) / R.q.shadow; + // snap in light space: project onto two axes perpendicular to the sun + var ax = _sv.set(-R.sunDir.z, 0, R.sunDir.x).normalize(); + var ay = new T.Vector3().crossVectors(R.sunDir, ax).normalize(); + var a = Math.round(p.dot(ax) / size) * size, b = Math.round(p.dot(ay) / size) * size, c = p.dot(R.sunDir); + var q = ax.clone().multiplyScalar(a).add(ay.multiplyScalar(b)).add(R.sunDir.clone().multiplyScalar(c)); + s.target.position.copy(q); + } else s.target.position.copy(p); + s.position.copy(s.target.position).addScaledVector(R.sunDir, d); + s.target.updateMatrixWorld(); + R.sky.position.copy(R.camera.position); + }; + + // ------------------------------------------------------------------ post stack + var FSV = 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }'; + function fsMat(frag, uniforms) { + return new T.ShaderMaterial({ uniforms: uniforms, vertexShader: FSV, fragmentShader: frag, depthTest: false, depthWrite: false, toneMapped: false }); + } + function buildPost() { + var P = R.post = {}; + var tri = new T.BufferGeometry(); + tri.setAttribute('position', new T.Float32BufferAttribute([-1, -1, 0, 3, -1, 0, -1, 3, 0], 3)); + tri.setAttribute('uv', new T.Float32BufferAttribute([0, 0, 2, 0, 0, 2], 2)); + P.cam = new T.OrthographicCamera(-1, 1, 1, -1, 0, 1); + P.quad = new T.Mesh(tri); P.quad.frustumCulled = false; + P.scene = new T.Scene(); P.scene.add(P.quad); + var opt = { type: T.HalfFloatType, depthBuffer: true }; + P.rt = new T.WebGLRenderTarget(4, 4, opt); + if (R.q.msaa) P.rt.samples = R.q.msaa; + if (R.q.ssao) { P.rt.depthTexture = new T.DepthTexture(4, 4); P.rt.depthTexture.type = T.UnsignedIntType; } + // bloom: bright pass then a dual-filter blur pyramid (down 1/2..1/16, back up) + P.levels = []; + for (var i = 0; i < 4; i++) P.levels.push(new T.WebGLRenderTarget(4, 4, { type: T.HalfFloatType, depthBuffer: false })); + P.ups = []; + for (i = 0; i < 3; i++) P.ups.push(new T.WebGLRenderTarget(4, 4, { type: T.HalfFloatType, depthBuffer: false })); + P.bright = fsMat([ + 'uniform sampler2D tSrc; uniform vec2 uTexel; uniform float uThresh; varying vec2 vUv;', + 'vec3 s(vec2 o){ vec3 c = texture2D(tSrc, vUv + o*uTexel).rgb; float l = max(c.r, max(c.g, c.b)); return c * smoothstep(uThresh, uThresh*1.8, l); }', + 'void main(){ vec3 c = s(vec2(-1.,-1.)) + s(vec2(1.,-1.)) + s(vec2(-1.,1.)) + s(vec2(1.,1.)); gl_FragColor = vec4(min(c*0.25, vec3(40.0)), 1.0); }' + ].join('\n'), { tSrc: { value: null }, uTexel: { value: new T.Vector2() }, uThresh: { value: 1.6 } }); + P.down = fsMat([ + 'uniform sampler2D tSrc; uniform vec2 uTexel; varying vec2 vUv;', + 'void main(){ vec3 c = texture2D(tSrc, vUv).rgb*4.0;', + ' c += texture2D(tSrc, vUv + uTexel*vec2(-1.,-1.)).rgb + texture2D(tSrc, vUv + uTexel*vec2(1.,-1.)).rgb;', + ' c += texture2D(tSrc, vUv + uTexel*vec2(-1.,1.)).rgb + texture2D(tSrc, vUv + uTexel*vec2(1.,1.)).rgb;', + ' gl_FragColor = vec4(c/8.0, 1.0); }' + ].join('\n'), { tSrc: { value: null }, uTexel: { value: new T.Vector2() } }); + P.up = fsMat([ + 'uniform sampler2D tSrc; uniform sampler2D tAdd; uniform vec2 uTexel; varying vec2 vUv;', + 'void main(){ vec3 c = vec3(0.0);', + ' c += texture2D(tSrc, vUv + uTexel*vec2(-2.,0.)).rgb + texture2D(tSrc, vUv + uTexel*vec2(2.,0.)).rgb;', + ' c += texture2D(tSrc, vUv + uTexel*vec2(0.,-2.)).rgb + texture2D(tSrc, vUv + uTexel*vec2(0.,2.)).rgb;', + ' c += (texture2D(tSrc, vUv + uTexel*vec2(-1.,-1.)).rgb + texture2D(tSrc, vUv + uTexel*vec2(1.,-1.)).rgb + texture2D(tSrc, vUv + uTexel*vec2(-1.,1.)).rgb + texture2D(tSrc, vUv + uTexel*vec2(1.,1.)).rgb)*2.0;', + ' gl_FragColor = vec4(c/12.0 + texture2D(tAdd, vUv).rgb, 1.0); }' + ].join('\n'), { tSrc: { value: null }, tAdd: { value: null }, uTexel: { value: new T.Vector2() } }); + if (R.q.ssao) { + P.aoRT = new T.WebGLRenderTarget(4, 4, { depthBuffer: false }); + P.ao = fsMat([ + 'uniform sampler2D tDepth; uniform mat4 uProjInv; uniform vec2 uTexel; uniform float uNear; uniform float uFar; uniform mat4 uProj; varying vec2 vUv;', + 'vec3 vpos(vec2 uv){ float d = texture2D(tDepth, uv).x; vec4 p = uProjInv * vec4(uv*2.0-1.0, d*2.0-1.0, 1.0); return p.xyz/p.w; }', + 'void main(){', + ' vec3 P0 = vpos(vUv); if (-P0.z > 140.0) { gl_FragColor = vec4(1.0); return; }', + ' vec3 N = normalize(cross(dFdx(P0), dFdy(P0)));', + ' float occ = 0.0; float R0 = 0.55; float ang = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898,78.233)))*43758.5453)*6.2831;', + ' for (int i = 0; i < 10; i++) {', + ' float fi = float(i); float r = R0 * (0.15 + 0.85*fract(fi*0.618 + 0.13));', + ' float a = ang + fi*2.399; vec3 dir = vec3(cos(a), sin(a), 0.6 + 0.4*fract(fi*0.37));', + ' vec3 t = normalize(cross(N, vec3(0.0,1.0,0.3))); vec3 b = cross(N, t);', + ' vec3 S = P0 + (t*dir.x + b*dir.y)*r*0.8 + N*dir.z*r;', + ' vec4 c = uProj * vec4(S, 1.0); vec2 suv = c.xy/c.w*0.5+0.5;', + ' float sz = vpos(suv).z;', + ' float rng = smoothstep(0.0, 1.0, R0 / abs(P0.z - sz));', + ' occ += (sz >= S.z + 0.03 ? 1.0 : 0.0) * rng;', + ' }', + ' float ao = 1.0 - occ/10.0; gl_FragColor = vec4(vec3(clamp(ao*1.15, 0.0, 1.0)), 1.0);', + '}' + ].join('\n'), { tDepth: { value: null }, uProjInv: { value: new T.Matrix4() }, uProj: { value: new T.Matrix4() }, uTexel: { value: new T.Vector2() }, uNear: { value: 0.1 }, uFar: { value: 900 } }); + P.ao.extensions = { derivatives: true }; + } + P.comp = fsMat([ + 'uniform sampler2D tScene; uniform sampler2D tBloom; uniform sampler2D tAO; uniform float uAO; uniform vec2 uTexel;', + 'uniform vec2 uPx; uniform float uSharp; uniform float uGrain; uniform float uExposure; uniform float uSat; uniform float uWarm; uniform float uCool; uniform float uLift; uniform float uContrast; uniform float uBloom; uniform float uTime; uniform float uVig; uniform vec3 uFlash;', + 'varying vec2 vUv;', + 'vec3 aces(vec3 x){ x *= 0.6; return clamp((x*(2.51*x+0.03))/(x*(2.43*x+0.59)+0.14), 0.0, 1.0); }', + '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;', + // unsharp mask on flat-ish areas only (edges already have contrast), before anything else touches the colour + ' { vec3 bl = (texture2D(tScene, vUv + vec2(uPx.x, 0.)).rgb + texture2D(tScene, vUv - vec2(uPx.x, 0.)).rgb + texture2D(tScene, vUv + vec2(0., uPx.y)).rgb + texture2D(tScene, vUv - vec2(0., uPx.y)).rgb) * 0.25;', + ' vec3 dd = c - bl; float ct = length(dd); c += dd * uSharp * (1.0 - smoothstep(0.05, 0.3, ct)); c = max(c, 0.0); }', + ' if (uAO > 0.0) { vec2 o = uTexel*1.5; float ao = (texture2D(tAO, vUv).r*2.0 + texture2D(tAO, vUv+vec2(o.x,0.)).r + texture2D(tAO, vUv-vec2(o.x,0.)).r + texture2D(tAO, vUv+vec2(0.,o.y)).r + texture2D(tAO, vUv-vec2(0.,o.y)).r)/6.0; c *= mix(1.0, ao, uAO); }', + ' c += texture2D(tBloom, vUv).rgb * uBloom;', + ' c += uFlash;', + ' c = aces(c * uExposure * 1.65);', + ' float l = dot(c, vec3(0.2126, 0.7152, 0.0722));', + ' c = mix(vec3(l), c, uSat);', + ' c += vec3(uWarm, uWarm*0.45, -uWarm*0.3) * smoothstep(0.35, 1.0, l);', // warm highlights + ' c += vec3(-uCool*0.4, uCool*0.05, uCool) * (1.0 - smoothstep(0.0, 0.4, l)) * 0.5;', // cool shadows + ' c = (c - 0.5) * uContrast + 0.5; c = clamp(c, 0.0, 1.0); c = mix(c, c*c*(3.0 - 2.0*c), 0.18); c = c + uLift * (1.0 - c);', // contrast, a gentle S-curve, lifted blacks + ' vec2 q = vUv - 0.5; c *= 1.0 - uVig * dot(q, q) * 1.6;', + ' c = toSRGB(clamp(c, 0.0, 1.0));', + ' { float n = fract(sin(dot(gl_FragCoord.xy * 0.7 + uTime * 3.1, vec2(41.3, 289.1))) * 1731.7) - 0.5; float ll = dot(c, vec3(0.299, 0.587, 0.114)); c += n * uGrain * (1.0 - 0.7 * smoothstep(0.25, 0.9, ll)); }', // film grain, strongest in the mid-darks + ' c += (fract(sin(dot(gl_FragCoord.xy + uTime, vec2(12.9898, 78.233)))*43758.5453) - 0.5) * (1.5/255.0);', // dither + ' gl_FragColor = vec4(c, 1.0);', + '}' + ].join('\n'), { + tScene: { value: null }, tBloom: { value: null }, tAO: { value: null }, uAO: { value: 0 }, uTexel: { value: new T.Vector2() }, + uExposure: { value: 1 }, uSat: { value: 1 }, uWarm: { value: 0 }, uCool: { value: 0 }, uLift: { value: 0 }, uContrast: { value: 1 }, + uBloom: { value: 0.4 }, uPx: { value: new T.Vector2(1 / 1280, 1 / 720) }, uSharp: { value: 0.28 }, uGrain: { value: 0.022 }, uTime: { value: 0 }, uVig: { value: 0.35 }, uFlash: { value: new T.Vector3() } + }); + P.size = function () { + var r = R.renderer, v = r.getDrawingBufferSize(new T.Vector2()), w = Math.max(4, v.x), h = Math.max(4, v.y); + P.rt.setSize(w, h); + var lw = w, lh = h; + for (var i = 0; i < P.levels.length; i++) { lw = Math.max(2, lw >> 1); lh = Math.max(2, lh >> 1); P.levels[i].setSize(lw, lh); if (i < 3) P.ups[i].setSize(lw, lh); } + if (P.aoRT) P.aoRT.setSize(Math.max(4, w >> 1), Math.max(4, h >> 1)); + P.w = w; P.h = h; P.comp.uniforms.uPx.value.set(1 / w, 1 / h); + }; + P.setGrade = function (g, exp) { + var u = P.comp.uniforms; u.uSat.value = g.sat; u.uWarm.value = g.warm; u.uCool.value = g.cool; u.uLift.value = g.lift; u.uContrast.value = g.contrast; u.uExposure.value = exp; + }; + P.pass = function (mat, target) { P.quad.material = mat; R.renderer.setRenderTarget(target); R.renderer.render(P.scene, P.cam); }; + } + + R.flash = new T.Vector3(); // additive screen flash (explosions), decays in draw + R.draw = function (dt) { + var r = R.renderer, P = R.post; + r.info.reset(); + R.frame++; + R.flash.multiplyScalar(Math.exp(-dt * 9)); + if (!P) { + r.setRenderTarget(null); + r.render(R.scene, R.camera); + } else { + r.setRenderTarget(P.rt); r.clear(); r.render(R.scene, R.camera); + // bloom pyramid + var src = P.rt.texture, i; + P.bright.uniforms.tSrc.value = src; P.bright.uniforms.uTexel.value.set(1 / P.w, 1 / P.h); + P.pass(P.bright, P.levels[0]); + for (i = 1; i < P.levels.length; i++) { + P.down.uniforms.tSrc.value = P.levels[i - 1].texture; + P.down.uniforms.uTexel.value.set(1 / P.levels[i - 1].width, 1 / P.levels[i - 1].height); + P.pass(P.down, P.levels[i]); + } + var prev = P.levels[3]; + for (i = 2; i >= 0; i--) { + P.up.uniforms.tSrc.value = prev.texture; P.up.uniforms.tAdd.value = P.levels[i].texture; + P.up.uniforms.uTexel.value.set(1 / prev.width, 1 / prev.height); + P.pass(P.up, P.ups[i]); prev = P.ups[i]; + } + var cu = P.comp.uniforms; + if (P.ao) { + var au = P.ao.uniforms; + au.tDepth.value = P.rt.depthTexture; au.uProjInv.value.copy(R.camera.projectionMatrixInverse); au.uProj.value.copy(R.camera.projectionMatrix); + P.pass(P.ao, P.aoRT); + cu.tAO.value = P.aoRT.texture; cu.uAO.value = 0.85; cu.uTexel.value.set(1 / P.aoRT.width, 1 / P.aoRT.height); + } + cu.tScene.value = P.rt.texture; cu.tBloom.value = prev.texture; cu.uTime.value = (R.frame % 97); + cu.uFlash.value.copy(R.flash); + P.pass(P.comp, null); + } + R.stats.calls = r.info.render.calls; R.stats.tris = r.info.render.triangles; + }; + + // Draw one frame with every hidden effect shown, so shaders compile behind the loading screen, not mid-fight. + R.warm = function () { + var hidden = []; + R.scene.traverse(function (o) { if (!o.visible) { hidden.push(o); o.visible = true; } }); + try { R.renderer.compile(R.scene, R.camera); R.draw(0); } catch (e) { console.warn(e); } + hidden.forEach(function (o) { o.visible = false; }); + }; + + // ------------------------------------------------------------------ code-made textures (RP.tex) + // Each returns a CanvasTexture tiled in metres by the map's UVs. Height maps become normal maps by finite differences. + var TEX = RP.tex = {}; + function canvas(n) { var c = document.createElement('canvas'); c.width = c.height = n; return c; } + function tex(c, srgb) { + var t = new T.CanvasTexture(c); + t.wrapS = t.wrapT = T.RepeatWrapping; t.anisotropy = 4; + if (srgb) t.encoding = T.sRGBEncoding; + t.needsUpdate = true; return t; + } + function normalFrom(h, n, strength) { + var c = canvas(n), x = c.getContext('2d'), img = x.createImageData(n, n), d = img.data; + for (var j = 0; j < n; j++) for (var i = 0; i < n; i++) { + var l = h[j * n + ((i - 1 + n) % n)], r = h[j * n + ((i + 1) % n)], u = h[((j - 1 + n) % n) * n + i], b = h[((j + 1) % n) * n + i]; + var nx = (l - r) * strength, ny = (u - b) * strength, nz = 1, il = 1 / Math.sqrt(nx * nx + ny * ny + 1); + var o = (j * n + i) * 4; + d[o] = (nx * il * 0.5 + 0.5) * 255; d[o + 1] = (ny * il * 0.5 + 0.5) * 255; d[o + 2] = nz * il * 255; d[o + 3] = 255; + } + x.putImageData(img, 0, 0); return tex(c, false); + } + // tileable value noise on an n x n canvas at a given period + function tnoise(n, period, seed) { + var g = new Float32Array(period * period), rnd = M.rng(seed), out = new Float32Array(n * n); + for (var i = 0; i < g.length; i++) g[i] = rnd(); + for (var y = 0; y < n; y++) for (var x = 0; x < n; x++) { + var fx = x / n * period, fy = y / n * period, xi = Math.floor(fx), yi = Math.floor(fy), tx = fx - xi, ty = fy - yi; + tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty); + var a = g[(yi % period) * period + xi % period], b = g[(yi % period) * period + (xi + 1) % period]; + var c = g[((yi + 1) % period) * period + xi % period], d = g[((yi + 1) % period) * period + (xi + 1) % period]; + out[y * n + x] = (a + (b - a) * tx) * (1 - ty) + (c + (d - c) * tx) * ty; + } + return out; + } + function fbmT(n, seed, periods, amps) { + var out = new Float32Array(n * n); + for (var k = 0; k < periods.length; k++) { var t = tnoise(n, periods[k], seed + k * 17); for (var i = 0; i < out.length; i++) out[i] += t[i] * amps[k]; } + return out; + } + function paint(n, fn) { + var c = canvas(n), x = c.getContext('2d'), img = x.createImageData(n, n), d = img.data; + for (var j = 0; j < n; j++) for (var i = 0; i < n; i++) { var o = (j * n + i) * 4, v = fn(i, j); d[o] = v[0]; d[o + 1] = v[1]; d[o + 2] = v[2]; d[o + 3] = v[3] == null ? 255 : v[3]; } + x.putImageData(img, 0, 0); return c; + } + + RP.buildTextures = function () { + var N = R.qname === 'low' ? 256 : 512; + // stucco / lime plaster: soft blotches, fine grain, a few hairline cracks; near white so vertex colours tint it + var h = fbmT(N, 11, [4, 9, 23, 61], [0.45, 0.3, 0.17, 0.08]); + TEX.stucco = tex(paint(N, function (i, j) { var v = h[j * N + i]; var g = 205 + (v - 0.5) * 70; return [g + 6, g + 3, g - 4]; }), true); + TEX.stuccoN = normalFrom(h, N, 2.2); + // ashlar stone (cathedral, parapets, harbour wall): coursed blocks with mortar + var hs = fbmT(N, 23, [8, 32, 90], [0.5, 0.35, 0.15]); + var st = new Float32Array(N * N); + TEX.stone = tex(paint(N, function (i, j) { + var row = Math.floor(j / (N / 4)), bx = (i + (row % 2) * N / 6) % (N / 3), by = j % (N / 4); + var m = (bx < 3 || by < 3) ? 1 : 0, v = hs[j * N + i], tone = M.hash2(row, Math.floor((i + (row % 2) * N / 6) / (N / 3))); + st[j * N + i] = m ? 0 : 0.6 + v * 0.4; + var g = m ? 150 : 178 + (v - 0.5) * 50 + tone * 26; + return [g + 10, g + 4, g - 8]; + }), true); + TEX.stoneN = normalFrom(st, N, 3); + // basalt-grey paving slabs (piazza, lanes) + var hp = fbmT(N, 31, [6, 24, 80], [0.5, 0.35, 0.15]), pv = new Float32Array(N * N); + TEX.paving = tex(paint(N, function (i, j) { + var s = N / 4, rx = Math.floor(j / s), bx = (i + (rx % 2) * s / 2) % s, by = j % s; + var gap = bx < 2 || by < 2, v = hp[j * N + i], tone = M.hash2(rx, Math.floor((i + (rx % 2) * s / 2) / s)); + pv[j * N + i] = gap ? 0 : 0.7 + v * 0.3; + var g = gap ? 70 : 128 + (v - 0.5) * 40 + (tone - 0.5) * 30; + return [g, g - 1, g - 4]; + }), true); + TEX.pavingN = normalFrom(pv, N, 2.5); + // asphalt for the coast road + var ha = fbmT(N, 41, [16, 64, 128], [0.4, 0.35, 0.25]); + TEX.asphalt = tex(paint(N, function (i, j) { var v = ha[j * N + i]; var g = 62 + (v - 0.5) * 34; return [g, g, g + 2]; }), true); + TEX.asphaltN = normalFrom(ha, N, 1.2); + // terracotta barrel tiles (coppi), running down the roof slope (v) + TEX.roof = tex(paint(N, function (i, j) { + var u = (i / N * 8) % 1, ridge = Math.sin(u * Math.PI), course = (j / N * 10) % 1, n = M.hash2(Math.floor(i / N * 8), Math.floor(j / N * 10)); + var g = 0.6 + ridge * 0.4 - (course > 0.92 ? 0.25 : 0); + return [(170 + n * 40) * g, (88 + n * 18) * g, (58 + n * 10) * g]; + }), true); + // majolica: yellow and green glazed tiles in a diamond pattern (the domes and the bell tower top) + TEX.majolica = tex(paint(N, function (i, j) { + var u = i / N * 16, v = j / N * 16, a = (Math.floor(u) + Math.floor(v)) % 2, fu = u % 1, fv = v % 1; + var edge = fu < 0.06 || fv < 0.06, dia = Math.abs(fu - 0.5) + Math.abs(fv - 0.5) < 0.28; + if (edge) return [210, 205, 190]; + if (dia) return a ? [30, 110, 72] : [235, 186, 40]; + return a ? [235, 186, 40] : [24, 112, 82]; + }), true); + // limestone cliff rock: banded strata + noise + var hr = fbmT(N, 53, [3, 8, 21, 55], [0.45, 0.3, 0.17, 0.08]); + TEX.rock = tex(paint(N, function (i, j) { var v = hr[j * N + i], band = Math.sin(j / N * 40 + v * 6) * 0.5 + 0.5; var g = 150 + (v - 0.5) * 90 + band * 18; return [g + 8, g + 2, g - 10]; }), true); + TEX.rockN = normalFrom(hr, N, 4); + // scrub / grass ground + var hg = fbmT(N, 61, [5, 17, 48, 120], [0.4, 0.3, 0.2, 0.1]); + TEX.ground = tex(paint(N, function (i, j) { var v = hg[j * N + i]; return [90 + v * 60, 100 + v * 50, 48 + v * 22]; }), true); + // wood planks (boats, pergolas, doors) + var hw = fbmT(N, 71, [2, 40, 120], [0.3, 0.5, 0.2]); + TEX.wood = tex(paint(N, function (i, j) { var v = hw[j * N + i], plank = (j % (N / 8)) < 2 ? 0.55 : 1; var g = (120 + v * 70) * plank; return [g, g * 0.72, g * 0.48]; }), true); + // sand + var hsd = fbmT(N, 81, [12, 40, 128], [0.4, 0.4, 0.2]); + TEX.sand = tex(paint(N, function (i, j) { var v = hsd[j * N + i]; var g = 170 + (v - 0.5) * 40; return [g + 12, g, g - 30]; }), true); + // leaves: an alpha card of overlapping leaf blobs (trees, lemon groves, bougainvillea), tinted by vertex colour + // (about 1100 leaves of 2-6 cm on a 2-3 m card: real leaf size, light and shade varying leaf to leaf) + var lc = canvas(512), lx = lc.getContext('2d'), rr = M.rng(5); + for (var k = 0; k < 1500; k++) { + var x0 = 256 + (rr() - 0.5) * 452, y0 = 256 + (rr() - 0.5) * 452, rd = (x0 - 256) * (x0 - 256) + (y0 - 256) * (y0 - 256); + if (rd > 222 * 222 || (rd > 170 * 170 && rr() < 0.55)) continue; // a ragged edge, not a disc + var gg = 105 + rr() * 140; lx.fillStyle = 'rgb(' + (gg * 0.9 | 0) + ',' + (gg | 0) + ',' + (gg * 0.74 | 0) + ')'; + lx.beginPath(); lx.ellipse(x0, y0, 4 + rr() * 6, 2 + rr() * 3, rr() * 3.14, 0, 6.29); lx.fill(); + if (rr() < 0.5) { lx.fillStyle = 'rgba(255,255,235,0.25)'; lx.beginPath(); lx.ellipse(x0 - 1, y0 - 1, 2 + rr() * 2, 1, rr() * 3.14, 0, 6.29); lx.fill(); } // a glint + } + TEX.leaves = tex(lc, true); TEX.leaves.wrapS = TEX.leaves.wrapT = T.ClampToEdgeWrapping; + // soft round blob (contact shadows, smoke, dust) + var bc = canvas(64), bx2 = bc.getContext('2d'), gr = bx2.createRadialGradient(32, 32, 0, 32, 32, 32); + gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.5, 'rgba(255,255,255,0.5)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); + bx2.fillStyle = gr; bx2.fillRect(0, 0, 64, 64); + TEX.blob = tex(bc, false); TEX.blob.wrapS = TEX.blob.wrapT = T.ClampToEdgeWrapping; + // bullet hole / scorch decal + var dc = canvas(64), dx = dc.getContext('2d'), dg = dx.createRadialGradient(32, 32, 0, 32, 32, 30); + dg.addColorStop(0, 'rgba(20,18,16,1)'); dg.addColorStop(0.18, 'rgba(40,36,32,0.95)'); dg.addColorStop(0.3, 'rgba(90,84,76,0.6)'); dg.addColorStop(1, 'rgba(120,110,100,0)'); + dx.fillStyle = dg; dx.fillRect(0, 0, 64, 64); + TEX.hole = tex(dc, true); TEX.hole.wrapS = TEX.hole.wrapT = T.ClampToEdgeWrapping; + }; + + // ------------------------------------------------------------------ materials (RP.mat) + RP.buildMaterials = function () { + var X = RP.tex, low = R.qname === 'low'; + function std(o) { var m = new T.MeshStandardMaterial(o); return m; } + RP.mat = { + stucco: std({ map: X.stucco, normalMap: low ? null : X.stuccoN, vertexColors: true, roughness: 0.92, metalness: 0 }), + stone: std({ map: X.stone, normalMap: low ? null : X.stoneN, vertexColors: true, roughness: 0.85 }), + paving: std({ map: X.paving, normalMap: low ? null : X.pavingN, roughness: 0.78, vertexColors: true }), + asphalt: std({ map: X.asphalt, normalMap: low ? null : X.asphaltN, roughness: 0.9, vertexColors: true }), + roof: std({ map: X.roof, roughness: 0.8, vertexColors: true }), + majolica: std({ map: X.majolica, roughness: 0.22, metalness: 0.05, vertexColors: true }), + wood: std({ map: X.wood, roughness: 0.75, vertexColors: true }), + paint: std({ roughness: 0.55, vertexColors: true }), // shutters, doors, railings (colour per vertex) + metal: std({ roughness: 0.35, metalness: 0.85, vertexColors: true }), + glass: std({ color: RP.col('#1d2a33'), roughness: 0.05, metalness: 0.9, envMapIntensity: 1.3 }), + dark: std({ color: RP.col('#16120f'), roughness: 1 }), // window and door openings + sand: std({ map: X.sand, roughness: 0.95, vertexColors: true }), + leaves: std({ map: X.leaves, alphaTest: 0.45, side: T.DoubleSide, roughness: 0.8 }), + bark: std({ roughness: 0.95 }), + fabric: std({ roughness: 0.9, vertexColors: true, side: T.DoubleSide }), + lamp: new T.MeshBasicMaterial({ color: new T.Color(6, 4.6, 2.6), toneMapped: true }), // HDR: blooms + gold: std({ color: RP.col('#c9a24a'), roughness: 0.3, metalness: 1, vertexColors: false }) + }; + // leaves: a gentle wind sway in the vertex shader (world-space phase, so neighbouring trees move together) + RP.windU = { value: 0 }; + RP.mat.leaves.onBeforeCompile = function (sh) { + sh.uniforms.uWind = RP.windU; + sh.vertexShader = 'uniform float uWind;\n' + sh.vertexShader.replace('#include ', + '#include \n vec4 wp0 = modelMatrix * vec4(position, 1.0); float sw = sin(uWind*1.7 + wp0.x*0.31 + wp0.z*0.23) + 0.5*sin(uWind*3.1 + wp0.x*0.9);\n transformed.x += sw * 0.045 * max(position.y, 0.0) * 0.3; transformed.z += sw * 0.03 * max(position.y, 0.0) * 0.3;'); + // the clump's normals point out from its centre (build.js): use them as they are on both sides of each card, so + // a crown shades like a round mass instead of a set of flat panels (one of them always facing away, black) + sh.fragmentShader = sh.fragmentShader.replace('#include ', '#include \n normal = normalize(vNormal);'); + }; + RP.mat.leaves.customProgramCacheKey = function () { return 'leaves2'; }; + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/sea.js b/e63334287a3deaa3/blacktie/js/sea.js new file mode 100644 index 00000000..6e328ca5 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/sea.js @@ -0,0 +1,128 @@ +/* + * The sea (RP.Sea): a grid that follows the camera, Gerstner swell in the vertex shader (Medium/High), ripple normals + * from summed waves in the fragment shader, Fresnel reflection of the same sky function the sky dome uses, a sun glint, + * colour by depth (turquoise over the shallows, deep blue offshore) from a texture of the terrain heights, and foam + * where the water meets the shore. One function (RP.Sea.height) gives the swell height for floating things. + * RP.Sea.update runs every frame, so it also drives the map's chunk streaming (RP.B.stream). + */ +(function () { + 'use strict'; + var T = THREE, R = RP.R; + var S = RP.Sea = {}; + var WAVES = [ // direction x, z, wavelength m, amplitude m, speed factor + [0.8, 0.6, 38, 0.22, 1], [0.3, 0.95, 21, 0.13, 1.1], [-0.5, 0.86, 13, 0.07, 1.25], [0.95, -0.3, 8, 0.035, 1.4] + ]; + S.height = function (x, z, t) { + if (!R.q || R.q.sea === 0) return 0; + var y = 0; + for (var i = 0; i < WAVES.length; i++) { + var w = WAVES[i], k = 2 * Math.PI / w[2], c = Math.sqrt(9.8 / k), l = Math.hypot(w[0], w[1]); + y += w[3] * Math.sin(k * ((w[0] * x + w[1] * z) / l) - c * k * t * 0.25); + } + return y; + }; + S.build = function (hf) { + var q = R.q.sea, seg = q === 2 ? 220 : q === 1 ? 150 : 80; + // a square grid that is fine under the camera and stretches toward the horizon (6 km across), so the far coast + // of the long map still has sea in front of it + var g = new T.PlaneGeometry(2, 2, seg, seg); g.rotateX(-Math.PI / 2); + var gp = g.attributes.position, INNER = 420, OUTER = 3000; + for (var gi = 0; gi < gp.count; gi++) { + var ux = gp.getX(gi), uz = gp.getZ(gi); + gp.setX(gi, ux * INNER + ux * ux * ux * (OUTER - INNER)); gp.setZ(gi, uz * INNER + uz * uz * uz * (OUTER - INNER)); + } + // pack the terrain heights into a float texture for the depth colour + var tex = null; + if (hf) { + var data = new Float32Array(hf.nx * hf.nz); + for (var i = 0; i < data.length; i++) data[i] = hf.h[i]; + tex = new T.DataTexture(data, hf.nx, hf.nz, T.RedFormat, T.FloatType); + tex.magFilter = tex.minFilter = T.LinearFilter; tex.needsUpdate = true; + } + var u = T.UniformsUtils.merge([T.UniformsLib.fog, { + uTime: { value: 0 }, tDepth: { value: tex }, uHF: { value: new T.Vector4(hf.x0, hf.z0, hf.nx * hf.cell, hf.nz * hf.cell) }, + uDeep: { value: RP.col('#0b3a5a') }, uShallow: { value: RP.col('#2bb3b0') }, uSwell: { value: q > 0 ? 1 : 0 } + }]); + for (var k in R.skyU) u[k] = R.skyU[k]; + var wv = WAVES.map(function (w) { return 'vec4(' + w.slice(0, 4).map(function (n) { return n.toFixed(3); }).join(',') + ')'; }); + var mat = S.mat = new T.ShaderMaterial({ + uniforms: u, fog: true, transparent: true, depthWrite: true, + vertexShader: [ + 'uniform float uTime; uniform float uSwell; varying vec3 vW; varying float vH;', + '#include ', + 'const vec4 WV[4] = vec4[4](' + wv.join(',') + ');', + 'void main(){', + ' vec4 w = modelMatrix * vec4(position, 1.0); vec3 p = w.xyz; float h = 0.0;', + ' for (int i = 0; i < 4; i++) { vec4 q = WV[i]; float k = 6.2831/q.z; float c = sqrt(9.8/k);', + ' float ph = k*dot(normalize(q.xy), p.xz) - c*k*uTime*0.25; h += q.w*sin(ph); }', + ' w.y += h * uSwell; vW = w.xyz; vH = h;', + ' vec4 mv = viewMatrix * w; gl_Position = projectionMatrix * mv;', + ' #include ', + '}' + ].join('\n').replace('vec4 mv = viewMatrix * w;', 'vec4 mvPosition = viewMatrix * w;').replace('projectionMatrix * mv;', 'projectionMatrix * mvPosition;'), + fragmentShader: [ + R.SKY_GLSL, + 'uniform float uTime; uniform sampler2D tDepth; uniform vec4 uHF; uniform vec3 uDeep; uniform vec3 uShallow; varying vec3 vW; varying float vH;', + '#include ', + 'float hsh(vec2 p){ return fract(sin(dot(p, vec2(127.1,311.7)))*43758.5453); }', + 'float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*f); return mix(mix(hsh(i), hsh(i+vec2(1,0)), f.x), mix(hsh(i+vec2(0,1)), hsh(i+vec2(1,1)), f.x), f.y); }', + 'vec2 ripple(vec2 p, float t){', // slope (dh/dx, dh/dz) from small waves + ' vec2 g = vec2(0.0);', + ' vec2 d1 = normalize(vec2(0.7,0.7)), d2 = normalize(vec2(-0.4,0.9)), d3 = normalize(vec2(0.95,-0.2)), d4 = normalize(vec2(-0.8,-0.5));', + ' g += d1 * cos(dot(d1,p)*1.9 - t*2.2) * 0.09; g += d2 * cos(dot(d2,p)*3.1 - t*3.0) * 0.06;', + ' g += d3 * cos(dot(d3,p)*5.3 - t*3.9) * 0.045; g += d4 * cos(dot(d4,p)*8.7 - t*5.1) * 0.03;', + ' float e = 0.15; vec2 q = p*0.9 + vec2(t*0.3, t*0.2);', + ' g += vec2(vn(q+vec2(e,0.))-vn(q-vec2(e,0.)), vn(q+vec2(0.,e))-vn(q-vec2(0.,e))) * 0.9;', + ' return g;', + '}', + 'void main(){', + ' vec3 V = normalize(cameraPosition - vW); float dist = length(cameraPosition - vW);', + ' vec2 sl = ripple(vW.xz, uTime) * mix(1.0, 0.25, smoothstep(30.0, 260.0, dist));', + ' vec3 N = normalize(vec3(-sl.x, 1.0, -sl.y));', + ' vec2 duv = (vW.xz - uHF.xy) / uHF.zw; float ground = texture2D(tDepth, duv).r; float depth = max(0.0, -ground + vH);', + ' if (duv.x < 0.0 || duv.y < 0.0 || duv.x > 1.0 || duv.y > 1.0) depth = 60.0;', + ' float fres = 0.02 + 0.98 * pow(1.0 - max(dot(N, V), 0.0), 5.0);', + ' vec3 R = reflect(-V, N); R.y = abs(R.y);', + ' vec3 refl = skyCol(R);', + ' float sh = smoothstep(0.0, 9.0, depth);', + ' vec3 body = mix(uShallow, uDeep, sh) * (0.35 + 0.65 * max(uSunDir.y, 0.15)) * (uZenith*0.8 + uHorizon*0.5);', + ' body += uShallow * 0.25 * pow(max(dot(-V, uSunDir), 0.0), 3.0) * (1.0 - sh);', // light through the shallows + ' vec3 col = mix(body, refl, fres);', + ' vec3 H = normalize(uSunDir + V); float spec = pow(max(dot(N, H), 0.0), 380.0) * 18.0 + pow(max(dot(N, H), 0.0), 40.0) * 0.18;', + ' col += uSunCol * spec * smoothstep(-0.02, 0.1, uSunDir.y);', + ' float foamN = vn(vW.xz*1.7 + uTime*0.4) * vn(vW.xz*0.6 - uTime*0.2);', + ' float foam = smoothstep(0.9, 0.0, depth) * smoothstep(0.15, 0.5, foamN + 0.35*sin(uTime*1.3 + depth*9.0));', + ' col = mix(col, vec3(0.9, 0.92, 0.9) * (uHorizon*0.6+0.5), foam*0.8);', + ' float alpha = mix(0.55, 1.0, smoothstep(0.0, 2.5, depth));', + ' alpha = max(alpha, fres);', + ' gl_FragColor = vec4(col, alpha);', + ' #include ', + ' #include ', + ' #include ', + '}' + ].join('\n') + }); + S.step = INNER * 2 / seg; + var m = S.mesh = new T.Mesh(g, mat); + m.frustumCulled = false; m.renderOrder = 2; + R.scene.add(m); + return m; + }; + // called when the time of day changes: street lamps and lit windows glow at dusk, barely by day + // a still pool (the villa's): a glassy, see-through teal surface over a tiled basin built by the map + S.pool = function (x, y, z, w, d) { + var g = new T.PlaneGeometry(w, d, 1, 1); g.rotateX(-Math.PI / 2); + var m = new T.Mesh(g, new T.MeshPhysicalMaterial({ color: RP.col('#3f9aa0'), roughness: 0.04, metalness: 0, transparent: true, opacity: 0.62, + envMapIntensity: 1.1, clearcoat: 1, clearcoatRoughness: 0.02, depthWrite: false })); + m.position.set(x, y, z); m.renderOrder = 2; m.receiveShadow = true; + R.scene.add(m); return m; + }; + S.atmos = function () { if (RP.MapTex) RP.MapTex.glowU.value = R.atmosName === 'dusk' ? 1 : R.atmosName === 'golden' ? 0.3 : 0.06; }; + S.update = function (t, cam) { + if (RP.B && RP.B.stream) RP.B.stream(cam); // the map's chunks follow the camera too (see build.js) + if (!S.mesh) return; + S.mat.uniforms.uTime.value = t; + var st = S.step; + S.mesh.position.set(Math.round(cam.position.x / st) * st, 0, Math.round(cam.position.z / st) * st); + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/traffic.js b/e63334287a3deaa3/blacktie/js/traffic.js new file mode 100644 index 00000000..e5b475f0 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/traffic.js @@ -0,0 +1,240 @@ +/* + * Traffic (RP.Traffic): bystanders' cars driving both ways along the coast road (RP.map.driveLine), keeping right. + * - They follow their lane by steering at a point ahead, slow for bends, and brake for anything in the lane ahead + * (you, other cars, guards, bystanders), with a toot of the horn when you stand in their way. + * - Cars appear and leave out of sight in a window around the player (how many depends on the quality preset). + * - F by a slow or stopped one pulls the driver out: they run off (unhurt, like every bystander) and the car is yours. + * - Shooting a car, ramming it, or a fight nearby (alert 3+) makes the driver stop, get out and run. + * Traffic runs on the 7 m coast road only, not down the bowl town's narrow street. + * Drivers are ordinary bystander actors seated with the player's driving pose (RP.Vehicles.pose). Missions turn + * traffic on with `traffic: true` (free roam and the coast-road chase). + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W; + var TR = RP.Traffic = { list: [], on: false }; + var COUNT = { low: 4, medium: 7, high: 10 }, LANE = 1.65, WINDOW = 260; + var line = null, cum = null; + var TYPES = ['city', 'city', 'berlina', 'spider']; + var COLS = { city: ['#c8402f', '#e9e2cf', '#7fb2c4', '#e2b23a', '#3d6b4f', '#2d3f6b', '#9b9ea3'], berlina: ['#15171a', '#1d2026', '#6b6e72', '#d9d4c6', '#3a2a22'], spider: ['#8f1d22', '#1c2a3f', '#d9d4c6', '#1d1d1f'] }; + + function prep() { + line = RP.map && RP.map.driveLine; + if (!line || line.length < 2) { line = null; return false; } + cum = [0]; + for (var i = 1; i < line.length; i++) cum.push(cum[i - 1] + Math.hypot(line[i][0] - line[i - 1][0], line[i][1] - line[i - 1][1])); + // traffic keeps to the coast road itself (7 m); the bowl town's narrow hairpin street is left to the player + var last = line.length - 1; while (last > 1 && (line[last][3] || 7) < 7) last--; + TR.len = cum[last]; + return true; + } + // the line at arc length s: point, road height and heading (toward increasing s) + function at(s, out) { + s = M.clamp(s, 0, TR.len); + var lo = 0, hi = cum.length - 1; + while (hi - lo > 1) { var mid = (lo + hi) >> 1; if (cum[mid] <= s) lo = mid; else hi = mid; } + var a = line[lo], b = line[hi], t = (s - cum[lo]) / Math.max(1e-6, cum[hi] - cum[lo]); + out.x = a[0] + (b[0] - a[0]) * t; out.z = a[1] + (b[1] - a[1]) * t; + out.y = a[2] != null && b[2] != null ? a[2] + (b[2] - a[2]) * t : null; + out.w = (t < 0.5 ? a[3] : b[3]) || 7; + out.yaw = Math.atan2(b[0] - a[0], b[1] - a[1]); + return out; + } + // arc length of the closest point on the line to (x, z), searching segments i0..i1 + function sOf(x, z, i0, i1) { + var best = 0, bd = 1e18; + i0 = Math.max(0, i0 || 0); i1 = Math.min(line.length - 2, i1 == null ? line.length - 2 : i1); + for (var i = i0; i <= i1; i++) { + var a = line[i], b = line[i + 1], dx = b[0] - a[0], dz = b[1] - a[1], l2 = dx * dx + dz * dz; + var t = l2 > 0 ? M.clamp(((x - a[0]) * dx + (z - a[1]) * dz) / l2, 0, 1) : 0; + var px = a[0] + dx * t - x, pz = a[1] + dz * t - z, d = px * px + pz * pz; + if (d < bd) { bd = d; best = cum[i] + t * Math.sqrt(l2); } + } + return best; + } + function segOf(s) { var lo = 0, hi = cum.length - 1; while (hi - lo > 1) { var mid = (lo + hi) >> 1; if (cum[mid] <= s) lo = mid; else hi = mid; } return lo; } + // the lane: right of the direction of travel (right of a heading h is (-cos h, sin h)) + var _p = {}, _q = {}; + function lanePoint(s, dir, out, side) { + at(s, out); var h = out.yaw + (dir < 0 ? Math.PI : 0), k = LANE * (out.w / 7) * (side == null ? 1 : side); + out.x += -Math.cos(h) * k; out.z += Math.sin(h) * k; out.h = h; + return out; + } + function visible(x, y, z) { + var cam = RP.R.camera, d = cam.position.distanceTo(_v.set(x, y, z)); + if (d < 60) return true; + if (d > 170) return false; + _fr.setFromProjectionMatrix(_m.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse)); + return _fr.containsPoint(_v.setY(y + 1)); + } + var _v = new T.Vector3(), _fr = new T.Frustum(), _m = new T.Matrix4(); + + // ------------------------------------------------------------------ cars in and out + function spawnAt(s, dir) { + var lp = lanePoint(s, dir, _p); + // room to appear: no car within 14 m + for (var i = 0; i < RP.Vehicles.list.length; i++) { var o = RP.Vehicles.list[i]; if (Math.hypot(o.pos.x - lp.x, o.pos.z - lp.z) < 14) return null; } + var type = TYPES[Math.floor(Math.random() * TYPES.length)], cols = COLS[type]; + var v = RP.Vehicles.spawn(type, lp.x, lp.z, lp.h, cols[Math.floor(Math.random() * cols.length)]); + if (!v) return null; + // stand on the road itself (on the viaduct and in the tunnels the ground query alone would find the valley or the hill) + if (lp.y != null) { v.pos.y = W.ground(lp.x, lp.z, lp.y + 1.2, 1.6).y; RP.Vehicles.syncBox(v); } + var a = RP.Chars.spawn('guest'); RP.R.scene.add(a.root); + a.playFull('sitIdle', { fade: 0, loop: true, hold: true }); + v.traffic = { dir: dir, s: s, cruise: 10.5 + Math.random() * 4, a: a, waitT: 0, hornT: 0, stuck: 0, panic: 0 }; + v.v = v.traffic.cruise * 0.7; + TR.list.push(v); + return v; + } + function despawn(v) { + var t = v.traffic; + if (t && t.a && t.a.root.parent) t.a.root.parent.remove(t.a.root); + RP.Vehicles.remove(v); + var i = TR.list.indexOf(v); if (i >= 0) TR.list.splice(i, 1); + } + // the driver gets out on their side and runs; the car is left where it stands, ready to take + TR.eject = function (v, from) { + var t = v.traffic; if (!t) return; + var c = Math.cos(v.yaw), s = Math.sin(v.yaw), lx = v.ty.wid / 2 + 0.6, lz = v.ty.doorZ - 0.6; + var x = v.pos.x + lx * c + lz * s, z = v.pos.z - lx * s + lz * c; + t.a.stopFull(0.15); + var cv = RP.AI.spawnCiv({ x: x, z: z, y: v.pos.y, yaw: v.yaw + Math.PI / 2 }, { actor: t.a, wander: 0 }); + if (cv) cv.scare(from || v.pos, 5); + v.traffic = null; v.v = 0; + var i = TR.list.indexOf(v); if (i >= 0) TR.list.splice(i, 1); + TR.left.push(v); + }; + TR.left = []; + + TR.clear = function () { + TR.list.slice().forEach(despawn); TR.list = []; TR.left = []; + }; + TR.start = function (mission) { + TR.clear(); + TR.on = !!(mission && mission.traffic) && prep(); + if (!TR.on) return; + var p = RP.G.player, sP = sOf(p.pos.x, p.pos.z), n = COUNT[RP.R.qname] || 6, tries = 0; + while (TR.list.length < n && tries++ < 40) { + var s = sP + (Math.random() * 2 - 1) * WINDOW * 0.8; + if (s < 25 || s > TR.len - 25 || Math.abs(s - sP) < 30) continue; + spawnAt(s, Math.random() < 0.5 ? 1 : -1); + } + TR._spawnT = 0; + }; + + TR.update = function (dt) { + if (!TR.on || !line) return; + var p = RP.G.player; if (!p) return; + var sP = sOf(p.pos.x, p.pos.z), n = COUNT[RP.R.qname] || 6; + // leave: far along the road or at its ends, out of sight + for (var i = TR.list.length - 1; i >= 0; i--) { + var v = TR.list[i], t = v.traffic; + var gone = Math.abs(t.s - sP) > WINDOW + 20 || (t.dir > 0 ? t.s > TR.len - 12 : t.s < 12) || v.dead; + if (gone && !visible(v.pos.x, v.pos.y, v.pos.z)) despawn(v); + } + // abandoned cars far behind are tidied away too + for (i = TR.left.length - 1; i >= 0; i--) { + var o = TR.left[i]; + if (o.driver) continue; + if (o.pos.distanceTo(p.pos) > 220 && !visible(o.pos.x, o.pos.y, o.pos.z)) { RP.Vehicles.remove(o); TR.left.splice(i, 1); } + } + // arrive: ahead of or behind the player along the road, out of sight + TR._spawnT -= dt; + if (TR.list.length < n && TR._spawnT <= 0) { + TR._spawnT = 0.5; + var s = sP + (Math.random() < 0.5 ? -1 : 1) * (110 + Math.random() * (WINDOW - 110)); + if (s > 25 && s < TR.len - 25) { + var lp = lanePoint(s, 1, _q); + if (!visible(lp.x, lp.y != null ? lp.y : p.pos.y, lp.z)) spawnAt(s, (s > sP ? -1 : 1) * (Math.random() < 0.65 ? 1 : -1)); // mostly coming toward the player + } + } + }; + + // ------------------------------------------------------------------ driving (called by RP.Vehicles.update) + var _f = { x: 0, z: 0 }; + function ahead(v, t, look) { + // the nearest thing in this car's lane ahead: returns the gap in metres (Infinity when clear) + var c = Math.cos(v.yaw), s = Math.sin(v.yaw), fx = Math.sin(v.yaw), fz = Math.cos(v.yaw), half = v.ty.len / 2, gap = Infinity, who = null; + t.whoObj = null; + function test(x, z, y, rad, halfLen, what, obj) { + if (Math.abs(y - v.pos.y) > 3) return; + if (t.passT > 0 && obj && obj === t.passing) return; + var dx = x - v.pos.x, dz = z - v.pos.z, fw = dx * fx + dz * fz, lat = -dx * c + dz * s; + if (fw < 0 || fw > look + half + halfLen) return; + if (Math.abs(lat) > v.ty.wid / 2 + rad + 0.35) return; + var g = fw - half - halfLen; if (g < gap) { gap = g; who = what; t.whoObj = obj; } + } + var p = RP.G.player; + if (p && p.alive) { if (p.vehicle) { if (p.vehicle !== v) test(p.vehicle.pos.x, p.vehicle.pos.z, p.vehicle.pos.y, p.vehicle.ty.wid / 2, p.vehicle.ty.len / 2, 'player', p.vehicle); } else test(p.pos.x, p.pos.z, p.pos.y, 0.4, 0.4, 'player'); } + RP.Vehicles.list.forEach(function (o) { if (o !== v && o !== (p && p.vehicle)) test(o.pos.x, o.pos.z, o.pos.y, o.ty.wid / 2, o.ty.len / 2, 'car', o); }); + RP.G.guards.forEach(function (g) { if (g.alive) test(g.pos.x, g.pos.z, g.pos.y, 0.4, 0.4, 'person'); }); + RP.G.civilians.forEach(function (cv) { test(cv.pos.x, cv.pos.z, cv.pos.y, 0.4, 0.4, 'person'); }); + t.who = who; + return gap; + } + TR.step = function (v, dt) { + var t = v.traffic, V = RP.Vehicles, p = RP.G.player; + t.s = sOf(v.pos.x, v.pos.z, segOf(t.s) - 2, segOf(t.s) + 2); + if (v.dead) { TR.eject(v, v.pos); return; } // a wreck: the driver climbs out and runs + // trouble: shot at, rammed, or a fight close by: stop and get out + if (t.panic > 0 || (RP.Alert.level >= 3 && p && !p.vehicle && p.pos.distanceTo(v.pos) < 45)) { + t.panic = Math.max(t.panic, 0.01); + V.drive(v, dt, Math.abs(v.v) > 0.5 ? -1 : 0, 0, Math.abs(v.v) < 3); + if (Math.abs(v.v) < 1.2) { TR.eject(v, t.from); return; } + seat(v, t, dt); return; + } + // lane target: a point ahead along the road, further at speed + // overtaking a car stopped in the lane (abandoned or parked): out into the other lane until past it + t.passT = Math.max(0, (t.passT || 0) - dt); + var sp = Math.abs(v.v), look = 7 + sp * 0.7, lp = lanePoint(t.s + t.dir * look, t.dir, _p, t.passT > 0 ? -1 : 1); + var err = M.wrap(Math.atan2(lp.x - v.pos.x, lp.z - v.pos.z) - v.yaw); + // speed: cruise, less for the bend coming (heading change over the next 30 m), less again for anything ahead + var h0 = at(t.s, _q).yaw, h1 = at(t.s + t.dir * 30, _q).yaw, bend = Math.abs(M.wrap(h1 - h0)); + var want = Math.min(t.cruise, M.clamp(16 - bend * 13, 5.5, 16)); + var gap = ahead(v, t, 6 + sp * 1.3); + if (gap < Infinity) want = Math.min(want, Math.max(0, (gap - 2.2) * 0.85)); + // a car standing in the lane (abandoned, parked, the player's car nose to nose with us, a Halcyon car): after a + // moment go round it in the other lane, backing off first if we are touching; a queue of traffic is waited out longer + var blk = t.who ? t.whoObj : null; + if (gap < 10 && blk && blk.ty && Math.abs(blk.v) < 0.5 && t.passT <= 0) { + t.blockT = (t.blockT || 0) + dt; + if (t.blockT > (blk.traffic ? 5 : 2)) { t.passing = blk; t.passT = 6; t.blockT = 0; t.backT = gap < 2 ? 1.1 : 0; } + } else if (t.passT <= 0) t.blockT = 0; + if (t.passT > 0) want = Math.min(want, 7); + if (t.backT > 0) { + t.backT -= dt; + V.drive(v, dt, -0.8, -M.clamp(err * 2.4, -1, 1), false); V.hitPeople(v); v.hit = 0; seat(v, t, dt); return; + } + // someone standing in front: wait, then sound the horn + if (gap < 9 && t.who === 'player' && !(p && p.vehicle) && sp < 1) { + t.waitT += dt; t.hornT -= dt; + if (t.waitT > 1.3 && t.hornT <= 0) { RP.Audio.horn && RP.Audio.horn(v.pos, t.waitT > 5 ? 0.9 : 0.22, t.waitT <= 5); t.hornT = 2.5 + Math.random() * 2; } + } else t.waitT = 0; + var thr = v.v < want - 0.4 ? M.clamp((want - v.v) / 3, 0.3, 1) : v.v > want + 0.4 ? -M.clamp((v.v - want) / 3, 0.25, 1) : 0; + if (Math.abs(err) > 2) thr = Math.min(thr, 0.2); + V.drive(v, dt, thr, M.clamp(err * 2.4, -1, 1), want < 0.3 && sp < 0.6); + V.hitPeople(v); + // a hard knock (the player's car, a wall) or a long hold-up: an annoyed driver gives up and leaves the car + if (v.hit > 6) { t.panic = 1; t.from = v.pos.clone(); } + v.hit = 0; + t.stuck = sp < 0.5 && gap === Infinity ? t.stuck + dt : 0; + if (t.stuck > 8 && !visible(v.pos.x, v.pos.y, v.pos.z)) { despawn(v); return; } + seat(v, t, dt); + }; + // the driver in the seat, hands on the wheel (as the player is placed in player.js) + var _fake = { vehicle: null, actor: null }; + function seat(v, t, dt) { + var a = t.a; if (!a) return; + var c = Math.cos(v.yaw), s = Math.sin(v.yaw), se = v.ty.seat; + a.root.position.set(v.pos.x + se[0] * c + se[2] * s, v.pos.y + se[1] - 0.63 * (a.height / 1.8) * 1.04, v.pos.z - se[0] * s + se[2] * c); + a.root.rotation.y = v.yaw; + a.setVisible(v.lod !== 2); + if (v.lod === 2) return; + a.weaponAim = 0; a.reloadU = -1; a.airborne = true; + a.drive({ speed: 0, dir: 0, strafe: 0, stealth: 0, sprint: 0, turnRate: 0, accel: 0 }); + a.setAim(0, 0); a.update(dt); + if (a.lodLevel === 0) { _fake.vehicle = v; _fake.actor = a; RP.Vehicles.pose(_fake); } + } + // a bullet in the bodywork: the driver panics + TR.hit = function (v, from) { if (v.traffic) { v.traffic.panic = 1; v.traffic.from = from; } }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/vehicles.js b/e63334287a3deaa3/blacktie/js/vehicles.js new file mode 100644 index 00000000..da589fd6 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/vehicles.js @@ -0,0 +1,696 @@ +/* + * Vehicles (RP.Vehicles): cars and a motorboat you can drive, GTA-style. + * F (or Use on a phone) by a door gets in; W/S throttle and brake/reverse, A/D steer, Space handbrake, F gets out + * (bails out with a tumble above 20 km/h). One-handed guns and SMGs fire from the driver's seat (aim with the + * right button, as on foot). Guards hit at speed go flying; bystanders are shoved clear and never hurt. + * Every make and model is invented (Lucciola city car, Brezza Spider, Marea launch); no real cars, badges or brands. + * + * Model: made in code (a body lofted through cross-sections, see loftBody; lathe wheels, lamps), front toward +Z. + * Handling: an arcade bicycle model: speed along the heading, steering lock that shrinks with speed, a slip angle that + * opens when cornering force passes the tyres' grip or the handbrake is on (the tail steps out, speed scrubs off). + * The body follows the ground under its four wheels (pitch and roll), falls when the ground drops away, and is moved + * as two circles (front and rear axle) through RP.W so walls and kerbs turn it realistically. A parked or driven car + * is also a box in RP.W (cover, bullets, people), moved through the broad-phase grid as it goes. + */ +(function () { + 'use strict'; + var T = THREE, M = RP.M, W = RP.W; + var V = RP.Vehicles = { list: [] }; + var CELL = 8; // RP.W's broad-phase cell (world.js) + + V.TYPES = { + city: { name: 'Lucciola', len: 3.45, wid: 1.56, h: 1.42, wheelR: 0.28, wb: 2.25, track: 1.32, top: 27, accel: 6.2, brake: 15, grip: 0.95, seat: [0.36, 0.56, -0.25], doorZ: -0.1, cols: ['#c8402f', '#e9e2cf', '#7fb2c4', '#e2b23a', '#3d6b4f'] }, + spider: { name: 'Brezza Spider', len: 4.15, wid: 1.74, h: 1.16, wheelR: 0.32, wb: 2.45, track: 1.46, top: 46, accel: 10.5, brake: 19, grip: 1.2, open: true, seat: [0.38, 0.4, -0.62], doorZ: -0.4, cols: ['#8f1d22', '#1c2a3f', '#d9d4c6', '#1d1d1f'] }, + berlina: { name: 'Halcyon saloon', len: 4.4, wid: 1.76, h: 1.44, wheelR: 0.31, wb: 2.7, track: 1.5, top: 40, accel: 8, brake: 17, grip: 1.05, seat: [0.38, 0.54, -0.2], doorZ: -0.1, cols: ['#15171a', '#1d2026'] }, + boat: { name: 'Marea launch', len: 6.4, wid: 2.1, h: 1.1, top: 19, accel: 5.5, brake: 5, grip: 0.6, water: true, seat: [0.4, 0.66, -0.62], doorZ: -0.6, cols: ['#6b4026'] } + }; + + // ------------------------------------------------------------------ models + var MAT = null; + function mats() { + if (MAT) return MAT; + var std = function (hex, r, m, o) { return new T.MeshStandardMaterial(Object.assign({ color: RP.col(hex), roughness: r, metalness: m || 0 }, o || {})); }; + MAT = { tyre: std('#141414', 0.9), rim: std('#b9bdc2', 0.3, 0.9), dark: std('#1a1a1c', 0.7, 0.1), chrome: std('#d5d8dc', 0.15, 1), seat: std('#5b3a26', 0.75), + glass: new T.MeshPhysicalMaterial({ color: RP.col('#1c2a30'), roughness: 0.05, metalness: 0, transparent: true, opacity: 0.55, envMapIntensity: 1.5 }), + head: std('#fff6dc', 0.2, 0, { emissive: RP.col('#fff1c8'), emissiveIntensity: 0.6 }), tail: std('#8a1010', 0.3, 0, { emissive: RP.col('#c01a1a'), emissiveIntensity: 0.5 }), + wood: std('#7a4a2a', 0.35), deck: std('#c9a26b', 0.5), hull: std('#f1ede3', 0.35), + well: std('#0c0c0d', 0.95, 0, { side: T.DoubleSide }), grille: std('#101113', 0.55, 0.5) }; + MAT.glass.userData.farCol = RP.col('#26343c'); + return MAT; + } + function paint(hex) { return new T.MeshPhysicalMaterial({ color: RP.col(hex), roughness: 0.55, metalness: 0.1, clearcoat: 0.5, clearcoatRoughness: 0.2, envMapIntensity: 0.6 }); } + // side profile [z, y] extruded across the width (rounded edges), centred on x = 0 + function prof(pts, width, bevel) { + var sh = new T.Shape(); sh.moveTo(pts[0][0], pts[0][1]); + for (var i = 1; i < pts.length; i++) { var p = pts[i]; if (p.length === 4) sh.quadraticCurveTo(p[0], p[1], p[2], p[3]); else sh.lineTo(p[0], p[1]); } + var b = bevel == null ? 0.06 : bevel; + var g = new T.ExtrudeGeometry(sh, { depth: Math.max(0.01, width - 2 * b), bevelEnabled: b > 0, bevelThickness: b, bevelSize: b, bevelSegments: 3, curveSegments: 10 }); + g.rotateY(-Math.PI / 2); g.translate((width - 2 * b) / 2, 0, 0); return g; + } + function mesh(geo, mat, x, y, z) { var m = new T.Mesh(geo, mat); m.position.set(x || 0, y || 0, z || 0); m.castShadow = true; return m; } + function wheel(R, wdt) { + var g = new T.Group(), M0 = mats(); + var tyre = new T.Mesh(new T.CylinderGeometry(R, R, wdt, 20), M0.tyre); tyre.rotation.z = Math.PI / 2; tyre.castShadow = true; g.add(tyre); + var rim = new T.Mesh(new T.CylinderGeometry(R * 0.64, R * 0.64, wdt * 1.03, 16), M0.rim); rim.rotation.z = Math.PI / 2; g.add(rim); + var hub = new T.Mesh(new T.CylinderGeometry(R * 0.2, R * 0.2, wdt * 1.1, 10), M0.dark); hub.rotation.z = Math.PI / 2; g.add(hub); + for (var i = 0; i < 5; i++) { var sp = new T.Mesh(new T.BoxGeometry(wdt * 1.06, R * 0.52, R * 0.1), M0.dark); sp.rotation.x = i / 5 * Math.PI * 2; sp.position.set(0, Math.cos(i / 5 * Math.PI * 2) * R * 0.36, Math.sin(i / 5 * Math.PI * 2) * R * 0.36); g.add(sp); } + return g; + } + // the lower body's outline (clockwise from the rear bumper, over the top, back along the sills) with the two + // wheel arches cut into the sill line, so the extrusion has real wheel wells + function bodyShape(top, f, r, b0, R, wb) { + var sh = new T.Shape(), Ra = R + 0.075, zf = wb / 2, zr = -wb / 2; + sh.moveTo(top[0][0], top[0][1]); + for (var i = 1; i < top.length; i++) { var p = top[i]; if (p.length === 4) sh.quadraticCurveTo(p[0], p[1], p[2], p[3]); else sh.lineTo(p[0], p[1]); } + sh.lineTo(f - 0.14, b0); sh.lineTo(zf + Ra, b0); sh.lineTo(zf + Ra, R); sh.absarc(zf, R, Ra, 0, Math.PI, false); + sh.lineTo(zf - Ra, b0); sh.lineTo(zr + Ra, b0); sh.lineTo(zr + Ra, R); sh.absarc(zr, R, Ra, 0, Math.PI, false); + sh.lineTo(zr - Ra, b0); sh.lineTo(r + 0.12, b0); sh.closePath(); + return sh; + } + function extrude(sh, width, bevel) { + var g = new T.ExtrudeGeometry(sh, { depth: Math.max(0.01, width - 2 * bevel), bevelEnabled: bevel > 0, bevelThickness: bevel, bevelSize: bevel * 0.6, bevelSegments: 3, curveSegments: 12 }); + g.rotateY(-Math.PI / 2); g.translate((width - 2 * bevel) / 2, 0, 0); return g; + } + // ------------------------------------------------------------------ lofted car bodies + // A car body is one smooth surface lofted through cross-sections along its length (front toward +Z): + // plan: the half-width at each station follows a superellipse, so the corners are rounded seen from above; + // side: `top` is the silhouette (bumper, bonnet, windscreen, roof, rear window, boot) and `belt` the waistline + // where the glass starts; the sill rises over each wheel, which cuts real arches into the side; + // section: a tucked sill, a flank that bulges a little, a shoulder at the waist, and a cabin that leans in toward + // the roof (tumblehome). + // Faces are then sorted into paint, glass (windscreen, side and rear windows, leaving the pillars painted), dark + // underside, or nothing (an open car's cockpit). Nose and tail are raked back above bumper height. + var BODY = { + city: { p: 7, tumble: 0.24, rakeF: 0.22, rakeR: 0.1, bPillar: -0.32, cockpit: null, + top: [[-1.725, 0.5], [-1.7, 0.92], [-1.66, 1.2], [-1.56, 1.35], [-1.38, 1.41], [-0.4, 1.42], [0.04, 1.4], [0.18, 1.35], [0.74, 0.93], [1.2, 0.87], [1.52, 0.8], [1.68, 0.67], [1.725, 0.48]], + belt: [[-1.725, 0.86], [0.74, 0.9], [1.725, 0.9]] }, + spider: { p: 6, tumble: 0, rakeF: 0.3, rakeR: 0.18, bPillar: null, cockpit: [-0.98, 0.32], + top: [[-2.075, 0.42], [-2.04, 0.6], [-1.92, 0.72], [-1.5, 0.78], [-0.98, 0.79], [0.4, 0.77], [1.2, 0.71], [1.78, 0.63], [2.0, 0.54], [2.075, 0.38]], + belt: [[-2.075, 2], [2.075, 2]] }, + berlina: { p: 7, tumble: 0.2, rakeF: 0.2, rakeR: 0.14, bPillar: -0.12, cockpit: null, + top: [[-2.2, 0.55], [-2.17, 0.8], [-2.08, 0.9], [-1.7, 0.94], [-1.28, 0.96], [-1.06, 1.04], [-0.76, 1.36], [-0.5, 1.43], [0.3, 1.44], [0.48, 1.41], [0.64, 1.33], [1.14, 0.96], [1.6, 0.91], [2.0, 0.84], [2.15, 0.71], [2.2, 0.52]], + belt: [[-2.2, 0.93], [1.14, 0.96], [2.2, 0.96]] } + }; + function sstep(a, b, x) { var t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); } + function lerpPts(pts, z) { + if (z <= pts[0][0]) return pts[0][1]; + for (var i = 1; i < pts.length; i++) if (z <= pts[i][0]) { var a = pts[i - 1], b = pts[i]; return a[1] + (b[1] - a[1]) * (z - a[0]) / (b[0] - a[0]); } + return pts[pts.length - 1][1]; + } + function bodyKit(ty, bd) { + var L = ty.len, hl = L / 2, hw = ty.wid / 2, R = ty.wheelR, Ra = R + 0.08, b0 = 0.17, axles = [ty.wb / 2, -ty.wb / 2]; + var K = { + hw: hw, hl: hl, p: bd.p, + plan: function (z) { var t = Math.min(1, Math.abs(z) / hl); return Math.pow(Math.max(0, 1 - Math.pow(t, bd.p)), 1 / bd.p); }, + top: function (z) { return lerpPts(bd.top, z); }, + belt: function (z) { return Math.min(lerpPts(bd.top, z), lerpPts(bd.belt, z)); }, + sill: function (z) { + var y = b0; + axles.forEach(function (za) { var d = Math.abs(z - za); if (d < Ra) y = Math.max(y, R + Math.sqrt(Ra * Ra - d * d) * 0.96); }); + return y; + }, + // nose and tail lean back above bumper height + rake: function (z, y) { + var zs = hl - 0.62, k; + if (z > zs) { k = 1 - bd.rakeF * sstep(0.42, 0.95, y); return zs + (z - zs) * k; } + if (z < -zs) { k = 1 - bd.rakeR * sstep(0.5, 1.1, y); return -zs + (z + zs) * k; } + return z; + } + }; + // half cross-section at station z: [x, y] from the bottom middle round to the top middle (13 points) + K.section = function (z) { + var pl = K.plan(z), w = hw * pl, top = K.top(z), belt = K.belt(z), yb = Math.min(K.sill(z), belt - 0.02), cab = Math.max(0, top - belt); + var bulge = 0.028 * pl, crown = 0.035 * pl, wt = Math.max(0, w - 0.05 - bd.tumble * cab), rr = Math.min(0.07, 0.02 + cab * 0.12); + var pts = [[0, yb], [w * 0.86, yb], [w - 0.035 * pl, yb + 0.045], [w, yb + 0.13], [w + bulge, (yb + belt) / 2], [w + bulge * 0.4, belt - 0.07], [w - 0.02 * pl, belt], + [M.lerp(w - 0.03 * pl, wt, 0.33), belt + cab * 0.33], [M.lerp(w - 0.03 * pl, wt, 0.66), belt + cab * 0.66], [wt, belt + Math.max(0, cab - rr)], + [Math.max(0, wt - rr * 0.7), belt + Math.max(0, cab - rr * 0.25)], [wt * 0.5, top + crown], [0, top + crown]]; + for (var i = 1; i < pts.length; i++) { if (pts[i][1] < pts[i - 1][1]) pts[i][1] = pts[i - 1][1]; if (i <= 6 && pts[i][1] > belt) pts[i][1] = belt; } + return pts; + }; + // where along the body the plan's edge is at height y, for lamps and trim on the nose and tail: z for a given x + K.endZ = function (x, front, y) { + var t = Math.min(0.999, Math.abs(x) / hw), z = hl * Math.pow(1 - Math.pow(t, bd.p), 1 / bd.p); + return K.rake(front ? z : -z, y); + }; + return K; + } + // stations along the body: close together at the rounded ends and over the arches + function stations(K, ty) { + var zs = [], n = 40, Ra = ty.wheelR + 0.08; + for (var i = 0; i <= n; i++) zs.push(-K.hl * Math.cos(Math.PI * i / n)); + [ty.wb / 2, -ty.wb / 2].forEach(function (za) { for (var d = -Ra - 0.04; d <= Ra + 0.04; d += 0.07) zs.push(za + d); }); + zs.sort(function (a, b) { return a - b; }); + return zs.filter(function (z, i) { return i === 0 || z - zs[i - 1] > 0.018; }); + } + function loftBody(ty, bd) { + var K = bodyKit(ty, bd), zs = stations(K, ty), NS = 13, RING = 2 * NS - 2; + var pos = [], info = []; + zs.forEach(function (z) { + var h = K.section(z), ring = []; + for (var i = 0; i < NS; i++) ring.push([h[i][0], h[i][1], i]); + for (i = NS - 2; i >= 1; i--) ring.push([-h[i][0], h[i][1], i]); + ring.forEach(function (q) { pos.push(q[0], q[1], K.rake(z, q[1])); info.push(z, q[2]); }); + }); + var geo = new T.BufferGeometry(); geo.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); + var all = []; for (var s = 0; s < zs.length - 1; s++) for (var r = 0; r < RING; r++) { + var a = s * RING + r, b = s * RING + (r + 1) % RING, c = (s + 1) * RING + r, d = (s + 1) * RING + (r + 1) % RING; + all.push(a, b, c, b, d, c); + } + geo.setIndex(all); geo.computeVertexNormals(); + // sort the quads + var P = geo.attributes.position, lists = { paint: [], glass: [], dark: [] }, e1 = new T.Vector3(), e2 = new T.Vector3(), nn = new T.Vector3(), va = new T.Vector3(), vb = new T.Vector3(); + for (var q = 0; q < all.length; q += 6) { + // corners: i0 (station s, ring r), i1 (s, r+1), i2 (s+1, r), i3 (s+1, r+1); outward normal from the diagonals + var i0 = all[q], i1 = all[q + 1], i2 = all[q + 2], i3 = all[q + 4]; + e1.subVectors(vb.fromBufferAttribute(P, i1), va.fromBufferAttribute(P, i2)); e2.subVectors(vb.fromBufferAttribute(P, i3), va.fromBufferAttribute(P, i0)); + nn.crossVectors(e1, e2); + if (nn.lengthSq() < 1e-12) continue; + nn.normalize(); + var z = (info[i0 * 2] + info[i2 * 2]) / 2, row = Math.max(info[i0 * 2 + 1], info[i1 * 2 + 1]), rowLo = Math.min(info[i0 * 2 + 1], info[i1 * 2 + 1]); + var cx = (P.getX(i0) + P.getX(i1) + P.getX(i2) + P.getX(i3)) / 4, cy = (P.getY(i0) + P.getY(i1) + P.getY(i2) + P.getY(i3)) / 4; + var belt = K.belt(z), top = K.top(z), cab = top - belt, sec = K.section(z), wt = sec[9][0]; + var which = 'paint'; + if (nn.y < -0.55 || rowLo === 0 && row <= 1) which = 'dark'; + else if (bd.cockpit && z > bd.cockpit[0] && z < bd.cockpit[1] && rowLo >= 10 && Math.abs(cx) < sec[6][0] - 0.12) which = null; + else if (cab > 0.2 && rowLo >= 6 && row <= 10) { + // side windows: between the pillars, clear of the waist and the roof rail + var cabB = K.top(z - 0.11) - K.belt(z - 0.11), cabF = K.top(z + 0.11) - K.belt(z + 0.11); + var side = Math.abs(nn.x) > 0.42 && rowLo >= 6 && row <= 9 && cabB > 0.3 && cabF > 0.3 && !(bd.bPillar != null && Math.abs(z - bd.bPillar) < 0.06); + if (side && cy > belt + 0.035 && cy < top - 0.05) which = 'glass'; + } + if (which === 'paint' && cab > 0.12 && rowLo >= 10 && cy > belt + 0.04 && Math.abs(cx) < wt - 0.06) { + if (nn.z > 0.38 || nn.z < -0.38) which = 'glass'; // windscreen and rear window, inside their pillars + } + if (which) lists[which].push(all[q], all[q + 1], all[q + 2], all[q + 3], all[q + 4], all[q + 5]); + } + var out = {}; + Object.keys(lists).forEach(function (k) { if (!lists[k].length) return; var g = geo.clone(); g.setIndex(lists[k]); out[k] = g; }); + out.K = K; + return out; + } + // a band of trim that follows the plan of the nose or tail (bumpers, grille, lamps): x from x0 to x1 (|x| as a + // fraction of the half-width; negative x0 mirrors across the middle), y0..y1, standing `off` proud of the body + function endBand(K, front, x0, x1, y0, y1, off, bulge) { + var n = 16, pos = [], idx = [], rows = [y0, (y0 + y1) / 2, y1], cap = Math.pow(1 - Math.pow(0.88, K.p), 1 / K.p); + x0 = Math.max(-cap, Math.min(cap, x0)); x1 = Math.max(-cap, Math.min(cap, x1)); + for (var i = 0; i <= n; i++) { + var f = x0 + (x1 - x0) * i / n, x = f * K.hw; + rows.forEach(function (y, j) { + var z = K.endZ(x, front, y), o = off + (j === 1 ? bulge : 0); + // push outward along the plan normal (approximated from the neighbouring point) + var z2 = K.endZ(x + 0.01, front, y), tz = z2 - z, l = Math.hypot(0.01, tz), nx = -tz / l, nz = 0.01 / l; + if (nz * (front ? 1 : -1) < 0) { nx = -nx; nz = -nz; } + pos.push(x + nx * o, y, z + nz * o); + }); + } + for (i = 0; i < n; i++) for (var j = 0; j < 2; j++) { + var a = i * 3 + j, b = a + 1, c = a + 3, d = c + 1; + if (front) idx.push(a, c, b, b, c, d); else idx.push(a, b, c, b, d, c); + } + var g = new T.BufferGeometry(); g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); g.setIndex(idx); g.computeVertexNormals(); + return g; + } + function buildCar(ty, hex) { + var g = new T.Group(), M0 = mats(), P = paint(hex), L = ty.len, hw = ty.wid / 2, R = ty.wheelR, f = L / 2, r = -L / 2, H = ty.h, b0 = 0.17; + var yb = ty.open ? 0.72 : 0.88, type = ty.open ? 'spider' : ty.wb > 2.6 ? 'berlina' : 'city', bd = BODY[type]; + var body = loftBody(ty, bd), K = body.K; + P.side = T.DoubleSide; // the inside of the pillars and roof, seen through the far window + g.add(mesh(body.paint, P)); + if (body.glass) g.add(mesh(body.glass, M0.glass)); + if (body.dark) g.add(mesh(body.dark, M0.dark)); + // wheel wells (dark liners over each tyre) and the cabin tub that hides the hollow body behind the glass + [ty.wb / 2, -ty.wb / 2].forEach(function (za) { + var wl = new T.Mesh(new T.CylinderGeometry(R + 0.07, R + 0.07, ty.wid - 0.08, 14, 1, true, 0, Math.PI), M0.well); + wl.rotation.z = Math.PI / 2; wl.position.set(0, R, za); g.add(wl); + }); + var cz0 = ty.open ? bd.cockpit[0] : r + 0.5, cz1 = ty.open ? bd.cockpit[1] + 0.1 : ty.wb / 2 - 0.15; + g.add(mesh(new T.BoxGeometry(ty.wid - 0.22, yb - b0 - 0.2, cz1 - cz0), M0.dark, 0, (yb + b0 + 0.05) / 2, (cz0 + cz1) / 2)); + // seats: two buckets in front, a bench behind in the closed cars + [-1, 1].forEach(function (s) { + var bh = ty.open ? 0.72 : 0.92; + g.add(mesh(prof([[-0.5, 0], [-0.47, bh], [-0.33, bh + 0.02], [-0.34, 0.13], [0.14, 0.15], [0.16, 0]], 0.46, 0.05), M0.seat, s * 0.38, ty.seat[1] - 0.2, ty.seat[2])); + }); + if (!ty.open) { + // the rear bench's back, kept under the roof line where the rear window slopes down + var zb = ty.seat[2] - 0.78, bt = Math.min(K.top(zb) - 0.16, K.belt(zb) + 0.32), by0 = ty.seat[1] - 0.15; + g.add(mesh(new T.BoxGeometry(ty.wid - 0.36, bt - by0, 0.14), M0.seat, 0, (bt + by0) / 2, zb)); + g.add(mesh(new T.BoxGeometry(ty.wid - 0.36, 0.12, 0.45), M0.seat, 0, by0 + 0.06, zb + 0.28)); + } + // dashboard under the windscreen + var zd = ty.open ? 0.3 : (type === 'city' ? 0.62 : 0.98); + g.add(mesh(new T.BoxGeometry(ty.wid - 0.3, 0.14, 0.34), M0.dark, 0, yb - 0.02, zd)); + if (ty.open) { + var ws = prof([[0.33, yb - 0.02], [0.4, yb - 0.02], [0.08, H], [0.03, H]], ty.wid - 0.34, 0.012); g.add(mesh(ws, M0.glass)); + g.add(mesh(new T.BoxGeometry(ty.wid - 0.36, 0.03, 0.045), M0.chrome, 0, H, 0.055)); + [-1, 1].forEach(function (s) { g.add(mesh(new T.CylinderGeometry(0.06, 0.08, 0.26, 10), P, s * 0.38, yb + 0.1, -0.98)); }); // roll hoops + } + // steering wheel (for the hands) + var sw = new T.Mesh(new T.TorusGeometry(0.17, 0.016, 6, 16), M0.dark); sw.position.set(ty.seat[0], yb - (ty.open ? 0.02 : 0.1), ty.seat[2] + 0.44); sw.rotation.x = -0.45; g.add(sw); g.userData.wheel = sw; + // nose: grille, headlamps in chrome rims, a bumper band; tail: wrap-round lamps, bumper, number plates, exhaust + var bump = ty.open ? M0.chrome : M0.dark, lampY = ty.open ? 0.52 : type === 'city' ? 0.6 : 0.66; + g.add(mesh(endBand(K, true, -0.36, 0.36, lampY - 0.17, lampY - 0.04, 0.004, 0.006), M0.grille)); + g.add(mesh(endBand(K, true, -0.97, 0.97, b0 + 0.07, b0 + 0.2, 0.012, 0.022), bump)); + g.add(mesh(endBand(K, false, -0.97, 0.97, b0 + 0.08, b0 + 0.22, 0.012, 0.022), bump)); + [-1, 1].forEach(function (s) { + var lx = s * (hw - 0.27), lz = K.endZ(lx, true, lampY); + g.add(mesh(new T.SphereGeometry(0.1, 14, 8).scale(1, 0.8, 0.45), M0.head, lx, lampY, lz - 0.03)); + g.add(mesh(new T.TorusGeometry(0.098, 0.012, 6, 18), M0.chrome, lx, lampY, lz - 0.005)); + var tl = s > 0 ? [0.5, 0.995] : [-0.995, -0.5]; + g.add(mesh(endBand(K, false, tl[0], tl[1], lampY - 0.05, lampY + 0.07, 0.006, 0.004), M0.tail)); + g.add(mesh(new T.BoxGeometry(0.1, 0.06, 0.12), ty.open ? M0.chrome : M0.dark, s * (hw + 0.05), yb + 0.07, ty.open ? 0.42 : (type === 'city' ? 0.62 : 0.92))); // mirrors + g.add(mesh(new T.BoxGeometry(0.06, 0.03, 0.04), M0.dark, s * (hw - 0.04), yb + 0.06, ty.open ? 0.42 : (type === 'city' ? 0.66 : 0.96))); // mirror arms + g.add(mesh(new T.BoxGeometry(0.03, 0.022, 0.11), M0.chrome, s * (hw + 0.026), yb - 0.1, ty.seat[2] - 0.18)); // door handle + }); + g.add(mesh(new T.BoxGeometry(0.34, 0.09, 0.012), M0.hull, 0, b0 + 0.3, K.endZ(0, false, b0 + 0.3) - 0.008)); + g.add(mesh(new T.BoxGeometry(0.3, 0.08, 0.012), M0.hull, 0, b0 + 0.14, K.endZ(0, true, b0 + 0.14) + 0.026)); + g.add(mesh(new T.CylinderGeometry(0.025, 0.025, 0.14, 8).rotateX(Math.PI / 2), M0.chrome, -hw + 0.32, b0 + 0.04, K.endZ(-hw + 0.32, false, b0) + 0.02)); + // wheels (children so they can spin and steer), set just inside the arches + g.userData.wheels = []; + [[1, 1], [-1, 1], [1, -1], [-1, -1]].forEach(function (k) { + var wl = wheel(R, 0.2), piv = new T.Group(); piv.position.set(k[0] * (hw - 0.115), R, k[1] * ty.wb / 2); piv.add(wl); g.add(piv); + g.userData.wheels.push({ piv: piv, spin: wl, front: k[1] > 0 }); + }); + return g; + } + function buildBoat(ty, hex) { + var g = new T.Group(), M0 = mats(), L = ty.len, f = L / 2, r = -L / 2; + // hull: a pointed plan extruded upward, sides flared by scaling the top + var sh = new T.Shape(); sh.moveTo(-1.0, r); sh.lineTo(1.0, r); sh.quadraticCurveTo(1.08, 0.6, 0.0, f); sh.quadraticCurveTo(-1.08, 0.6, -1.0, r); + var hull = new T.ExtrudeGeometry(sh, { depth: 0.75, bevelEnabled: true, bevelThickness: 0.06, bevelSize: 0.05, bevelSegments: 2, curveSegments: 14 }); + hull.rotateX(-Math.PI / 2); hull.scale(1, 1, -1); // plan in x-z, extruded up y + var pos = hull.attributes.position; for (var i = 0; i < pos.count; i++) { var y = pos.getY(i), k = 0.72 + 0.28 * M.clamp(y / 0.75, 0, 1); pos.setX(i, pos.getX(i) * k); } + hull.translate(0, -0.3, 0); hull.computeVertexNormals(); + g.add(mesh(hull, M0.wood)); + var deck = new T.Mesh(new T.ShapeGeometry(sh, 14), M0.deck); deck.rotation.x = -Math.PI / 2; deck.scale.set(0.97, -0.97, 1); deck.position.y = 0.46; g.add(deck); + g.add(mesh(new T.BoxGeometry(1.5, 0.3, 2.2), M0.dark, 0, 0.36, -0.9)); // cockpit well + var ws = prof([[0.55, 0.47], [0.62, 0.47], [0.2, 0.92], [0.14, 0.92]], 1.5, 0.01); g.add(mesh(ws, M0.glass)); + [-1, 1].forEach(function (s) { g.add(mesh(prof([[-0.95, 0.2], [-0.9, 0.8], [-0.78, 0.8], [-0.7, 0.36], [-0.3, 0.32], [-0.3, 0.2]], 0.5, 0.04), M0.hull, s * 0.4, 0, 0)); }); + g.add(mesh(new T.BoxGeometry(1.7, 0.5, 0.9), M0.wood, 0, 0.3, r + 0.6)); // engine cover + var sw = new T.Mesh(new T.TorusGeometry(0.17, 0.016, 6, 16), M0.chrome); sw.position.set(ty.seat[0], 0.72, ty.seat[2] + 0.5); sw.rotation.x = -0.5; g.add(sw); g.userData.wheel = sw; + g.add(mesh(new T.CylinderGeometry(0.012, 0.012, 0.7, 6), M0.chrome, 0, 0.82, f - 0.5)); + g.userData.wheels = []; + return g; + } + + // merge a group's direct mesh children by material (one draw call per material); `skip` meshes stay as they are + function mergeChildren(g, skip) { + var by = new Map(), drop = []; + g.children.forEach(function (o) { + if (!o.isMesh || (skip && skip.indexOf(o) >= 0)) return; + o.updateMatrix(); var geo = o.geometry.index ? o.geometry.toNonIndexed() : o.geometry.clone(); geo.applyMatrix4(o.matrix); + ['uv', 'uv1', 'uv2', 'color'].forEach(function (k) { if (geo.attributes[k] && k !== 'uv') geo.deleteAttribute(k); }); + if (!geo.attributes.uv) geo.setAttribute('uv', new T.Float32BufferAttribute(new Float32Array(geo.attributes.position.count * 2), 2)); + if (!by.has(o.material)) by.set(o.material, []); by.get(o.material).push(geo); drop.push(o); + }); + drop.forEach(function (o) { g.remove(o); }); + by.forEach(function (list, mat) { + var n = 0; list.forEach(function (q) { n += q.attributes.position.count; }); + var P = new Float32Array(n * 3), N = new Float32Array(n * 3), U = new Float32Array(n * 2), k = 0; + list.forEach(function (q) { P.set(q.attributes.position.array, k * 3); N.set(q.attributes.normal.array, k * 3); U.set(q.attributes.uv.array, k * 2); k += q.attributes.position.count; }); + var mg = new T.BufferGeometry(); mg.setAttribute('position', new T.BufferAttribute(P, 3)); mg.setAttribute('normal', new T.BufferAttribute(N, 3)); mg.setAttribute('uv', new T.BufferAttribute(U, 2)); + var m = new T.Mesh(mg, mat); m.castShadow = true; g.add(m); + }); + return g; + } + V.mergeChildren = mergeChildren; + + // ------------------------------------------------------------------ spawn + V.spawn = function (type, x, z, yaw, hex) { + var ty = V.TYPES[type]; if (!ty) return null; + hex = hex || ty.cols[Math.floor(Math.random() * ty.cols.length)]; + var g = ty.water ? buildBoat(ty, hex) : buildCar(ty, hex); + // the fixed parts become one mesh per material; each wheel becomes two (rubber and metal); the steering wheel stays + mergeChildren(g, g.userData.wheel ? [g.userData.wheel] : []); + g.userData.wheels.forEach(function (w) { mergeChildren(w.spin); }); + // the far car: the whole thing as one mesh (wheels and all), shown past FAR_D and hidden past the draw range + g.userData.far = RP.farMesh(g); g.add(g.userData.far); + var y = ty.water ? W.water : W.ground(x, z, (W.terrainH ? W.terrainH(x, z) : 0) + 1.2).y; // on the street, not on a roof above it + var v = { type: type, ty: ty, g: g, pos: new T.Vector3(x, y, z), yaw: yaw || 0, v: 0, slip: 0, steer: 0, vy: 0, pitch: 0, roll: 0, air: false, driver: null, hp: 100, spinA: 0, bobT: Math.random() * 6 }; + g.position.copy(v.pos); g.rotation.set(0, v.yaw, 0, 'YXZ'); + RP.R.scene.add(g); + v.box = W.addBox({ x: x, z: z, y0: y - (ty.water ? 0.5 : 0), y1: y + ty.h, hx: ty.wid / 2, hz: ty.len / 2, yaw: v.yaw, mat: 'car', cover: !ty.water, kind: 'car', dyn: true }); + v.box._cells = cellsOf(v.box); v.box.veh = v; + // bullets on the bodywork: sparks, damage; a finished car smokes and its engine dies + v.box.onHit = function (hit, dir, def) { + if (v.dead) return; v.hp -= (def && def.dmg || 10) * (v.ai ? 0.55 : 0.22); if (v.hp <= 0) kill(v); + if (v.traffic && RP.Traffic) RP.Traffic.hit(v, v.pos.clone().addScaledVector(dir || _a.set(0, 0, 1), -10)); + // through the glass (or over the side of an open car or the launch): the driver is hit too + var belt = v.ty.water ? 0.5 : v.ty.open ? 0.72 : 0.88; + if (v.driver && v.driver.alive && hit && hit.y > v.pos.y + belt && v.driver.takeDamage) { + v.driver.takeDamage((def && def.dmg || 10) * 0.6, { dir: dir, bullet: true, weapon: def, point: new T.Vector3(hit.x, hit.y, hit.z) }); + } + }; + V.list.push(v); return v; + }; + function kill(v) { + v.dead = true; v.hp = 0; + if (v.driver) RP.emit('toast', 'The ' + v.ty.name + ' is finished'); + if (v.ai && !v.ai.out) bailOut(v); + } + // the crew of a wrecked or cornered Halcyon car get out and fight on foot + function bailOut(v) { + v.ai.out = true; + var c = Math.cos(v.yaw), s = Math.sin(v.yaw); + [1, -1].forEach(function (sd, i) { + var x = v.pos.x + sd * (v.ty.wid / 2 + 0.7) * c, z = v.pos.z - sd * (v.ty.wid / 2 + 0.7) * s; + var g = RP.AI.spawnGuard(i ? 'sentry' : 'enforcer', { x: x, z: z, y: v.pos.y, yaw: v.yaw }); + if (g && RP.AI.alertGuard) RP.AI.alertGuard(g, RP.G.player.pos, false); + }); + } + // ---- pursuit: Halcyon cars follow the driving line after the player, close in, and a passenger fires bursts + V.chaser = function (behind) { + var line = RP.map && RP.map.driveLine, p = RP.G.player; if (!line || !p) return null; + var pi = nearestIdx(line, p.pos.x, p.pos.z, 0, line.length - 1), i = pi, d = 0; + while (i > 0 && d < behind) { d += Math.hypot(line[i][0] - line[i - 1][0], line[i][1] - line[i - 1][1]); i--; } + var a = line[i], b = line[Math.min(line.length - 1, i + 1)]; + var v = V.spawn('berlina', a[0], a[1], Math.atan2(b[0] - a[0], b[1] - a[1])); + v.ai = { team: 'guard', alive: true, pos: v.pos, idx: i, gunT: 2 + Math.random() * 2, burst: 0, stuck: 0 }; v.hp = 160; v.v = 14; + return v; + }; + function nearestIdx(line, x, z, i0, i1) { var best = i0, bd = 1e9; for (var i = i0; i <= i1; i++) { var d = (line[i][0] - x) * (line[i][0] - x) + (line[i][1] - z) * (line[i][1] - z); if (d < bd) { bd = d; best = i; } } return best; } + var CGUN = { name: 'Car gun', dmg: 8, range: [40, 110], minFrac: 0.5, snd: 'smg', cat: 'smg' }; + function stepAI(v, dt) { + var a = v.ai, p = RP.G.player, line = RP.map.driveLine; + if (v.dead || a.out || !p || !p.alive) { drive(v, dt, 0, 0, true); return; } + a.idx = nearestIdx(line, v.pos.x, v.pos.z, Math.max(0, a.idx - 2), Math.min(line.length - 1, a.idx + 4)); + var pIdx = nearestIdx(line, p.pos.x, p.pos.z, 0, line.length - 1), dP = Math.hypot(p.pos.x - v.pos.x, p.pos.z - v.pos.z); + var onFoot = !p.vehicle, tx, tz, want; + if (dP < 16 && Math.abs(p.pos.y - v.pos.y) < 4) { tx = p.pos.x; tz = p.pos.z; want = onFoot ? 0 : Math.abs(p.vehicle.v) + 3; } // close: go for the player + else { + // steer for a point about 16 m further along the line (by distance: the line's points are 10-26 m apart, and + // two points ahead cut every bend onto the hillside) + var ahead = pIdx >= a.idx, st2 = ahead ? 1 : -1, ti = a.idx, acc = 0; + while (ti + st2 >= 0 && ti + st2 < line.length && acc < 16) { acc += Math.hypot(line[ti + st2][0] - line[ti][0], line[ti + st2][1] - line[ti][1]); ti += st2; } + tx = line[ti][0]; tz = line[ti][1]; + want = M.clamp((p.vehicle ? Math.abs(p.vehicle.v) : 4) + (dP - 14) * 0.3, 7, v.ty.top * 0.92); + if (!ahead) { want = 9; } + } + // the player on foot nearby: pull up and get out + if (onFoot && dP < 26) { drive(v, dt, 0, 0, true); if (Math.abs(v.v) < 1.5) bailOut(v); return; } + var err = M.wrap(Math.atan2(tx - v.pos.x, tz - v.pos.z) - v.yaw); + if (Math.abs(err) > 2.2) { drive(v, dt, -0.7, -Math.sign(err), false); } // facing the wrong way: back round + else { want *= M.clamp(1.25 - Math.abs(err) * 0.9, 0.35, 1); drive(v, dt, v.v < want ? 1 : (v.v > want + 3 ? -0.6 : 0), M.clamp(err * 2.2, -1, 1), false); } + hitPeople(v); + // stuck against something: reverse out + a.stuck = Math.abs(v.v) < 0.6 ? a.stuck + dt : 0; if (a.stuck > 2.5) { v.v = -5; a.stuck = 0; } + // the passenger's gun + a.gunT -= dt; + if (a.burst > 0) { + a.shotT -= dt; + if (a.shotT <= 0) { + a.shotT = 0.09; a.burst--; + _a.set(v.pos.x, v.pos.y + 1.15, v.pos.z); _b.set(p.pos.x, p.pos.y + 1.0, p.pos.z).sub(_a).normalize(); + v.box.off = true; RP.Combat.fire(a, _a.clone().addScaledVector(_b, 1.2), _b.clone(), CGUN, { spread: 3.2 + Math.abs(v.v) * 0.12 + (p.vehicle ? Math.abs(p.vehicle.v) * 0.1 : 0), dmgMul: 0.6 }); v.box.off = false; + RP.FX.muzzle(_a.clone().addScaledVector(_b, 1.2), _b, false); RP.Audio.shot('smg', _a.clone(), { gain: 0.8 }); + if (a.burst === 0) a.gunT = 1.7 + Math.random() * 1.7; + } + } else if (a.gunT <= 0 && dP < 75 && W.los(v.pos.x, v.pos.y + 1.2, v.pos.z, p.pos.x, p.pos.y + 1.1, p.pos.z)) { a.burst = 4 + Math.floor(Math.random() * 4); a.shotT = 0; } + if (v.hit > 8) { v.hp -= v.hit * 2; if (v.hp <= 0) kill(v); } v.hit = 0; + } + // take one vehicle out of the world (traffic leaving) + V.remove = function (v) { + if (v.g.parent) v.g.parent.remove(v.g); v.box.off = true; + (v.box._cells || []).forEach(function (k) { var l = W.grid[k]; if (l) { var i = l.indexOf(v.box); if (i >= 0) l.splice(i, 1); } }); + var i = V.list.indexOf(v); if (i >= 0) V.list.splice(i, 1); + }; + V.clear = function () { + V.list.forEach(function (v) { if (v.g.parent) v.g.parent.remove(v.g); v.box.off = true; }); + V.list = []; stopEngine(); + }; + function cellsOf(b) { + var out = [], gx0 = Math.floor((b.x - b.r) / CELL), gx1 = Math.floor((b.x + b.r) / CELL), gz0 = Math.floor((b.z - b.r) / CELL), gz1 = Math.floor((b.z + b.r) / CELL); + for (var gx = gx0; gx <= gx1; gx++) for (var gz = gz0; gz <= gz1; gz++) out.push(gx + ',' + gz); + return out; + } + // move the vehicle's RP.W box (through the broad-phase grid when it crosses cells) + function syncBox(v) { + var b = v.box; b.x = v.pos.x; b.z = v.pos.z; b.yaw = v.yaw; b.c = Math.cos(v.yaw); b.s = Math.sin(v.yaw); + b.y0 = v.pos.y - (v.ty.water ? 0.5 : 0); b.y1 = v.pos.y + v.ty.h; + var cells = cellsOf(b), old = b._cells; + if (cells.join('|') === old.join('|')) return; + old.forEach(function (k) { var l = W.grid[k]; if (l) { var i = l.indexOf(b); if (i >= 0) l.splice(i, 1); } }); + cells.forEach(function (k) { (W.grid[k] = W.grid[k] || []).push(b); }); + b._cells = cells; + } + + // ------------------------------------------------------------------ getting in and out + function doorPoint(v, out) { var c = Math.cos(v.yaw), s = Math.sin(v.yaw), lx = v.ty.wid / 2 + 0.55, lz = v.ty.doorZ; return out.set(v.pos.x + lx * c + lz * s, v.pos.y, v.pos.z - lx * s + lz * c); } + var _dp = new T.Vector3(), _a = new T.Vector3(), _b = new T.Vector3(); + V.near = function (p) { + var best = null, bd = 2.3; + V.list.forEach(function (v) { + if (v.driver || v.dead || (v.traffic && Math.abs(v.v) > 3)) return; + var d = Math.min(doorPoint(v, _dp).distanceTo(p.pos), Math.hypot(v.pos.x - p.pos.x, v.pos.z - p.pos.z) - v.ty.wid / 2); + if (Math.abs(v.pos.y - p.pos.y) < 1.8 && d < bd) { bd = d; best = v; } + }); + return best; + }; + V.enter = function (p, v) { + if (p.state !== 'move' || v.driver || p.st < 0.3) return false; // (not on the frame you got out) + if (v.traffic && RP.Traffic) RP.Traffic.eject(v, p.pos); // the driver is pulled out and runs + v.driver = p; p.vehicle = v; RP.Player.setState(p, 'drive'); + v.box.see = true; // sight passes through the glass to the driver (bullets still hit the bodywork; see onHit) + p.speed = 0; p.cover = null; p.reload = null; p.melee = null; p.stealth = false; p.sprinting = false; + // only one-handed guns and SMGs can be used at the wheel + var d = RP.Weapons.DEFS[p.cur]; + if (!(d.oneHand && !d.melee) && d.cat !== 'smg') { + var alt = RP.Items.slotOf(p, 'pistol') || RP.Items.slotOf(p, 'smg'); + RP.Player.equip(p, alt || 'fists', true); + } + p.actor.playFull('sitIdle', { fade: 0.2, loop: true, hold: true }); + RP.Audio.mech('close', p.pos); startEngine(v); + RP.emit('toast', v.ty.name); + return true; + }; + V.exit = function (p, bail) { + var v = p.vehicle; if (!v) return; + var c = Math.cos(v.yaw), s = Math.sin(v.yaw), ok = false, y = v.pos.y; + // out of the driver's side if there is room, else the other side, else over the back + [[1, v.ty.doorZ], [-1, v.ty.doorZ], [0, -v.ty.len / 2 - 0.8]].some(function (o) { + var lx = o[0] * (v.ty.wid / 2 + 0.6), lz = o[1], x = v.pos.x + lx * c + lz * s, z = v.pos.z - lx * s + lz * c; + var g = W.ground(x, z, v.pos.y + 1.2); + if (v.ty.water ? (g.y > W.water - 0.25 && g.y < v.pos.y + 1.6) : (!g.water && Math.abs(g.y - v.pos.y) < 1.3)) { + v.box.off = true; var free = !W.blocked || !W.blocked(x, z, 0.35, g.y); v.box.off = false; + if (free) { p.pos.set(x, g.y, z); ok = true; return true; } + } + return false; + }); + if (!ok) { if (v.ty.water) { RP.emit('toast', 'Bring her alongside a quay to get out'); return; } p.pos.set(v.pos.x + (v.ty.wid / 2 + 0.6) * c, y, v.pos.z - (v.ty.wid / 2 + 0.6) * s); } + v.driver = null; p.vehicle = null; p.yaw = v.yaw; v.box.see = false; + p.actor.stopFull(0.2); RP.Player.setState(p, 'move'); + p.vel.set(Math.sin(v.yaw) * v.v, 0, Math.cos(v.yaw) * v.v); + if (bail && Math.abs(v.v) > 5.5 && RP.Player.tumble) RP.Player.tumble(p, p.vel.clone().multiplyScalar(0.6)); + RP.Audio.mech('close', p.pos); stopEngine(); + }; + + // ------------------------------------------------------------------ driving + var _g = {}, _f = new T.Vector3(), _r = new T.Vector3(); + function drive(v, dt, thr, st, hb) { + var ty = v.ty, top = ty.top; + if (v.dead) { thr = 0; hb = true; } + // throttle, brake, reverse + if (thr > 0.05) { if (v.v < -0.5) v.v += ty.brake * dt; else v.v += ty.accel * thr * (1 - M.clamp(v.v / top, 0, 1) * 0.92) * dt; } + else if (thr < -0.05) { if (v.v > 0.6) v.v -= ty.brake * -thr * dt; else v.v = Math.max(-top * 0.28, v.v + ty.accel * 0.7 * thr * dt); } + var drag = (ty.water ? 0.9 : 0.35) + 0.0022 * v.v * v.v + (hb ? 7 : 0); + v.v -= Math.sign(v.v) * Math.min(Math.abs(v.v), drag * dt); + if (v.air) thr = 0; + // steering: less lock at speed; slip opens past the grip limit or on the handbrake + var sp = Math.abs(v.v), lock = M.lerp(0.62, 0.11, M.clamp(sp / top, 0, 1)); + v.steer = M.damp(v.steer, st * lock, ty.water ? 3 : 9, dt); + var wb = ty.wb || ty.len * 0.5, yawRate = v.air ? 0 : v.v / wb * Math.tan(v.steer) * (ty.water ? M.clamp(sp / 4, 0, 1) : 1); + var latA = Math.abs(v.v * yawRate), limit = 9.5 * ty.grip * (hb ? 0.45 : 1); + var over = Math.max(0, latA - limit) / limit; + var slipT = (over > 0 || hb && sp > 4 ? Math.sign(yawRate) * Math.min(0.6, 0.18 + over * 0.6) : 0) * (ty.water ? 1.6 : 1); + v.slip = M.damp(v.slip, slipT, slipT ? 3.5 : 5, dt); + if (hb && sp > 4) yawRate *= 1.35; + if (Math.abs(v.slip) > 0.05) v.v -= Math.sign(v.v) * Math.abs(v.slip) * 9 * dt; + v.yaw += yawRate * dt; + v.screech = Math.abs(v.slip) > 0.14 && sp > 6 && !ty.water; + // move as two circles (front and rear axle) so walls and kerbs turn the body + var head = v.yaw - v.slip, dx = Math.sin(head) * v.v * dt, dz = Math.cos(head) * v.v * dt, half = (ty.wb || ty.len * 0.6) / 2, rad = ty.wid / 2 + 0.05; + _f.set(v.pos.x + Math.sin(v.yaw) * half, v.pos.y, v.pos.z + Math.cos(v.yaw) * half); _r.set(v.pos.x - Math.sin(v.yaw) * half, v.pos.y, v.pos.z - Math.cos(v.yaw) * half); + var fx = _f.x + dx, fz = _f.z + dz, rx = _r.x + dx, rz = _r.z + dz; + v.box.off = true; + if (ty.water) { + // open water only: the shore, quays and rocks stop the hull + var gf = W.ground(fx, fz, W.water + 0.3).y, gr = W.ground(rx, rz, W.water + 0.3).y; + if (gf > W.water - 0.45 || gr > W.water - 0.45) { v.v *= -0.25; v.hit = Math.abs(v.v); } + else { _f.x = fx; _f.z = fz; _r.x = rx; _r.z = rz; } + } else { + var fy0 = W.ground(_f.x, _f.z, v.pos.y + 0.7, 0.5).y, ry0 = W.ground(_r.x, _r.z, v.pos.y + 0.7, 0.5).y; + var ox0 = _f.x, oz0 = _f.z, ox1 = _r.x, oz1 = _r.z; + W.move(_f, dx, dz, rad, 1.2, 0.32); var hitBox = W.lastHit.box; W.move(_r, dx, dz, rad, 1.2, 0.32); hitBox = hitBox || W.lastHit.box; + // no driving up hillsides and cliffs: ground ahead rising steeper than about 35 degrees stops the car like a wall + // (stairs and kerbs are boxes and are handled by the step height above; this is the terrain itself) + if (!v.air) { + var lead = v.v >= 0 ? _f : _r, lx0 = v.v >= 0 ? ox0 : ox1, lz0 = v.v >= 0 ? oz0 : oz1, ly0 = v.v >= 0 ? fy0 : ry0; + var run = Math.hypot(lead.x - lx0, lead.z - lz0); + if (run > 1e-4) { + var ly1 = W.ground(lead.x, lead.z, v.pos.y + 0.7, 0.5).y; + if ((ly1 - ly0) / run > 0.7) { _f.x = ox0; _f.z = oz0; _r.x = ox1; _r.z = oz1; if (sp > 3) v.hit = sp * 0.6; v.v *= 0.4; } + } + } + var lost = Math.hypot(_f.x - fx, _f.z - fz) + Math.hypot(_r.x - rx, _r.z - rz); + if (lost > 0.02 * Math.max(1, sp * dt * 20)) { + var hitK = M.clamp(lost / Math.max(1e-3, sp * dt), 0, 1); + // an impact is speed lost at once: only a real hit (more than 3 m/s gone) shakes and damages the car; + // leaning on a wall or scraping a parapet just slows it + if (hitK > 0.35 && sp * hitK > 3) { + // the player's car is tougher than the rest (it has to last a chase); a car you hit takes the knock too + v.hit = sp * hitK; v.hp -= (sp * hitK - 3) * (v.driver === RP.G.player ? 0.4 : 0.8); if (v.hp <= 0 && !v.dead) kill(v); + var ov = hitBox && hitBox.veh; + if (ov && ov !== v && !ov.ty.water) { + ov.hit = Math.max(ov.hit || 0, sp * hitK); ov.hp -= (sp * hitK - 3) * 0.6; if (ov.hp <= 0 && !ov.dead) kill(ov); + ov.v += Math.cos(ov.yaw - v.yaw) * sp * hitK * 0.35; // shunted along its own heading + if (ov.traffic && RP.Traffic) RP.Traffic.hit(ov, v.pos.clone()); + } + } + v.v *= 1 - hitK * (hitK > 0.35 ? 0.8 : 0.3); + } + } + v.pos.x = (_f.x + _r.x) / 2; v.pos.z = (_f.z + _r.z) / 2; // (its own box stays out of the ground queries below: a low car would climb onto itself) + var ny = Math.atan2(_f.x - _r.x, _f.z - _r.z); v.yaw += M.wrap(ny - v.yaw); + // the ground under the wheels: height, pitch, roll; falling + if (ty.water) { + v.bobT += dt; v.pos.y = W.water + Math.sin(v.bobT * 1.3) * 0.05 + Math.min(0.22, sp * 0.012); + v.pitch = M.damp(v.pitch, -Math.min(0.14, sp * 0.008) + Math.sin(v.bobT * 1.1) * 0.02, 3, dt); v.roll = M.damp(v.roll, v.steer * sp * 0.035 + Math.sin(v.bobT * 0.8) * 0.02, 3, dt); + } else { + var hf = W.ground(_f.x, _f.z, v.pos.y + 0.7, 0.5, _g).y, hr = W.ground(_r.x, _r.z, v.pos.y + 0.7, 0.5, _g).y; + var c = Math.cos(v.yaw), s = Math.sin(v.yaw), tw = ty.track / 2; + var hl = W.ground(v.pos.x + c * tw, v.pos.z - s * tw, v.pos.y + 0.7, 0.5, _g).y, hrr = W.ground(v.pos.x - c * tw, v.pos.z + s * tw, v.pos.y + 0.7, 0.5, _g).y; + var gy = (hf + hr) / 2; + if (v.pos.y > gy + 0.25) { v.air = true; v.vy -= 9.8 * 1.6 * dt; v.pos.y += v.vy * dt; if (v.pos.y <= gy) { v.pos.y = gy; if (v.vy < -6) { v.hit = -v.vy; v.hp -= -v.vy * 2; } v.vy = 0; v.air = false; } } + else { v.air = false; v.vy = 0; v.pos.y = M.damp(v.pos.y, gy, 22, dt); } + var pt = Math.atan2(hr - hf, ty.wb), rl = Math.atan2(hl - hrr, ty.track); + v.pitch = M.damp(v.pitch, v.air ? v.pitch : pt - M.clamp((v.v - (v._lv || 0)) / Math.max(dt, 1e-3), -20, 20) * 0.004, 10, dt); + v.roll = M.damp(v.roll, v.air ? v.roll : rl - v.v * yawRate * 0.012, 10, dt); + if (hf < W.water - 0.35 && hr < W.water - 0.35) { v.dead = true; v.v = 0; if (v.driver) { RP.emit('toast', 'Flooded'); V.exit(v.driver); } } + } + v._lv = v.v; + v.box.off = false; + } + // people in the way + function hitPeople(v) { + var pl = RP.G.player; + var sp = Math.abs(v.v); if (sp < 0.8) return; + var c = Math.cos(v.yaw), s = Math.sin(v.yaw), hx = v.ty.wid / 2 + 0.3, hz = v.ty.len / 2 + 0.3, dir = Math.sign(v.v); + function local(e) { var dx = e.pos.x - v.pos.x, dz = e.pos.z - v.pos.z; _a.set(dx * c - dz * s, 0, dx * s + dz * c); return Math.abs(_a.x) < hx && Math.abs(_a.z) < hz && Math.abs(e.pos.y - v.pos.y) < 1.6; } + RP.G.guards.forEach(function (g) { + if (!g.alive || !local(g)) return; + var imp = new T.Vector3(Math.sin(v.yaw) * dir, 0.45, Math.cos(v.yaw) * dir).multiplyScalar(Math.min(9, sp * 0.7)); + if (sp > 4 && !v.traffic) { g.takeDamage(sp * 7, { dir: imp.clone().normalize(), force: Math.min(6, sp * 0.4), from: v.driver, vehicle: true }); v.v *= 0.9; RP.Cam.shake(0.25); RP.Audio.impact && RP.Audio.impact('car', g.pos, 1.5); } + else { g.pos.x += Math.sign(_a.x || 1) * c * 0.06; g.pos.z -= Math.sign(_a.x || 1) * s * 0.06; } + }); + // a Halcyon car into the player on foot + if (v.ai && pl && pl.alive && !pl.vehicle && pl.state !== 'ragdoll' && local(pl) && sp > 4) { + pl.takeDamage(sp * 3.5, { dir: new T.Vector3(Math.sin(v.yaw) * dir, 0, Math.cos(v.yaw) * dir) }); + if (pl.alive && RP.Player.tumble) RP.Player.tumble(pl, new T.Vector3(Math.sin(v.yaw) * dir * sp * 0.5, 2.5, Math.cos(v.yaw) * dir * sp * 0.5)); + v.v *= 0.7; + } + RP.G.civilians.forEach(function (cv) { + if (!v.traffic && cv.pos.distanceTo(v.pos) < 9 && sp > 3 && cv.scare) cv.scare(v.pos, 4); + if (!local(cv)) return; + var sd = Math.sign(_a.x || 1); cv.pos.x += sd * c * (hx - Math.abs(_a.x) + 0.05); cv.pos.z -= sd * s * (hx - Math.abs(_a.x) + 0.05); // shoved clear, never hurt + }); + } + + // the driver each frame (called from the player's state machine) + V.stepDriver = function (p, dt) { + var v = p.vehicle, I = RP.In; + var thr = I.move.y, st = -I.move.x, hb = I.down('jump'); + drive(v, dt, thr, st, hb); hitPeople(v); + if (v.hit > 3) { RP.Cam.shake(Math.min(0.9, v.hit * 0.05)); RP.Audio.impact && RP.Audio.impact('car', v.pos, Math.min(2, v.hit * 0.15)); if (v.hit > 17) p.takeDamage((v.hit - 8) * 1.4, {}); } // (a big smash hurts; scrapes and knocks don't) + v.hit = 0; + // the player rides in the seat + var c = Math.cos(v.yaw), s = Math.sin(v.yaw), se = v.ty.seat; + p.pos.set(v.pos.x + se[0] * c + se[2] * s, v.pos.y + se[1] - 0.63 * (p.actor.height / 1.8) * 1.04, v.pos.z - se[0] * s + se[2] * c); // seat height is where the hips sit (the sitting clip's hips are 0.63 m above its root) + p.yaw = v.yaw; p.speed = 0; p.vel.set(Math.sin(v.yaw) * v.v, 0, Math.cos(v.yaw) * v.v); p.onGround = true; + p.noise = Math.abs(v.v) > 2 ? 22 : 8; + if (I.pressed('enter') || I.pressed('interact')) V.exit(p, true); + }; + // level of detail by camera distance: 0 the full car, 1 one mesh, 2 not drawn + var FAR_D = { low: 30, medium: 50, high: 80 }; + function setLod(v, lvl) { + if (v.lod === lvl) return; v.lod = lvl; + var g = v.g, far = g.userData.far; + g.visible = lvl < 2; + g.children.forEach(function (c) { c.visible = c === far ? lvl === 1 : lvl === 0; }); + } + V.update = function (dt) { + var p = RP.G.player, cam = RP.R.camera, qn = RP.R.qname, farD = FAR_D[qn] || 50; + var hideD = Math.max(160, ((RP.B && RP.B.range && RP.B.range.civ) || 240) * 1.5); + for (var i = 0; i < V.list.length; i++) { + var v = V.list[i]; + var cd = cam.position.distanceTo(v.pos); + setLod(v, v.driver === p || cd < farD ? 0 : cd < hideD ? 1 : 2); + if (v.traffic && RP.Traffic) RP.Traffic.step(v, dt); + else if (v.ai) stepAI(v, dt); + else if (!v.driver && (Math.abs(v.v) > 0.05 || v.air)) { drive(v, dt, 0, 0, true); hitPeople(v); v.hit = 0; } // rolls to a stop + if (v.dead && !v.ty.water) { v.smokeT = (v.smokeT || 0) - dt; if (v.smokeT <= 0) { v.smokeT = 0.14; RP.FX.dust(v.pos.x + Math.sin(v.yaw) * 1.3, v.pos.y + 0.9, v.pos.z + Math.cos(v.yaw) * 1.3, 0, 1, 0, '#2b2b2b', 1, 1.1, 0.8); } } + var g = v.g; g.position.copy(v.pos); g.rotation.set(v.pitch, v.yaw, v.roll, 'YXZ'); + v.spinA += v.v * dt / (v.ty.wheelR || 1); + for (var k = 0; k < g.userData.wheels.length; k++) { var w = g.userData.wheels[k]; w.spin.rotation.x = v.spinA; if (w.front) w.piv.rotation.y = v.steer; } + if (g.userData.wheel) g.userData.wheel.rotation.z = -v.steer * 2.2; + syncBox(v); + } + // prompt + if (p && p.alive && p.state === 'move' && !RP.HUD.interact) { var nv = V.near(p); V._near = nv; if (nv) RP.HUD.interact = (nv.ty.water || nv.traffic ? 'Take the ' : 'Drive the ') + nv.ty.name; } else V._near = null; + // a driver who was killed or thrown out leaves the car + V.list.forEach(function (v) { if (v.driver && (v.driver.state !== 'drive' || !v.driver.alive)) { v.driver.vehicle = null; v.driver = null; v.box.see = false; stopEngine(); } }); + engine(p && p.vehicle, dt); + speedo(p && p.vehicle); + }; + V.drive = drive; V.hitPeople = hitPeople; V.syncBox = syncBox; + V.interact = function (p) { if (p.vehicle) return false; var v = V._near || V.near(p); return v ? V.enter(p, v) : false; }; + + // the driver's hands on the wheel (called after the actor's pose is made) + var _hl = new T.Vector3(), _hr = new T.Vector3(), _pl = new T.Vector3(); + V.pose = function (p) { + var v = p.vehicle, a = p.actor, b = a.bones, w = v.g.userData.wheel; if (!w || !RP.Chars.ikPole) return; + w.updateMatrixWorld(true); + _hl.set(0.16, 0.02, 0).applyMatrix4(w.matrixWorld); _hr.set(-0.16, 0.02, 0).applyMatrix4(w.matrixWorld); + var rq = a.root.quaternion; + b.upperarm_l.getWorldPosition(_pl).add(_a.set(0.4, -1, 0).applyQuaternion(rq)); RP.Chars.ikPole(b.upperarm_l, b.lowerarm_l, b.hand_l, _hl, _pl, 1); + // feet to the pedals, knees up (the sitting clip is a chair; a car seat is lower with the legs out in front) + var c = Math.cos(v.yaw), sn = Math.sin(v.yaw), se = v.ty.seat, fy = v.pos.y + (v.ty.water ? 0.36 : 0.26); + ['l', 'r'].forEach(function (sd, i) { + var lx = se[0] + (i ? -0.11 : 0.13), lz = se[2] + 0.78; + _hl.set(v.pos.x + lx * c + lz * sn, fy, v.pos.z - lx * sn + lz * c); + b['thigh_' + sd].getWorldPosition(_pl).add(_a.set(0, 1, 0.6).applyQuaternion(rq)); + RP.Chars.ikPole(b['thigh_' + sd], b['calf_' + sd], b['foot_' + sd], _hl, _pl, 1); + }); + w.updateMatrixWorld(true); _hl.set(0.16, 0.02, 0).applyMatrix4(w.matrixWorld); + if (!p.aiming && !(p.hipT > 0)) { b.upperarm_r.getWorldPosition(_pl).add(_a.set(-0.4, -1, 0).applyQuaternion(rq)); RP.Chars.ikPole(b.upperarm_r, b.lowerarm_r, b.hand_r, _hr, _pl, 1); } + }; + + // ------------------------------------------------------------------ engine sound and speedometer + var eng = null; + function startEngine(v) { + var ctx = RP.Audio && RP.Audio.ctx; if (!ctx || eng) return; + try { + var o1 = ctx.createOscillator(), o2 = ctx.createOscillator(), lp = ctx.createBiquadFilter(), g = ctx.createGain(); + o1.type = 'sawtooth'; o2.type = 'square'; lp.type = 'lowpass'; lp.frequency.value = 500; g.gain.value = 0; + o1.connect(lp); o2.connect(lp); lp.connect(g); g.connect(RP.Audio.sfxBus || ctx.destination); o1.start(); o2.start(); + eng = { o1: o1, o2: o2, lp: lp, g: g, water: !!v.ty.water }; + } catch (e) { eng = null; } + } + function stopEngine() { if (!eng) return; try { eng.g.gain.setTargetAtTime(0, RP.Audio.ctx.currentTime, 0.1); var e = eng; setTimeout(function () { try { e.o1.stop(); e.o2.stop(); } catch (x) {} }, 500); } catch (x) {} eng = null; } + function engine(v, dt) { + if (!eng || !v) return; + var ctx = RP.Audio.ctx, sp = Math.abs(v.v), top = v.ty.top; + // revs rise through four "gears" + var gr = Math.min(3, Math.floor(sp / top * 4)), inGear = (sp / top * 4) - gr, rev = 0.25 + 0.75 * inGear; + var f = (eng.water ? 38 : 46) + rev * (eng.water ? 50 : 95) + gr * 6; + eng.o1.frequency.setTargetAtTime(f, ctx.currentTime, 0.06); eng.o2.frequency.setTargetAtTime(f * 0.5, ctx.currentTime, 0.06); + eng.lp.frequency.setTargetAtTime(350 + rev * 900 + Math.abs(RP.In.move.y) * 500, ctx.currentTime, 0.08); + eng.g.gain.setTargetAtTime((0.05 + 0.05 * Math.abs(RP.In.move.y)) * (RP.settings.volume == null ? 1 : RP.settings.volume), ctx.currentTime, 0.1); + } + var spEl = null; + function speedo(v) { + if (!spEl) { spEl = document.createElement('div'); spEl.id = 'vSpeed'; spEl.style.cssText = 'position:absolute;right:18px;bottom:96px;font:700 30px/1 var(--f-cond,sans-serif);letter-spacing:.02em;color:#f6f1e7;text-shadow:0 1px 3px rgba(0,0,0,.6);display:none'; var h = document.getElementById('hud'); if (h) h.appendChild(spEl); } + if (!v) { if (spEl.style.display !== 'none') spEl.style.display = 'none'; return; } + spEl.style.display = 'block'; + var txt = v.ty.water ? Math.round(Math.abs(v.v) * 1.944) + ' kn' : Math.round(Math.abs(v.v) * 3.6) + ' km/h'; + if (spEl.textContent !== txt) spEl.textContent = txt; + } +})(); diff --git a/e63334287a3deaa3/blacktie/js/weapons.js b/e63334287a3deaa3/blacktie/js/weapons.js new file mode 100644 index 00000000..8caafaad --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/weapons.js @@ -0,0 +1,141 @@ +/* + * Weapons (RP.Weapons): the stats of every weapon, its wheel category, and a small model made in code for each. + * All names are invented. Balance rule: no weapon is best at everything (see README: damage x rate x accuracy x + * range x handling trade off against each other, and heavier weapons slow you down). + * + * Stat units: dmg per bullet (or per pellet), rpm rounds a minute, spread degrees (hip / aimed), recoil degrees per + * shot (up, side random), recover degrees a second, range m (full damage up to r0, falls to minFrac at r1), + * reload s, aimTime s (handling), weight (speed multiplier), mag/reserve rounds. + * + * Model contract: barrel along +Z, up +Y, origin at the right-hand grip; userData.muzzle (Object3D), userData.gripL + * (left hand), userData.eject (shell ejection port). Built from boxes and cylinders and merged into 1-2 meshes. + */ +(function () { + 'use strict'; + var T = THREE; + var W = RP.Weapons = {}; + W.CATS = ['melee', 'pistol', 'smg', 'rifle', 'shotgun', 'sniper', 'heavy', 'throw']; + W.CAT_NAMES = { melee: 'Melee', pistol: 'Pistols', smg: 'SMG', rifle: 'Rifles', shotgun: 'Shotguns', sniper: 'Sniper', heavy: 'Heavy', throw: 'Throwables' }; + + W.DEFS = { + // ---------------------------------------------------------------- melee (speed = swing time scale; reach m) + fists: { name: 'Fists', cat: 'melee', melee: true, dmg: 14, reach: 1.05, speed: 1, move: 'jab', recovery: 0.12, weight: 1, unarmed: true }, + knife: { name: 'Folding Knife', cat: 'melee', melee: true, dmg: 34, reach: 1.15, speed: 1.25, move: 'stab', recovery: 0.1, weight: 1, quiet: true }, + bat: { name: 'Slugger Bat', cat: 'melee', melee: true, dmg: 42, reach: 1.6, speed: 0.85, move: 'bigSwing', recovery: 0.35, weight: 0.97, knock: 1.6 }, + crowbar: { name: 'Pry Bar', cat: 'melee', melee: true, dmg: 36, reach: 1.4, speed: 0.95, move: 'swing', recovery: 0.25, weight: 0.98, knock: 1.1 }, + hammer: { name: 'Claw Hammer', cat: 'melee', melee: true, dmg: 40, reach: 1.15, speed: 1.0, move: 'chop', recovery: 0.28, weight: 0.99, knock: 0.9 }, + club: { name: 'Nine Iron', cat: 'melee', melee: true, dmg: 30, reach: 1.75, speed: 0.95, move: 'bigSwing', recovery: 0.3, weight: 0.99, knock: 1.3 }, + machete: { name: 'Cane Knife', cat: 'melee', melee: true, dmg: 48, reach: 1.35, speed: 0.9, move: 'chop', recovery: 0.32, weight: 0.98 }, + // ---------------------------------------------------------------- firearms + corsa: { name: 'Corsa 9', cat: 'pistol', dmg: 24, rpm: 360, mag: 15, reserve: 90, reload: 1.5, rtype: 'mag', spread: [2.6, 0.7], recoil: [1.5, 0.6], recover: 22, range: [22, 55], minFrac: 0.55, aimTime: 0.16, weight: 1, oneHand: true, auto: false, snd: 'pistol', vel: 360 }, + bastion: { name: 'Bastion .44', cat: 'pistol', dmg: 58, rpm: 110, mag: 6, reserve: 36, reload: 2.6, rtype: 'revolver', spread: [3.2, 0.5], recoil: [5.2, 1.2], recover: 14, range: [28, 70], minFrac: 0.6, aimTime: 0.22, weight: 0.99, oneHand: true, auto: false, snd: 'revolver', vel: 420 }, + vespa: { name: 'Vespa SMG', cat: 'smg', dmg: 17, rpm: 820, mag: 32, reserve: 192, reload: 1.9, rtype: 'mag', spread: [4.2, 1.6], recoil: [0.85, 0.65], recover: 18, range: [16, 45], minFrac: 0.45, aimTime: 0.2, weight: 0.98, auto: true, snd: 'smg', vel: 380 }, + tern: { name: 'Tern Carbine', cat: 'rifle', dmg: 27, rpm: 640, mag: 30, reserve: 180, reload: 2.3, rtype: 'mag', spread: [3.8, 0.55], recoil: [1.1, 0.55], recover: 15, range: [40, 120], minFrac: 0.6, aimTime: 0.27, weight: 0.95, auto: true, snd: 'rifle', vel: 880 }, + gale: { name: 'Gale AR', cat: 'rifle', dmg: 33, rpm: 560, mag: 25, reserve: 150, reload: 2.5, rtype: 'mag', spread: [4.6, 0.45], recoil: [1.6, 0.8], recover: 13, range: [55, 150], minFrac: 0.62, aimTime: 0.32, weight: 0.93, auto: true, snd: 'rifle2', vel: 900 }, + breaker: { name: 'Breaker Pump', cat: 'shotgun', dmg: 13, pellets: 9, rpm: 70, mag: 6, reserve: 42, reload: 0.5, rtype: 'shell', spread: [6.5, 4.6], recoil: [6.5, 1.6], recover: 12, range: [7, 24], minFrac: 0.15, aimTime: 0.3, weight: 0.95, auto: false, pump: 0.55, snd: 'shotgun', vel: 380 }, + twinbore: { name: 'Twinbore', cat: 'shotgun', dmg: 15, pellets: 10, rpm: 300, mag: 2, reserve: 30, reload: 2.2, rtype: 'break', spread: [7.5, 5.5], recoil: [8, 2], recover: 10, range: [6, 20], minFrac: 0.12, aimTime: 0.28, weight: 0.96, auto: false, snd: 'shotgun2', vel: 360 }, + longreach:{ name: 'Longreach', cat: 'sniper', dmg: 110, rpm: 48, mag: 5, reserve: 30, reload: 3.0, rtype: 'mag', spread: [9, 0.05], recoil: [6, 1], recover: 6, range: [200, 400], minFrac: 0.8, aimTime: 0.5, weight: 0.9, auto: false, scope: true, bolt: 1.0, snd: 'sniper', vel: 900 }, + mauler: { name: 'Mauler LMG', cat: 'heavy', dmg: 29, rpm: 700, mag: 100, reserve: 300, reload: 5.2, rtype: 'belt', spread: [6.5, 1.5], recoil: [1.0, 1.0], recover: 9, range: [50, 130], minFrac: 0.6, aimTime: 0.55, weight: 0.82, auto: true, snd: 'mg', vel: 850 }, + thumper: { name: 'Thumper GL', cat: 'heavy', proj: 'grenade', dmg: 120, radius: 5.5, rpm: 60, mag: 1, reserve: 10, reload: 1.6, rtype: 'single', spread: [2, 0.8], recoil: [4, 1], recover: 8, range: [0, 0], aimTime: 0.4, weight: 0.88, auto: false, snd: 'gl', vel: 34 }, + hornet: { name: 'Hornet RL', cat: 'heavy', proj: 'rocket', dmg: 220, radius: 6.5, rpm: 30, mag: 1, reserve: 5, reload: 2.8, rtype: 'single', spread: [3, 0.3], recoil: [6, 1], recover: 6, range: [0, 0], aimTime: 0.6, weight: 0.85, auto: false, snd: 'rl', vel: 55 }, + // ---------------------------------------------------------------- throwables (G to throw; dmg at the centre) + frag: { name: 'Frag Grenade', cat: 'throw', throw: 'frag', dmg: 130, radius: 6, fuse: 3.0, mag: 1, reserve: 4, weight: 1 }, + sticky: { name: 'Sticky Charge', cat: 'throw', throw: 'sticky', dmg: 160, radius: 5, fuse: 0, mag: 1, reserve: 3, weight: 1 }, + smoke: { name: 'Smoke Canister', cat: 'throw', throw: 'smoke', dmg: 0, radius: 7, fuse: 1.2, mag: 1, reserve: 3, weight: 1 } + }; + Object.keys(W.DEFS).forEach(function (k) { W.DEFS[k].id = k; }); + W.byCat = function (cat) { return Object.keys(W.DEFS).filter(function (k) { return W.DEFS[k].cat === cat; }); }; + + // ------------------------------------------------------------------ models + var MATS = null; + function mats() { + if (MATS) return MATS; + var std = function (hex, r, m) { return new T.MeshStandardMaterial({ color: RP.col(hex), roughness: r, metalness: m }); }; + MATS = { steel: std('#2a2c2f', 0.38, 0.85), black: std('#151617', 0.55, 0.3), poly: std('#1d1e1f', 0.7, 0.05), wood: std('#6b4528', 0.6, 0), tan: std('#8a7a5c', 0.7, 0.05), + blade: std('#b8bcc0', 0.22, 1), grip: std('#2b1d14', 0.8, 0), alu: std('#9aa0a6', 0.35, 0.9), green: std('#3f4a36', 0.6, 0.2), red: std('#8a2b22', 0.5, 0.1), yellow: std('#b59a3a', 0.5, 0.2) }; + return MATS; + } + function part(list, mat, geo, x, y, z, rx) { var m = new T.Mesh(geo, mat); m.position.set(x, y, z); if (rx) m.rotation.x = rx; list.push(m); return m; } + function box(w, h, d) { return new T.BoxGeometry(w, h, d); } + function cyl(r, l, s) { var g = new T.CylinderGeometry(r, r, l, s || 10); g.rotateX(Math.PI / 2); return g; } + // merge parts by material into one mesh each + function assemble(parts, opts) { + var g = new T.Group(), byMat = new Map(); + parts.forEach(function (p) { p.updateMatrix(); var geo = p.geometry.clone().applyMatrix4(p.matrix); if (!byMat.has(p.material)) byMat.set(p.material, []); byMat.get(p.material).push(geo); }); + byMat.forEach(function (list, mat) { + var merged = RP.B.mergeGeos(list.map(function (q) { return q.index ? q : q; })); + merged.computeVertexNormals(); + var m = new T.Mesh(merged, mat); m.castShadow = true; g.add(m); + }); + function pt(name, p) { var o = new T.Object3D(); o.position.set(p[0], p[1], p[2]); o.name = name; g.add(o); return o; } + g.userData.muzzle = pt('muzzle', opts.muzzle || [0, 0.03, 0.3]); + if (opts.gripL) g.userData.gripL = pt('gripL', opts.gripL); + g.userData.eject = pt('eject', opts.eject || [0.02, 0.05, 0.08]); + if (opts.oneHand) g.userData.oneHand = true; + return g; + } + var BUILD = { + corsa: function (M) { var p = []; part(p, M.black, box(0.03, 0.13, 0.04), 0, -0.04, -0.01); part(p, M.steel, box(0.032, 0.035, 0.2), 0, 0.045, 0.06); part(p, M.black, box(0.03, 0.03, 0.17), 0, 0.015, 0.06); return assemble(p, { muzzle: [0, 0.045, 0.165], oneHand: true, eject: [0.02, 0.06, 0.05] }); }, + bastion: function (M) { var p = []; part(p, M.wood, box(0.035, 0.12, 0.045), 0, -0.04, -0.02); part(p, M.alu, cyl(0.03, 0.06), 0, 0.03, 0.04); part(p, M.alu, cyl(0.012, 0.18, 8), 0, 0.045, 0.15); part(p, M.alu, box(0.025, 0.03, 0.12), 0, 0.03, 0.08); return assemble(p, { muzzle: [0, 0.045, 0.245], oneHand: true }); }, + vespa: function (M) { var p = []; part(p, M.black, box(0.045, 0.08, 0.3), 0, 0.03, 0.08); part(p, M.poly, box(0.03, 0.12, 0.04), 0, -0.05, 0); part(p, M.steel, box(0.025, 0.16, 0.035), 0, -0.06, 0.12); part(p, M.steel, cyl(0.012, 0.1), 0, 0.04, 0.27); part(p, M.poly, box(0.03, 0.05, 0.2), 0, 0.02, -0.14); return assemble(p, { muzzle: [0, 0.04, 0.32], gripL: [0, -0.04, 0.12] }); }, + tern: function (M) { var p = []; part(p, M.black, box(0.05, 0.08, 0.42), 0, 0.03, 0.1); part(p, M.poly, box(0.035, 0.12, 0.04), 0, -0.05, 0); part(p, M.steel, box(0.03, 0.15, 0.05), 0, -0.06, 0.1); part(p, M.steel, cyl(0.013, 0.3), 0, 0.045, 0.45); part(p, M.poly, box(0.05, 0.06, 0.26), 0, 0.04, 0.3); part(p, M.poly, box(0.04, 0.09, 0.24), 0, 0.0, -0.2); part(p, M.black, box(0.03, 0.035, 0.1), 0, 0.095, 0.07); return assemble(p, { muzzle: [0, 0.045, 0.6], gripL: [0, 0.0, 0.3] }); }, + gale: function (M) { var p = []; part(p, M.tan, box(0.055, 0.085, 0.44), 0, 0.03, 0.1); part(p, M.poly, box(0.035, 0.12, 0.04), 0, -0.05, 0); part(p, M.black, box(0.03, 0.17, 0.06), 0, -0.07, 0.11); part(p, M.steel, cyl(0.014, 0.34), 0, 0.045, 0.5); part(p, M.tan, box(0.055, 0.065, 0.28), 0, 0.04, 0.32); part(p, M.tan, box(0.04, 0.1, 0.26), 0, 0.0, -0.22); part(p, M.black, box(0.04, 0.05, 0.14), 0, 0.105, 0.08); return assemble(p, { muzzle: [0, 0.045, 0.67], gripL: [0, 0.0, 0.32] }); }, + breaker: function (M) { var p = []; part(p, M.black, box(0.05, 0.07, 0.3), 0, 0.03, 0.05); part(p, M.wood, box(0.04, 0.11, 0.3), 0, -0.02, -0.22); part(p, M.steel, cyl(0.016, 0.5), 0, 0.055, 0.42); part(p, M.steel, cyl(0.014, 0.42), 0, 0.02, 0.36); part(p, M.wood, cyl(0.026, 0.16), 0, 0.02, 0.34); return assemble(p, { muzzle: [0, 0.055, 0.67], gripL: [0, 0.0, 0.34] }); }, + twinbore: function (M) { var p = []; part(p, M.wood, box(0.04, 0.11, 0.34), 0, -0.02, -0.2); part(p, M.steel, box(0.05, 0.06, 0.1), 0, 0.03, 0.02); part(p, M.steel, cyl(0.016, 0.55), -0.016, 0.05, 0.34); part(p, M.steel, cyl(0.016, 0.55), 0.016, 0.05, 0.34); part(p, M.wood, box(0.045, 0.035, 0.22), 0, 0.02, 0.2); return assemble(p, { muzzle: [0, 0.05, 0.62], gripL: [0, 0.0, 0.22] }); }, + longreach: function (M) { var p = []; part(p, M.green, box(0.05, 0.09, 0.5), 0, 0.02, 0.05); part(p, M.green, box(0.04, 0.12, 0.3), 0, -0.01, -0.3); part(p, M.steel, cyl(0.014, 0.52), 0, 0.045, 0.56); part(p, M.black, cyl(0.025, 0.3), 0, 0.12, 0.06); part(p, M.black, box(0.02, 0.04, 0.04), 0, 0.09, 0.06); part(p, M.steel, box(0.02, 0.02, 0.05), 0.04, 0.06, -0.04); return assemble(p, { muzzle: [0, 0.045, 0.82], gripL: [0, -0.02, 0.26] }); }, + mauler: function (M) { var p = []; part(p, M.black, box(0.08, 0.1, 0.5), 0, 0.03, 0.08); part(p, M.poly, box(0.05, 0.1, 0.28), 0, 0.0, -0.28); part(p, M.steel, cyl(0.018, 0.45), 0, 0.045, 0.55); part(p, M.green, box(0.09, 0.11, 0.12), 0.07, -0.04, 0.06); part(p, M.black, box(0.03, 0.12, 0.04), 0, -0.05, 0); return assemble(p, { muzzle: [0, 0.045, 0.78], gripL: [0, -0.01, 0.3] }); }, + thumper: function (M) { var p = []; part(p, M.tan, box(0.06, 0.08, 0.3), 0, 0.02, 0.06); part(p, M.steel, cyl(0.04, 0.32), 0, 0.05, 0.3); part(p, M.poly, box(0.04, 0.1, 0.24), 0, -0.01, -0.2); part(p, M.black, box(0.03, 0.12, 0.04), 0, -0.05, 0); return assemble(p, { muzzle: [0, 0.05, 0.46], gripL: [0, 0.0, 0.28] }); }, + hornet: function (M) { var p = []; part(p, M.green, cyl(0.05, 1.0), 0, 0.06, 0.12); part(p, M.black, box(0.03, 0.12, 0.04), 0, -0.04, 0); part(p, M.black, box(0.03, 0.1, 0.04), 0, -0.03, 0.25); part(p, M.black, box(0.03, 0.05, 0.08), -0.05, 0.12, 0.1); return assemble(p, { muzzle: [0, 0.06, 0.62], gripL: [0, -0.02, 0.25] }); }, + knife: function (M) { var p = []; part(p, M.grip, box(0.025, 0.03, 0.1), 0, 0, 0); part(p, M.blade, box(0.006, 0.025, 0.12), 0, 0.005, 0.11); return assemble(p, { muzzle: [0, 0, 0.17], oneHand: true }); }, + bat: function (M) { var p = []; var g = new T.CylinderGeometry(0.035, 0.018, 0.82, 10); g.rotateX(Math.PI / 2); part(p, M.wood, g, 0, 0, 0.36); return assemble(p, { muzzle: [0, 0, 0.75], oneHand: true }); }, + crowbar: function (M) { var p = []; part(p, M.red, cyl(0.012, 0.7, 6), 0, 0, 0.3); part(p, M.red, box(0.02, 0.08, 0.02), 0, 0.03, 0.64); return assemble(p, { muzzle: [0, 0, 0.64], oneHand: true }); }, + hammer: function (M) { var p = []; part(p, M.wood, cyl(0.014, 0.34, 6), 0, 0, 0.12); part(p, M.steel, box(0.03, 0.12, 0.03), 0, 0.02, 0.28); return assemble(p, { muzzle: [0, 0, 0.3], oneHand: true }); }, + club: function (M) { var p = []; part(p, M.alu, cyl(0.008, 0.9, 6), 0, 0, 0.42); part(p, M.alu, box(0.025, 0.05, 0.09), 0, -0.02, 0.88); part(p, M.grip, cyl(0.014, 0.22, 8), 0, 0, 0.05); return assemble(p, { muzzle: [0, 0, 0.9], oneHand: true }); }, + machete: function (M) { var p = []; part(p, M.grip, box(0.025, 0.03, 0.12), 0, 0, 0); part(p, M.blade, box(0.004, 0.05, 0.42), 0, 0.01, 0.27); return assemble(p, { muzzle: [0, 0, 0.48], oneHand: true }); }, + frag: function (M) { var p = []; part(p, M.green, new T.SphereGeometry(0.035, 10, 8), 0, 0, 0.02); part(p, M.steel, box(0.012, 0.03, 0.012), 0, 0.04, 0.02); return assemble(p, { oneHand: true }); }, + sticky: function (M) { var p = []; part(p, M.yellow, box(0.08, 0.05, 0.06), 0, 0, 0.03); part(p, M.black, box(0.03, 0.02, 0.03), 0, 0.03, 0.03); return assemble(p, { oneHand: true }); }, + smoke: function (M) { var p = []; part(p, M.alu, cyl(0.03, 0.12), 0, 0, 0.04); return assemble(p, { oneHand: true }); } + }; + // ------------------------------------------------------------------ mods (found as pickups; fitted to the gun in hand) + W.MODS = { + suppressor: { name: 'Suppressor', cats: ['pistol', 'smg', 'rifle', 'sniper'], not: ['bastion'] }, + extmag: { name: 'Extended magazine', cats: ['pistol', 'smg', 'rifle'], not: ['bastion'] }, + scope: { name: 'Marksman scope', cats: ['smg', 'rifle'], not: [] }, + grip: { name: 'Foregrip', cats: ['smg', 'rifle', 'shotgun', 'heavy'], not: ['twinbore', 'hornet', 'thumper'] } + }; + W.canFit = function (id, mod) { var d = W.DEFS[id], m = W.MODS[mod]; return !!(d && m && m.cats.indexOf(d.cat) >= 0 && m.not.indexOf(id) < 0); }; + // the weapon's numbers with its mods on (cached per combination). Each mod trades something: + // suppressor: quiet (guards hear it from 18 m, not 80), a little less damage and reach + // extended magazine: half as many rounds again, a slower reload + // scope: tighter aimed fire and a closer view when aimed, slower to bring up + // foregrip: less climb and a steadier hip, a touch slower to aim + var _eff = {}; + W.eff = function (id, mods) { + var base = W.DEFS[id]; if (!mods) return base; + var key = id + ':' + Object.keys(mods).filter(function (k) { return mods[k]; }).sort().join('+'); + if (_eff[key]) return _eff[key]; + var d = Object.create(base); d.mods = mods; + if (mods.suppressor) { d.suppressed = true; d.dmg = Math.round(base.dmg * 0.92); d.range = [base.range[0] * 0.9, base.range[1] * 0.9]; } + if (mods.extmag) { d.mag = Math.round(base.mag * 1.5); d.reload = base.reload * 1.12; } + if (mods.scope) { d.spread = [base.spread[0], base.spread[1] * 0.55]; d.zoom = 0.62; d.aimTime = base.aimTime * 1.2; } + if (mods.grip) { d.recoil = [base.recoil[0] * 0.72, base.recoil[1] * 0.8]; d.spread = [(d.spread || base.spread)[0] * 0.85, (d.spread || base.spread)[1]]; d.aimTime = (d.aimTime || base.aimTime) * 1.05; } + return (_eff[key] = d); + }; + // put the mods on a model + W.dress = function (g, mods) { + if (!g || !mods) return g; + var mat = new T.MeshStandardMaterial({ color: RP.col('#18191b'), roughness: 0.5, metalness: 0.6 }), mz = g.userData.muzzle; + function add(geo, x, y, z) { var m = new T.Mesh(geo, mat); m.position.set(x, y, z); m.castShadow = true; g.add(m); return m; } + if (mods.suppressor && mz) { var c = new T.CylinderGeometry(0.017, 0.017, 0.16, 12); c.rotateX(Math.PI / 2); add(c, mz.position.x, mz.position.y, mz.position.z + 0.075); mz.position.z += 0.16; } + if (mods.scope) { var s = new T.CylinderGeometry(0.016, 0.019, 0.2, 12); s.rotateX(Math.PI / 2); add(s, 0, 0.115, 0.03); add(new T.BoxGeometry(0.016, 0.03, 0.05), 0, 0.085, 0.03); } + if (mods.grip && g.userData.gripL) { var gp = g.userData.gripL.position; add(new T.BoxGeometry(0.024, 0.085, 0.026), gp.x, gp.y - 0.055, gp.z); gp.y -= 0.06; } + if (mods.extmag && g.userData.mag) { g.userData.mag.scale.y = 1.32; } + return g; + }; + W.model = function (id) { + if (RP.GunModels) { var gm = RP.GunModels.build(id); if (gm) return gm; } + var f = BUILD[id]; if (!f) return null; + var g = f(mats()); g.userData.id = id; g.userData.long = !g.userData.oneHand; + return g; + }; +})(); diff --git a/e63334287a3deaa3/blacktie/js/world.js b/e63334287a3deaa3/blacktie/js/world.js new file mode 100644 index 00000000..c9f68096 --- /dev/null +++ b/e63334287a3deaa3/blacktie/js/world.js @@ -0,0 +1,487 @@ +/* + * The gameplay world: collision boxes, the terrain heightfield, ground queries, character movement against walls, + * ray casts (bullets, sight lines), a navigation grid with A*, and cover points for the AI. + * + * Everything here comes from map data, never from what was rendered, so a lower quality preset can't change where + * you can walk, what stops a bullet or where a guard takes cover. + * + * Box: { x, z, y0, y1, hx, hz, yaw, mat, cover, kind, ramp } (centre x/z, bottom y0, top y1, half sizes in its own frame) + * ramp: [topAtBack, topAtFront] makes the top slope along the box's local z (stairs, ramps): y1 is then the max. + * mat: 'stone' | 'plaster' | 'metal' | 'wood' | 'glass' | 'dirt' | 'water' | 'car' | 'cloth' (impact effects + sound) + * cover: true to make AI cover points along its sides. kind: free text ('house', 'wall', 'crate', ...). + * deck: true for a bridge or pier deck: the navigation grid stands on it even where the ground is far below. + * see: true for things sight lines pass (railings, foliage). nocol: true for boxes that only stop bullets. + */ +(function () { + 'use strict'; + var M = RP.M, TUN = RP.TUNING; + var W = RP.W = {}; + var CELL = 8; // m, broad-phase grid + + // The broad phase is a flat array of lists, one per 8 m cell over the map bounds (plus a margin), so a lookup is an + // index, not a string key: the long coast map makes a million of them while it builds its navigation grid. + var GX0 = 0, GZ0 = 0, GW = 1, GH = 1, GRID = []; + function cellList(gx, gz) { return gx < GX0 || gz < GZ0 || gx >= GX0 + GW || gz >= GZ0 + GH ? null : GRID[(gz - GZ0) * GW + (gx - GX0)]; } + function keyIdx(k) { + if (typeof k !== 'string') return -1; + var c = k.indexOf(','); if (c < 0) return -1; + var gx = +k.slice(0, c), gz = +k.slice(c + 1); + return gx >= GX0 && gz >= GZ0 && gx < GX0 + GW && gz < GZ0 + GH ? (gz - GZ0) * GW + (gx - GX0) : -1; + } + W.reset = function (bounds) { + W.boxes = []; W.bounds = bounds; // {x0, z0, x1, z1} + GX0 = Math.floor(bounds.x0 / CELL) - 2; GZ0 = Math.floor(bounds.z0 / CELL) - 2; + GW = Math.ceil(bounds.x1 / CELL) + 2 - GX0; GH = Math.ceil(bounds.z1 / CELL) + 2 - GZ0; + GRID = new Array(GW * GH); + // W.grid['gx,gz'] still reads and writes a cell's list (vehicles move their box through it this way) + W.grid = new Proxy({}, { + get: function (t, k) { var i = keyIdx(k); return i < 0 ? undefined : GRID[i]; }, + set: function (t, k, v) { var i = keyIdx(k); if (i >= 0) GRID[i] = v; return true; } + }); + W.hf = null; W.coverPts = []; W.coverGrid = {}; W.nav = null; W.water = -1e9; W.zones = []; + W._q = 0; + }; + + // ------------------------------------------------------------------ boxes + W.addBox = function (b) { + b.c = Math.cos(b.yaw || 0); b.s = Math.sin(b.yaw || 0); b.yaw = b.yaw || 0; + b.mat = b.mat || 'stone'; + b.id = W.boxes.length; + // world-space bounding radius on the ground plane + b.r = Math.sqrt(b.hx * b.hx + b.hz * b.hz); + W.boxes.push(b); + var gx0 = Math.floor((b.x - b.r) / CELL), gx1 = Math.floor((b.x + b.r) / CELL); + var gz0 = Math.floor((b.z - b.r) / CELL), gz1 = Math.floor((b.z + b.r) / CELL); + gx0 = Math.max(gx0, GX0); gz0 = Math.max(gz0, GZ0); gx1 = Math.min(gx1, GX0 + GW - 1); gz1 = Math.min(gz1, GZ0 + GH - 1); + for (var gx = gx0; gx <= gx1; gx++) for (var gz = gz0; gz <= gz1; gz++) { + var k = (gz - GZ0) * GW + (gx - GX0); (GRID[k] = GRID[k] || []).push(b); + } + return b; + }; + // after changing a box's x, z, yaw or size: put it in the right broad-phase cells again (moving things) + W.moveBox = function (b) { + for (var i = 0; i < GRID.length; i++) { var l = GRID[i]; if (l) { var k = l.indexOf(b); if (k >= 0) l.splice(k, 1); } } + b.c = Math.cos(b.yaw || 0); b.s = Math.sin(b.yaw || 0); b.r = Math.sqrt(b.hx * b.hx + b.hz * b.hz); + var gx0 = Math.max(Math.floor((b.x - b.r) / CELL), GX0), gx1 = Math.min(Math.floor((b.x + b.r) / CELL), GX0 + GW - 1), gz0 = Math.max(Math.floor((b.z - b.r) / CELL), GZ0), gz1 = Math.min(Math.floor((b.z + b.r) / CELL), GZ0 + GH - 1); + for (var gx = gx0; gx <= gx1; gx++) for (var gz = gz0; gz <= gz1; gz++) { var q = (gz - GZ0) * GW + (gx - GX0); (GRID[q] = GRID[q] || []).push(b); } + }; + // local coordinates of a world point in box b + function toLocal(b, x, z, out) { var dx = x - b.x, dz = z - b.z; out.x = dx * b.c - dz * b.s; out.z = dx * b.s + dz * b.c; return out; } + function toWorldDir(b, lx, lz, out) { out.x = lx * b.c + lz * b.s; out.z = -lx * b.s + lz * b.c; return out; } + W.toLocal = toLocal; W.toWorldDir = toWorldDir; + // top surface height of a box at a local point (ramps slope along local z) + function topAt(b, lz) { + if (!b.ramp) return b.y1; + var t = M.clamp((lz + b.hz) / (2 * b.hz), 0, 1); + return b.ramp[0] + (b.ramp[1] - b.ramp[0]) * t; + } + W.topAt = topAt; + var _seen = [], _stamp = 1; + W.near = function (x, z, r, out) { + out = out || []; out.length = 0; _stamp++; + var gx0 = Math.floor((x - r) / CELL), gx1 = Math.floor((x + r) / CELL), gz0 = Math.floor((z - r) / CELL), gz1 = Math.floor((z + r) / CELL); + for (var gx = gx0; gx <= gx1; gx++) for (var gz = gz0; gz <= gz1; gz++) { + var l = cellList(gx, gz); if (!l) continue; + for (var i = 0; i < l.length; i++) { var b = l[i]; if (b._st === _stamp || b.off) continue; b._st = _stamp; out.push(b); } + } + return out; + }; + + // ------------------------------------------------------------------ terrain heightfield + W.setTerrain = function (hf) { W.hf = hf; }; // {x0, z0, cell, nx, nz, h: Float32Array} + W.terrainH = function (x, z) { + var hf = W.hf; if (!hf) return 0; + var fx = (x - hf.x0) / hf.cell, fz = (z - hf.z0) / hf.cell; + fx = M.clamp(fx, 0, hf.nx - 1.001); fz = M.clamp(fz, 0, hf.nz - 1.001); + var i = Math.floor(fx), j = Math.floor(fz), tx = fx - i, tz = fz - j, n = hf.nx, h = hf.h; + var a = h[j * n + i], b = h[j * n + i + 1], c = h[(j + 1) * n + i], d = h[(j + 1) * n + i + 1]; + return (a + (b - a) * tx) * (1 - tz) + (c + (d - c) * tx) * tz; + }; + W.terrainN = function (x, z, out) { + var e = 0.6, hx = W.terrainH(x + e, z) - W.terrainH(x - e, z), hz = W.terrainH(x, z + e) - W.terrainH(x, z - e); + out = out || new THREE.Vector3(); out.set(-hx, 2 * e, -hz).normalize(); return out; + }; + + // highest walkable surface under (x,z) that is not above yRef + step. Returns {y, box, mat} + var _nb = [], _l = { x: 0, z: 0 }; + W.ground = function (x, z, yRef, step, out) { + out = out || {}; step = step == null ? TUN.stepUp : step; + var th = W.terrainH(x, z), best = th, bb = null; + var l = W.near(x, z, 0.1, _nb); + for (var i = 0; i < l.length; i++) { + var b = l[i]; toLocal(b, x, z, _l); + if (Math.abs(_l.x) > b.hx || Math.abs(_l.z) > b.hz) continue; + var top = topAt(b, _l.z); + if (top <= yRef + step && top > best) { best = top; bb = b; } + } + out.y = best; out.box = bb; out.mat = bb ? bb.mat : (W.surfaceMat ? W.surfaceMat(x, z) : 'dirt'); + out.water = best < W.water; + return out; + }; + + // ------------------------------------------------------------------ character movement + // Moves a circle of radius r with feet at p.y and the given height by (dx, dz), sliding along walls. Boxes whose + // top is within stepUp of the feet are not walls (they're stepped onto by the ground query). Returns the number of + // contacts and fills W.lastHit with the most-blocking box and the wall normal. + W.lastHit = { box: null, nx: 0, nz: 0, top: 0 }; + var _mb = []; + W.move = function (p, dx, dz, r, height, step) { + step = step == null ? TUN.stepUp : step; + var steps = Math.max(1, Math.ceil(Math.sqrt(dx * dx + dz * dz) / (r * 0.8))); + var hits = 0; W.lastHit.box = null; + for (var s = 0; s < steps; s++) { + p.x += dx / steps; p.z += dz / steps; + for (var it = 0; it < 3; it++) { + var l = W.near(p.x, p.z, r + 0.2, _mb), pushed = false; + for (var i = 0; i < l.length; i++) { + var b = l[i]; + if (b.y0 >= p.y + height || b.nocol) continue; + toLocal(b, p.x, p.z, _l); + var cx = M.clamp(_l.x, -b.hx, b.hx), cz = M.clamp(_l.z, -b.hz, b.hz); + var top = topAt(b, cz); + if (top <= p.y + step) continue; + var ex = _l.x - cx, ez = _l.z - cz, d2 = ex * ex + ez * ez; + if (d2 >= r * r) continue; + var nx, nz, pen; + if (d2 > 1e-8) { var d = Math.sqrt(d2); nx = ex / d; nz = ez / d; pen = r - d; } + else { + // centre inside the box: push out along the shallowest axis + var px = b.hx - Math.abs(_l.x), pz = b.hz - Math.abs(_l.z); + if (px < pz) { nx = Math.sign(_l.x) || 1; nz = 0; pen = px + r; } else { nx = 0; nz = Math.sign(_l.z) || 1; pen = pz + r; } + } + var w = toWorldDir(b, nx, nz, { x: 0, z: 0 }); + p.x += w.x * pen; p.z += w.z * pen; pushed = true; hits++; + W.lastHit.box = b; W.lastHit.nx = w.x; W.lastHit.nz = w.z; W.lastHit.top = top; + } + if (!pushed) break; + } + // terrain too steep to walk up: slide back + var gy = W.terrainH(p.x, p.z); + if (gy > p.y + step + 0.05) { + var n = W.terrainN(p.x, p.z); + var hl = Math.sqrt(n.x * n.x + n.z * n.z) || 1; + p.x -= dx / steps; p.z -= dz / steps; + // keep the part of the move along the slope's contour + var tx = -n.z / hl, tz = n.x / hl, dot = (dx / steps) * tx + (dz / steps) * tz; + p.x += tx * dot; p.z += tz * dot; + if (W.terrainH(p.x, p.z) > p.y + step + 0.05) { p.x -= tx * dot; p.z -= tz * dot; } + hits++; W.lastHit.box = null; W.lastHit.nx = n.x / hl; W.lastHit.nz = n.z / hl; W.lastHit.top = gy; + } + } + // stay inside the map + var B = W.bounds; + p.x = M.clamp(p.x, B.x0 + 2, B.x1 - 2); p.z = M.clamp(p.z, B.z0 + 2, B.z1 - 2); + return hits; + }; + + // is a body of radius r overlapping any wall at feet y (used for vault/climb landing checks) + W.blocked = function (x, y, z, r, height) { + var l = W.near(x, z, r + 0.2, _mb); + for (var i = 0; i < l.length; i++) { + var b = l[i]; if (b.y0 >= y + height || b.nocol) continue; + toLocal(b, x, z, _l); + var cx = M.clamp(_l.x, -b.hx, b.hx), cz = M.clamp(_l.z, -b.hz, b.hz); + if (topAt(b, cz) <= y + 0.05) continue; + var ex = _l.x - cx, ez = _l.z - cz; + if (ex * ex + ez * ez < r * r) return b; + } + if (W.terrainH(x, z) > y + 0.3) return true; + return null; + }; + + // ------------------------------------------------------------------ ray casts + // W.ray(ox,oy,oz, dx,dy,dz (unit), maxT, opts) -> {t, x,y,z, nx,ny,nz, mat, box, terrain, water} or null + // opts.skip(box) -> true to ignore a box; opts.noWater + var _rb = [], _hit = {}; + function rayBox(b, ox, oy, oz, dx, dy, dz, maxT) { + // into the box's frame (rotation about Y only) + var px = ox - b.x, pz = oz - b.z; + var lx = px * b.c - pz * b.s, lz = px * b.s + pz * b.c; + var ldx = dx * b.c - dz * b.s, ldz = dx * b.s + dz * b.c; + var cy = (b.y0 + b.y1) / 2, hy = (b.y1 - b.y0) / 2, ly = oy - cy; + var t0 = 0, t1 = maxT, n = 0, sgn = 0; + var o = [lx, ly, lz], d = [ldx, dy, ldz], h = [b.hx, hy, b.hz]; + for (var a = 0; a < 3; a++) { + if (Math.abs(d[a]) < 1e-9) { if (o[a] < -h[a] || o[a] > h[a]) return null; continue; } + var inv = 1 / d[a], ta = (-h[a] - o[a]) * inv, tb = (h[a] - o[a]) * inv, s = -1; + if (ta > tb) { var tt = ta; ta = tb; tb = tt; s = 1; } + if (ta > t0) { t0 = ta; n = a; sgn = s; } + if (tb < t1) t1 = tb; + if (t0 > t1) return null; + } + if (t0 <= 0) return null; // origin inside the box: ignore it (a muzzle poking into cover) + if (b.ramp) { + // sloped top: step along the hit span and find where the ray goes under the slope + var tEnter = t0, steps = 12; + for (var k = 0; k <= steps; k++) { + var tt2 = tEnter + (t1 - tEnter) * k / steps, yy = oy + dy * tt2, zz = lz + ldz * tt2; + if (yy <= topAt(b, zz)) { _hit.t = tt2; _hit.nl = [0, 1, 0]; return _hit; } + } + return null; + } + _hit.t = t0; + var nl = [0, 0, 0]; nl[n] = sgn; _hit.nl = nl; + return _hit; + } + W.ray = function (ox, oy, oz, dx, dy, dz, maxT, opts) { + var best = null, bt = maxT, bn = null, bb = null; + // broad phase: walk the grid cells along the ray + _stamp++; + var x = ox, z = oz, stepL = CELL * 0.5, n = Math.ceil(maxT / stepL) + 1; + for (var i = 0; i <= n; i++) { + var tt = Math.min(i * stepL, maxT); + if (tt > bt + CELL) break; + var cx = Math.floor((ox + dx * tt) / CELL), cz = Math.floor((oz + dz * tt) / CELL); + for (var gx = cx - 1; gx <= cx + 1; gx++) for (var gz = cz - 1; gz <= cz + 1; gz++) { + var l = cellList(gx, gz); if (!l) continue; + for (var k = 0; k < l.length; k++) { + var b = l[k]; if (b._st === _stamp || b.off) continue; b._st = _stamp; + if (opts && opts.skip && opts.skip(b)) continue; + var h = rayBox(b, ox, oy, oz, dx, dy, dz, bt); + if (h && h.t < bt && h.t >= 0) { bt = h.t; bb = b; bn = h.nl.slice(); } + } + } + } + // terrain: adaptive march, then bisection + var tt0 = 0, prevT = 0, hitT = -1; + while (tt0 < bt) { + var yy = oy + dy * tt0, hh = W.terrainH(ox + dx * tt0, oz + dz * tt0); + if (yy < hh) { hitT = tt0; break; } + prevT = tt0; tt0 += Math.max(0.4, (yy - hh) * 0.6); + } + var res = _res; + if (hitT >= 0) { + var a = prevT, c = hitT; + for (var it = 0; it < 8; it++) { var m = (a + c) / 2; if (oy + dy * m < W.terrainH(ox + dx * m, oz + dz * m)) c = m; else a = m; } + res.t = c; res.box = null; res.terrain = true; + var nn = W.terrainN(ox + dx * c, oz + dz * c); res.nx = nn.x; res.ny = nn.y; res.nz = nn.z; + res.mat = W.surfaceMat ? W.surfaceMat(ox + dx * c, oz + dz * c) : 'dirt'; + } else if (bb) { + res.t = bt; res.box = bb; res.terrain = false; res.mat = bb.mat; + var w = toWorldDir(bb, bn[0], bn[2], { x: 0, z: 0 }); res.nx = w.x; res.ny = bn[1]; res.nz = w.z; + } else { + res.t = maxT; res.box = null; res.terrain = false; res.mat = null; + } + // the sea surface + res.water = false; + if (!(opts && opts.noWater) && dy < 0 && oy > W.water) { + var tw = (W.water - oy) / dy; + if (tw < res.t) { res.t = tw; res.box = null; res.terrain = false; res.mat = 'water'; res.water = true; res.nx = 0; res.ny = 1; res.nz = 0; hitT = 0; } + } + if (hitT < 0 && !bb && !res.water) return null; + res.x = ox + dx * res.t; res.y = oy + dy * res.t; res.z = oz + dz * res.t; + return res; + }; + var _res = {}; + // clear line between two points (sight lines) + W.los = function (ax, ay, az, bx, by, bz) { + var dx = bx - ax, dy = by - ay, dz = bz - az, L = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (L < 0.01) return true; + var h = W.ray(ax, ay, az, dx / L, dy / L, dz / L, L - 0.05, { noWater: true, skip: skipSoft }); + return !h; + }; + function skipSoft(b) { return b.see; } // see-through boxes (railings, foliage) don't block sight + + // ------------------------------------------------------------------ navigation grid (1 m cells) + A* + var NAV_RISE = 0.72; // m between neighbouring cells that can still be walked: stepped lanes and stairs climb about 0.6 per metre + W.buildNav = function (cell) { + cell = cell || 1; + var B = W.bounds, nx = Math.ceil((B.x1 - B.x0) / cell), nz = Math.ceil((B.z1 - B.z0) / cell); + var h = new Float32Array(nx * nz), ok = new Uint8Array(nx * nz), boxy = new Uint8Array(nx * nz); + for (var j = 0; j < nz; j++) for (var i = 0; i < nx; i++) { + var x = B.x0 + (i + 0.5) * cell, z = B.z0 + (j + 0.5) * cell; + var th = W.terrainH(x, z), g = th, wall = false; + var l = W.near(x, z, 0.4, _nb); + if (!l.length) { // nothing built here: open ground or open sea + h[j * nx + i] = g; ok[j * nx + i] = g < W.water + 0.05 ? 0 : 1; continue; + } + boxy[j * nx + i] = 1; + // stand on the highest surface reachable from the terrain (or from a box top we step onto); a bridge or pier + // deck (b.deck) is stood on however far below it the ground is + for (var pass = 0; pass < 2; pass++) { + for (var k = 0; k < l.length; k++) { + var b = l[k]; if (b.nocol) continue; + toLocal(b, x, z, _l); + if (Math.abs(_l.x) > b.hx + 0.3 || Math.abs(_l.z) > b.hz + 0.3) continue; + var inside = Math.abs(_l.x) <= b.hx && Math.abs(_l.z) <= b.hz; + var top = topAt(b, M.clamp(_l.z, -b.hz, b.hz)); + if (inside && top > g && (top <= g + 0.45 || b.deck)) g = top; + } + } + for (k = 0; k < l.length; k++) { + b = l[k]; if (b.nocol) continue; + toLocal(b, x, z, _l); + if (Math.abs(_l.x) > b.hx + 0.3 || Math.abs(_l.z) > b.hz + 0.3) continue; // 0.3 m clearance round walls + top = topAt(b, M.clamp(_l.z, -b.hz, b.hz)); + if (top > g + 0.45 && b.y0 < g + 1.7) { wall = true; break; } + } + h[j * nx + i] = g; + ok[j * nx + i] = wall || g < W.water + 0.05 ? 0 : 1; + } + W.nav = { cell: cell, nx: nx, nz: nz, h: h, ok: ok, x0: B.x0, z0: B.z0, edge: new Uint8Array(nx * nz * 8), boxy: boxy }; + W.nav.warmI = 0; + }; + // check ledge-like edges a little at a time (from main.js, ~1.5 ms a frame) so path searches rarely meet an unchecked + // one; any they do meet are checked on the spot (edgeOk) + var WDX = [1, -1, 0, 0, 1, 1, -1, -1], WDZ = [0, 0, 1, -1, 1, -1, 1, -1]; + W.navWarm = function (ms) { + var N = W.nav; if (!N || N.warmI >= N.nx * N.nz) return; + var t0 = performance.now(), n = N.nx * N.nz; + while (N.warmI < n) { + var c = N.warmI++; + if (N.ok[c] && N.boxy[c]) { + var i = c % N.nx, j = (c / N.nx) | 0; + for (var k = 0; k < 8; k++) { + var xi = i + WDX[k], zj = j + WDZ[k]; if (xi < 0 || zj < 0 || xi >= N.nx || zj >= N.nz) continue; + var nc = zj * N.nx + xi; if (N.ok[nc] && Math.abs(N.h[nc] - N.h[c]) <= NAV_RISE) edgeOk(c, nc, k); + } + } + if ((c & 63) === 0 && performance.now() - t0 > ms) return; + } + }; + W.navCell = function (x, z) { + var N = W.nav, i = Math.floor((x - N.x0) / N.cell), j = Math.floor((z - N.z0) / N.cell); + if (i < 0 || j < 0 || i >= N.nx || j >= N.nz) return -1; + return j * N.nx + i; + }; + W.navOk = function (x, z) { var c = W.navCell(x, z); return c >= 0 && W.nav.ok[c] === 1; }; + // nearest walkable cell (spiral search) + W.navSnap = function (x, z, maxR) { + var N = W.nav, c = W.navCell(x, z); + if (c >= 0 && N.ok[c]) return c; + var ci = Math.floor((x - N.x0) / N.cell), cj = Math.floor((z - N.z0) / N.cell); + for (var r = 1; r <= (maxR || 6); r++) for (var dj = -r; dj <= r; dj++) for (var di = -r; di <= r; di++) { + if (Math.abs(di) !== r && Math.abs(dj) !== r) continue; + var i = ci + di, j = cj + dj; if (i < 0 || j < 0 || i >= N.nx || j >= N.nz) continue; + if (N.ok[j * N.nx + i]) return j * N.nx + i; + } + return -1; + }; + // A* on the grid; returns [{x,z,y}, ...] smoothed with line-of-walk checks, or null + var heap = [], gScore = null, came = null, closedS = null, stampA = 0; + W.path = function (ax, az, bx, bz, maxNodes) { + var N = W.nav; if (!N) return null; + var s = W.navSnap(ax, az, 4), g = W.navSnap(bx, bz, 8); + if (s < 0 || g < 0) return null; + var n = N.nx * N.nz; + if (!gScore || gScore.length !== n) { gScore = new Float32Array(n); came = new Int32Array(n); closedS = new Uint32Array(n); } + stampA++; + var gx = g % N.nx, gz = (g / N.nx) | 0; + heap.length = 0; + function hfun(c) { var x = c % N.nx, z = (c / N.nx) | 0, dx = Math.abs(x - gx), dz = Math.abs(z - gz); return (dx + dz) + (1.414 - 2) * Math.min(dx, dz); } + function push(c, f) { heap.push([f, c]); var i = heap.length - 1; while (i > 0) { var p = (i - 1) >> 1; if (heap[p][0] <= heap[i][0]) break; var t = heap[p]; heap[p] = heap[i]; heap[i] = t; i = p; } } + function pop() { var top = heap[0], last = heap.pop(); if (heap.length) { heap[0] = last; var i = 0; for (;;) { var l = 2 * i + 1, r = l + 1, m = i; if (l < heap.length && heap[l][0] < heap[m][0]) m = l; if (r < heap.length && heap[r][0] < heap[m][0]) m = r; if (m === i) break; var t = heap[m]; heap[m] = heap[i]; heap[i] = t; i = m; } } return top; } + var visit = new Map(); + gScore[s] = 0; visit.set(s, stampA); came[s] = -1; push(s, hfun(s)); + var expanded = 0, found = false, max = maxNodes || 9000; + var DX = [1, -1, 0, 0, 1, 1, -1, -1], DZ = [0, 0, 1, -1, 1, -1, 1, -1], DC = [1, 1, 1, 1, 1.414, 1.414, 1.414, 1.414]; + while (heap.length && expanded < max) { + var cur = pop()[1]; + if (closedS[cur] === stampA) continue; + closedS[cur] = stampA; expanded++; + if (cur === g) { found = true; break; } + var cx = cur % N.nx, cz = (cur / N.nx) | 0, ch = N.h[cur]; + for (var k = 0; k < 8; k++) { + var x = cx + DX[k], z = cz + DZ[k]; if (x < 0 || z < 0 || x >= N.nx || z >= N.nz) continue; + var nc = z * N.nx + x; if (!N.ok[nc] || closedS[nc] === stampA) continue; + if (Math.abs(N.h[nc] - ch) > NAV_RISE || !edgeOk(cur, nc, k)) continue; + if (k >= 4 && (!N.ok[cz * N.nx + x] || !N.ok[z * N.nx + cx])) continue; // no corner cutting + var ng = gScore[cur] + DC[k] + Math.max(0, N.h[nc] - ch) * 0.5; + if (visit.get(nc) === stampA && ng >= gScore[nc]) continue; + visit.set(nc, stampA); gScore[nc] = ng; came[nc] = cur; push(nc, ng + hfun(nc) * 1.05); + } + } + if (!found) return null; + var cells = []; for (var c = g; c !== -1; c = came[c]) cells.push(c); + cells.reverse(); + // string pulling: keep a cell only if the straight walk from the last kept one is blocked + var out = [], last = 0; + out.push(cellPt(cells[0])); + for (var i = 2; i < cells.length; i++) { + if (!walkLine(cells[last], cells[i])) { last = i - 1; out.push(cellPt(cells[last])); } + } + out.push(cellPt(cells[cells.length - 1])); + return out; + }; + // a rise between neighbouring cells is fine on stairs (several small steps in a metre) but not at a ledge the walker + // can't step onto (a slab edge on rising ground reads as a gentle slope in the cell heights): such edges are walked + // once with the real mover (W.move, the player's radius and step) and the answer is cached per edge + var _ep = new THREE.Vector3(); + function edgeOk(a, b, k) { + var N = W.nav, dh = N.h[b] - N.h[a]; if (Math.abs(dh) <= 0.3 || !(N.boxy[a] || N.boxy[b])) return true; // (bare hillside: the mover climbs whatever the grid allows) + var e = N.edge[a * 8 + k]; if (e) return e === 1; + var pa = cellPt(a), pb = cellPt(b), p = _ep.set(pa.x, pa.y, pa.z), ok = false; + for (var i = 0; i < 16; i++) { + var dx = pb.x - p.x, dz = pb.z - p.z, d = Math.hypot(dx, dz); + if (d < 0.12) { ok = Math.abs(p.y - pb.y) < 0.5; break; } + var st = Math.min(d, 0.2); W.move(p, dx / d * st, dz / d * st, TUN.radius, 1.7); + var g = W.ground(p.x, p.z, p.y + 0.05).y; if (p.y - g > 1.3) break; p.y = g; + } + N.edge[a * 8 + k] = ok ? 1 : 2; + return ok; + } + function cellPt(c) { var N = W.nav; return { x: N.x0 + ((c % N.nx) + 0.5) * N.cell, z: N.z0 + (((c / N.nx) | 0) + 0.5) * N.cell, y: N.h[c] }; } + // can a walker go straight from cell a's centre to cell b's? The line is swept with the walker's width (every + // cell under a 0.7-cell square at quarter-cell steps), so a shortcut never grazes a wall the cells only just clear + function walkLine(a, b) { + var N = W.nav, ax = a % N.nx + 0.5, az = ((a / N.nx) | 0) + 0.5, bx = b % N.nx + 0.5, bz = ((b / N.nx) | 0) + 0.5; + var n = Math.max(1, Math.ceil(Math.max(Math.abs(bx - ax), Math.abs(bz - az)) * 4)), ph = N.h[a], R = 0.35; + for (var i = 1; i <= n; i++) { + var px = ax + (bx - ax) * i / n, pz = az + (bz - az) * i / n; + for (var cz = Math.floor(pz - R); cz <= Math.floor(pz + R); cz++) for (var cx = Math.floor(px - R); cx <= Math.floor(px + R); cx++) { + if (cx < 0 || cz < 0 || cx >= N.nx || cz >= N.nz) return false; + var c = cz * N.nx + cx; + if (!N.ok[c] || Math.abs(N.h[c] - ph) > 0.45) return false; // (height changes keep their waypoints: stairs and ledges are checked edge by edge) + } + ph = N.h[Math.floor(pz) * N.nx + Math.floor(px)]; + } + return true; + } + W.walkable = function (ax, az, bx, bz) { + var a = W.navCell(ax, az), b = W.navCell(bx, bz); + if (a < 0 || b < 0) return false; return walkLine(a, b); + }; + + // ------------------------------------------------------------------ cover points for the AI + // Along every side of each cover box, every ~1.3 m: a point just outside the face, the direction it protects from + // (into the box), its height class (low: crouch behind, high: stand) and whether it is at an edge (can peek round). + W.buildCover = function () { + W.coverPts = []; W.coverGrid = {}; + W.boxes.forEach(function (b) { + if (!b.cover) return; + var faces = [[1, 0, b.hz], [-1, 0, b.hz], [0, 1, b.hx], [0, -1, b.hx]]; + faces.forEach(function (f) { + var half = f[2], n = Math.max(1, Math.floor(half * 2 / 1.3)), off = (f[0] ? b.hx : b.hz) + 0.45; + for (var i = 0; i <= n; i++) { + var u = -half + (half * 2) * (n ? i / n : 0.5); + var lx = f[0] ? f[0] * off : u, lz = f[1] ? f[1] * off : u; + var w = toWorldDir(b, lx, lz, { x: 0, z: 0 }), nd = toWorldDir(b, -f[0], -f[1], { x: 0, z: 0 }); + var x = b.x + w.x, z = b.z + w.z; + if (!W.navOk(x, z)) continue; + var gy = W.nav.h[W.navCell(x, z)]; + var hgt = b.y1 - gy; + if (hgt < 0.85) continue; + var p = { x: x, z: z, y: gy, dx: nd.x, dz: nd.z, low: hgt < 1.5, edge: i === 0 || i === n, box: b, taken: null }; + W.coverPts.push(p); + var k = Math.floor(x / 16) + ',' + Math.floor(z / 16); (W.coverGrid[k] = W.coverGrid[k] || []).push(p); + } + }); + }); + }; + W.coverNear = function (x, z, r, out) { + out = out || []; out.length = 0; + var g0 = Math.floor((x - r) / 16), g1 = Math.floor((x + r) / 16), h0 = Math.floor((z - r) / 16), h1 = Math.floor((z + r) / 16); + for (var gx = g0; gx <= g1; gx++) for (var gz = h0; gz <= h1; gz++) { + var l = W.coverGrid[gx + ',' + gz]; if (!l) continue; + for (var i = 0; i < l.length; i++) { var p = l[i], dx = p.x - x, dz = p.z - z; if (dx * dx + dz * dz < r * r) out.push(p); } + } + return out; + }; + + // ------------------------------------------------------------------ indoor zones (reverb, light) and named areas + W.addZone = function (z) { W.zones.push(z); return z; }; // {x0,z0,x1,z1,y0,y1, indoor:true, name} + W.indoor = function (x, y, z) { + for (var i = 0; i < W.zones.length; i++) { var q = W.zones[i]; if (q.indoor && x > q.x0 && x < q.x1 && z > q.z0 && z < q.z1 && y > q.y0 && y < q.y1) return q; } + return null; + }; +})(); diff --git a/e63334287a3deaa3/blacktie/preview.jpg b/e63334287a3deaa3/blacktie/preview.jpg new file mode 100644 index 00000000..da966fcf Binary files /dev/null and b/e63334287a3deaa3/blacktie/preview.jpg differ diff --git a/e63334287a3deaa3/blacktie/tools/chars/.gitignore b/e63334287a3deaa3/blacktie/tools/chars/.gitignore new file mode 100644 index 00000000..c18dd8d8 --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/e63334287a3deaa3/blacktie/tools/chars/README.md b/e63334287a3deaa3/blacktie/tools/chars/README.md new file mode 100644 index 00000000..95773e5e --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/README.md @@ -0,0 +1,33 @@ +# People build scripts (Black Tie) + +Rebuild the MakeHuman-based characters in `../../assets/` (`agent.glb`, more to come). The game never runs these. + +- Needs Python 3.13 with `bpy` (Blender as a module), `numpy`, `pillow` in a venv, and node with + `@gltf-transform/cli` for meshopt compression. +- Sources (not committed; all CC0): MakeHuman/MPFB2 data (`dl_mpfb/x`, base mesh, targets, rig, weights) and the + MakeHuman system assets (`dl_mh/x`: skins, eyes, brows, lashes, hair, clothes). Download as in + `../../../ironveil/tools/chars/fetch.sh` into `$CHARS_WORK`. +- The skeleton comes from the old `hero.glb` (UAL bone names and rest orientations, so every clip in `anims.glb` + plays): `npx gltf-transform copy $CHARS_WORK/hero_plain.glb` (it is in git history, + commit ce86328). +- `mhlib.py`, `geo.py` are copies of Midnight Ops' helpers; `mhlib.build_human` now also fits clothes and takes + `V` (pre-morphed vertices), lashes and eye colour. + +``` +export CHARS_WORK=~/rpwork +KIND=agent bvenv/bin/python build_people.py # -> $CHARS_WORK/agent.blend (+ tex_agent/) +bvenv/bin/python preview.py $CHARS_WORK/agent.blend out.png torso # Cycles still: full, back, torso, face +KIND=agent bvenv/bin/python export_people.py $CHARS_WORK/out_agent.glb +npx gltf-transform meshopt $CHARS_WORK/out_agent.glb ../../assets/agent.glb --level high +python3 -I webp_glb.py ../../assets/agent.glb # textures to WebP (EXT_texture_webp): about half the file +``` + +- `outfits_people.py`: `SPECS` (body, face targets, skin, hair, clothes, texture size, atlas layout) and one + `tex_` function per clothes item that recomputes its textures from the item's UV layout: the agent's + tuxedo turns MakeHuman's `male_elegantsuit01` black with satin-faced lapels (texture-space polygons), pleated + shirt front with studs where the long tie was (the tie's vertices are pressed back onto the chest), patent + `shoes04`, and a modelled bow tie. +- `webp_glb.py`: re-encodes a .glb's images as WebP in place (quality 88, alpha kept) and repacks the binary chunk, + including the regions EXT_meshopt_compression points at. The seven character files went from 11.8 MB to 5.4 MB. +- `export_people.py`: one cloth atlas per character, skin, a hair/brow/lash/eye atlas, LOD1 (6k tris) and LOD2 + (1.6k tris), meshes named ``, `Hair`, `Eyes`, `LOD1`, `LOD2`. diff --git a/e63334287a3deaa3/blacktie/tools/chars/build_people.py b/e63334287a3deaa3/blacktie/tools/chars/build_people.py new file mode 100644 index 00000000..171dd13f --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/build_people.py @@ -0,0 +1,30 @@ +# Builds one character (KIND env: agent, suit, tac, civm1, civm2, civf1, civf2) into $CHARS_WORK/.blend: +# MakeHuman body (CC0 data) on the shared UAL skeleton, MakeHuman CC0 clothes fitted and re-textured in code. +# CHARS_WORK=/path/to/work bvenv/bin/python build_people.py +import bpy, os, sys, math, glob, json +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import numpy as np +import mhlib as L, geo as G, people as P +import outfits_people as O + +KIND = os.environ.get('KIND', 'agent') +SPEC = O.SPECS[KIND] +L.UAL1 = L.WORK + '/hero_plain.glb' # the shared skeleton (UAL bone names and rest orientations) +bpy.ops.wm.read_factory_settings(use_empty=True) + +V0, VT, F = L.load_base() +V = L.apply_targets(V0, L.macro_targets(**SPEC['macro']) + list(SPEC.get('face', []))) +H = L.build_human(V=V, clothes=SPEC['clothes'], **SPEC['human']) +body = H['body'] +dele = set(); worn = [] +for item in SPEC['clothes']: + worn.append((item, H['C_' + item])); dele |= P.read_delete_verts(P.CL + '/%s/%s.mhclo' % (item, item)) +from mathutils.bvhtree import BVHTree +H['chest_bvh'] = G.bvh_of(body) +print('delete', len(dele), 'removed', P.delete_body_verts(body, H['used'], dele)) +TD = L.WORK + '/tex_' + KIND; os.makedirs(TD, exist_ok=True) +O.dress(KIND, SPEC, H, worn, TD) +for o in [body] + [w for _, w in worn] + ([bpy.data.objects['C_vest']] if bpy.data.objects.get('C_vest') else []): + print('shoulders', o.name, P.smooth_shoulders(o, H)) +bpy.ops.wm.save_as_mainfile(filepath=L.WORK + '/%s.blend' % KIND) +print('saved', KIND) diff --git a/e63334287a3deaa3/blacktie/tools/chars/export_people.py b/e63334287a3deaa3/blacktie/tools/chars/export_people.py new file mode 100644 index 00000000..b039558c --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/export_people.py @@ -0,0 +1,181 @@ +# Packs a built character ($CHARS_WORK/.blend from build_people.py) into the game's GLB: +# body skin + clothes (two materials: skin, cloth; all clothes share one atlas, the bow tie included) +# Hair hair, brows and lashes on one alpha atlas Eyes the eyes (same atlas, opaque) +# LOD1 / LOD2 decimated body + clothes (LOD2 also carries a hair cap baked into the skin colour) +# One skeleton per file (the UAL bone names), so every clip in anims.glb plays on it. +# KIND=agent bvenv/bin/python export_people.py out.glb +import bpy, os, sys, math +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import numpy as np +import mhlib as L, geo as G, people as P +import outfits_people as O + +KIND = os.environ.get('KIND', 'agent'); SPEC = O.SPECS[KIND] +NAME = SPEC.get('name', KIND.capitalize()) +OUT = sys.argv[-1] +TD = L.WORK + '/tex_' + KIND +bpy.ops.wm.open_mainfile(filepath=L.WORK + '/%s.blend' % KIND) +rig = bpy.data.objects['Armature'] +from PIL import Image + +def remap(ob, rect): + """Move an object's UVs (0..1) into rect = (x, y, w, h) of the atlas, y measured from the top.""" + x, y, w, h = rect + for d in ob.data.uv_layers['UVMap'].data: + u, v = d.uv + d.uv = (x + min(max(u, 0), 1) * w, (1 - y - h) + min(max(v, 0), 1) * h) + +# ---- clothes atlas +size = SPEC.get('tex', 1024) +atlas = Image.new('RGB', (size, size), (20, 20, 22)); natl = Image.new('RGB', (size, size), (128, 128, 255)); oatl = Image.new('RGB', (size, size), (255, 200, 0)) +cloth = [] +for item, rect in SPEC['layout']: + ob = bpy.data.objects['C_' + item] + x, y, w, h = rect + box = (int(x * size), int(y * size)); dim = (max(1, int(w * size)), max(1, int(h * size))) + for img, src in ((atlas, '_albedo.jpg'), (natl, '_normal.jpg'), (oatl, '_orm.jpg')): + img.paste(Image.open(TD + '/' + item + src).convert('RGB').resize(dim, Image.LANCZOS), box) + remap(ob, rect); cloth.append(ob) +bow = bpy.data.objects.get('BowTie') +if bow: + m = np.load(TD + '/male_elegantsuit01_masks.npy').astype(np.float32)[0] + ys, xs = np.nonzero(m > 0.95); i = len(xs) // 2 + u, v = (xs[i] + 0.5) / m.shape[1], 1 - (ys[i] + 0.5) / m.shape[0] + for d in bow.data.uv_layers['UVMap'].data: d.uv = (u, v) + cloth.append(bow) +nsz = min(size, 1024); osz = min(size, 512) +# real white cloth reflects about 80 % of light: soft-knee the brightest texels so shirts do not bloom in the sun +a = np.asarray(atlas).astype(np.float32) / 255 +a = np.where(a > 0.62, 0.62 + (a - 0.62) * 0.55, a) +atlas = Image.fromarray(np.clip(a * 255 + 0.5, 0, 255).astype(np.uint8)) +atlas.save(TD + '/cloth_albedo.jpg', quality=90); natl.resize((nsz, nsz), Image.LANCZOS).save(TD + '/cloth_normal.jpg', quality=90) +oatl.resize((osz, osz), Image.LANCZOS).save(TD + '/cloth_orm.jpg', quality=88) +cm = P.material(NAME + 'Cloth', TD + '/cloth_albedo.jpg', TD + '/cloth_normal.jpg', TD + '/cloth_orm.jpg') +for ob in cloth: P.set_mat(ob, cm) + +# ---- skin (1024) +body = bpy.data.objects['Body'] +for f, q in (('skin_albedo.jpg', 90), ('skin_normal.jpg', 90), ('skin_orm.jpg', 85)): + im = Image.open(TD + '/' + f); s = 1024 if 'albedo' in f or 'normal' in f else 512 + im.resize((s, s), Image.LANCZOS).save(TD + '/s_' + f, quality=q) +sm = P.material(NAME + 'Skin', TD + '/s_skin_albedo.jpg', TD + '/s_skin_normal.jpg', TD + '/s_skin_orm.jpg') +P.set_mat(body, sm) + +# ---- hair atlas: hair (top half), brows, lashes, eyes +hs = 1024 +hat = Image.new('RGBA', (hs, hs), (0, 0, 0, 0)) +parts = [('Hair', TD + '/hair.png', (0, 0, 1, 0.5)), ('Brows', None, (0, 0.5, 0.5, 0.25)), ('Lashes', None, (0.5, 0.5, 0.5, 0.25)), + ('Eyes', None, (0, 0.75, 0.25, 0.25))] +srcs = {} +for ob in bpy.data.objects: + if ob.type != 'MESH': continue + for slot in ob.material_slots: + for n in slot.material.node_tree.nodes if slot.material and slot.material.node_tree else []: + if n.type == 'TEX_IMAGE' and n.image: srcs.setdefault(ob.name, bpy.path.abspath(n.image.filepath)) +hair_obs = [] +for nm, path, rect in parts: + ob = bpy.data.objects.get(nm) + if not ob: continue + path = path or srcs[nm] + x, y, w, h = rect + im = Image.open(path).convert('RGBA').resize((int(w * hs), int(h * hs)), Image.LANCZOS) + if nm == 'Brows': + from PIL import ImageFilter + r, g, b, a = im.split() + a = a.filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.GaussianBlur(1.2)).point(lambda v: max(0, min(255, int((v - 40) * 1.6)))) + rgb = Image.new('RGB', im.size, SPEC.get('brow_rgb', (38, 28, 22))) + im = Image.merge('RGBA', (*rgb.split(), a)) + if nm == 'Eyes': im.putalpha(255) + hat.paste(im, (int(x * hs), int(y * hs))) + remap(ob, rect) + if nm != 'Eyes': hair_obs.append(ob) +# bleed colour into transparent texels so mipmaps don't fringe white or black +a = np.asarray(hat).astype(np.float32) +al = a[..., 3:4] / 255 +from PIL import ImageFilter +rgb = Image.fromarray(a[..., :3].astype(np.uint8)) +for _ in range(6): rgb = Image.fromarray(np.where(al > 0.1, a[..., :3], np.asarray(rgb.filter(ImageFilter.MaxFilter(5))).astype(np.float32)).astype(np.uint8)) +hat = Image.merge('RGBA', (*rgb.split(), hat.split()[3])); hat.save(TD + '/hair_atlas.png') +hm = P.material(NAME + 'Hair', TD + '/hair_atlas.png', alpha=True, rough=0.5) +eyes = bpy.data.objects['Eyes'] +Image.open(TD + '/hair_atlas.png').convert('RGB').save(TD + '/eyes.jpg', quality=90) +em = P.material(NAME + 'Eye', TD + '/eyes.jpg', rough=0.08) +P.set_mat(eyes, em) +for ob in hair_obs: P.set_mat(ob, hm) + +# ---- join and bind +for o in [body] + cloth + hair_obs + [eyes]: + for mo in list(o.modifiers): o.modifiers.remove(mo) +main = G.join([body] + cloth, NAME) +hair = G.join(hair_obs, NAME + 'Hair') +eyes.name = NAME + 'Eyes'; eyes.data.name = NAME + 'Eyes' +L.bind([main, hair, eyes], rig) +for o in (main, hair, eyes): + for vg in list(o.vertex_groups): + if vg.name not in rig.data.bones: o.vertex_groups.remove(vg) +def tris(o): return sum(len(p.vertices) - 2 for p in o.data.polygons) +print('tris', NAME, tris(main), 'hair', tris(hair), 'eyes', tris(eyes)) +# everyone but the agent is lighter close up too (they are seen at 12 m or less at this level, twice with shadows) +main_tris = SPEC.get('main_tris', 18000 if KIND != 'agent' else None) +if main_tris and tris(main) > main_tris: + for mo in list(main.modifiers): main.modifiers.remove(mo) + md = main.modifiers.new('dec', 'DECIMATE'); md.ratio = main_tris / tris(main); md.use_symmetry = True; md.symmetry_axis = 'X' + L.set_active(main); bpy.ops.object.modifier_apply(modifier=md.name) + main.modifiers.new('Armature', 'ARMATURE').object = rig + print('main decimated', tris(main)) +lods = [] +for suf, target in (('LOD1', SPEC.get('lod1', 6000)), ('LOD2', SPEC.get('lod2', 1600))): + c = main.copy(); c.data = main.data.copy(); c.name = NAME + suf; c.data.name = NAME + suf + bpy.context.scene.collection.objects.link(c) + for mo in list(c.modifiers): c.modifiers.remove(mo) + md = c.modifiers.new('dec', 'DECIMATE'); md.ratio = min(1.0, target / tris(main)); md.use_symmetry = True; md.symmetry_axis = 'X' + L.set_active(c); bpy.ops.object.modifier_apply(modifier=md.name) + c.modifiers.new('Armature', 'ARMATURE').object = rig + print('lod', c.name, tris(c)); lods.append(c) +# ---- far models in one draw call: skin and clothes side by side in one small atlas, a strip of swatches below, +# and a coarse solid copy of the hair (the alpha hair cards are not drawn at a distance, which left people bald) +AW, AH, SW = 1024, 528, 16 +lat = Image.new('RGB', (AW, AH), (30, 30, 30)) +lat.paste(Image.open(TD + '/s_skin_albedo.jpg').convert('RGB').resize((512, 512), Image.LANCZOS), (0, 0)) +lat.paste(Image.open(TD + '/cloth_albedo.jpg').convert('RGB').resize((512, 512), Image.LANCZOS), (512, 0)) +hc = SPEC.get('hair_col', '#2a2018').lstrip('#'); hrgb = tuple(int(hc[i:i + 2], 16) for i in (0, 2, 4)) +lat.paste(Image.new('RGB', (64, SW), hrgb), (0, 512)) +lat.save(TD + '/lod_albedo.jpg', quality=88) +lm = P.material(NAME + 'LOD', TD + '/lod_albedo.jpg', rough=0.8) +SWATCH = (32 / AW, 1 - (512 + SW / 2) / AH) +# the hair shell: hair-card faces only (the hair is the top half of the hair atlas), decimated, opaque +shell = hair.copy(); shell.data = hair.data.copy(); bpy.context.scene.collection.objects.link(shell) +for mo in list(shell.modifiers): shell.modifiers.remove(mo) +import bmesh +bm = bmesh.new(); bm.from_mesh(shell.data); uvl = bm.loops.layers.uv['UVMap'] +bmesh.ops.delete(bm, geom=[f for f in bm.faces if sum(l[uvl].uv.y for l in f.loops) / len(f.loops) < 0.5], context='FACES') +bm.to_mesh(shell.data); bm.free() +if len(shell.data.polygons): + md = shell.modifiers.new('dec', 'DECIMATE'); md.ratio = min(1.0, 500 / max(1, tris(shell))) + L.set_active(shell); bpy.ops.object.modifier_apply(modifier=md.name) +for o in lods: + skin_i = [i for i, m in enumerate(o.data.materials) if m and m.name.startswith(NAME + 'Skin')] + uv = o.data.uv_layers['UVMap'].data + for poly in o.data.polygons: + off = 0.0 if poly.material_index in skin_i else 0.5 + for li in poly.loop_indices: + u, v = uv[li].uv + uv[li].uv = (off + min(max(u, 0), 1) * 0.5, (AH - 512) / AH + min(max(v, 0), 1) * 512 / AH) + if len(shell.data.polygons): + sc = shell.copy(); sc.data = shell.data.copy(); bpy.context.scene.collection.objects.link(sc) + for d in sc.data.uv_layers['UVMap'].data: d.uv = SWATCH + for mo in list(o.modifiers): o.modifiers.remove(mo) + name = o.name; o2 = G.join([o, sc], name); o = o2 + P.set_mat(o, lm) + if not any(m.type == 'ARMATURE' for m in o.modifiers): o.modifiers.new('Armature', 'ARMATURE').object = rig + print('lod one material', o.name, tris(o)) +bpy.data.objects.remove(shell) +lods = [bpy.data.objects[NAME + 'LOD1'], bpy.data.objects[NAME + 'LOD2']] +keep = {rig.name, main.name, hair.name, eyes.name} | {o.name for o in lods} +for o in list(bpy.data.objects): + if o.name not in keep: bpy.data.objects.remove(o) +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, use_selection=False) +print('exported', OUT) diff --git a/e63334287a3deaa3/blacktie/tools/chars/geo.py b/e63334287a3deaa3/blacktie/tools/chars/geo.py new file mode 100644 index 00000000..39ab857b --- /dev/null +++ b/e63334287a3deaa3/blacktie/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/blacktie/tools/chars/mhlib.py b/e63334287a3deaa3/blacktie/tools/chars/mhlib.py new file mode 100644 index 00000000..32010622 --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/mhlib.py @@ -0,0 +1,398 @@ +# 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', g='male'): + 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-%s-young-%s-%s' % (g, mname, wname), mw * wgt)) + h = (height - 0.5) * 2 + if h: + t.append(('macrodetails/height/%s-young-%s-%s-%s' % (g, mname, wname, 'maxheight' if h > 0 else 'minheight'), mw * wgt * abs(h))) + pp = (prop - 0.5) * 2 + if pp: + t.append(('macrodetails/proportions/%s-young-%s-%s-idealproportions' % (g, mname, wname), mw * wgt * pp)) + t.append(('macrodetails/%s-%s-young' % (race, g), 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, V=None, clothes=(), lashes='eyelashes01', eyes='brown'): + """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() + if V is None: 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/%s/%s.mhclo' % (lashes, lashes), 'lashes')] + \ + ([(MHA + '/hair/%s/%s.mhclo' % (hair, hair), 'hair')] if hair else []) + \ + [(MHA + '/clothes/%s/%s.mhclo' % (c, c), 'C_' + c) for c in clothes]: + ob, refs = fit_mhclo(path, V, nm if nm.startswith('C_') else 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['used'] = used; parts['V'] = V + 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/%s_eye.png' % eyes + return parts diff --git a/e63334287a3deaa3/blacktie/tools/chars/outfits_people.py b/e63334287a3deaa3/blacktie/tools/chars/outfits_people.py new file mode 100644 index 00000000..d69ed5f5 --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/outfits_people.py @@ -0,0 +1,413 @@ +# Who each character is (MakeHuman build parameters, clothes) and how their clothes are re-textured. +# All clothes are MakeHuman system assets (CC0); every texture here is recomputed in code from their UV layouts. +import bpy, os, math +import numpy as np +from mathutils import Vector +import mhlib as L, geo as G, people as P + +ATHLETIC = [('hip/hip-scale-horiz-decr', 0.25), ('buttocks/buttocks-volume-decr', 0.5), ('stomach/stomach-pregnant-decr', 0.4), + ('torso/torso-vshape-incr', 0.25), ('torso/measure-waist-circ-decr', 0.15), ('neck/neck-scale-horiz-incr', 0.25)] +HEAVY = [('torso/torso-vshape-incr', 0.15), ('neck/neck-scale-horiz-incr', 0.5), ('arms/l-upperarm-muscle-incr', 0.3), ('arms/r-upperarm-muscle-incr', 0.3)] +def man(height, muscle, weight, prop=0.8, race='caucasian'): return dict(height=height, muscle=muscle, weight=weight, prop=prop, race=race) +def woman(height, muscle, weight, prop=0.8, race='caucasian'): return dict(height=height, muscle=muscle, weight=weight, prop=prop, race=race, g='female') +SPECS = { + # the agent: tall, lean and athletic, an even, composed face (no real person); black tuxedo + 'agent': dict(macro=man(0.62, 0.66, 0.44, 0.9), + face=ATHLETIC + [('head/head-square', 0.3), ('chin/chin-prominent-incr', 0.3), ('chin/chin-width-incr', 0.12), + ('cheek/l-cheek-bones-incr', 0.4), ('cheek/r-cheek-bones-incr', 0.4), ('cheek/l-cheek-volume-decr', 0.35), + ('cheek/r-cheek-volume-decr', 0.35), ('nose/nose-scale-vert-incr', 0.12), ('eyebrows/eyebrows-trans-down', 0.3), + ('mouth/mouth-scale-horiz-decr', 0.05)], + human=dict(skin='young_caucasian_male', brows='eyebrow001', hair='short02', eyes='grey'), + clothes=['male_elegantsuit01', 'shoes04'], tex=2048, hair_col='#2a1f19', bow=True, + suit=dict(wool='#17171b', lapel='satin', tie='front'), shoe=('#0a0a0b', 0.14), + layout=[('male_elegantsuit01', (0, 0, 1, 1)), ('shoes04', (1515 / 2048, 960 / 2048, 515 / 2048, 480 / 2048))]), + # Halcyon's suited security: charcoal suit, white shirt, narrow black tie, heavier build + 'suit': dict(name='Suit', macro=man(0.6, 0.72, 0.62, 0.75), face=HEAVY + [('head/head-square', 0.5), ('nose/nose-scale-horiz-incr', 0.3), + ('chin/chin-width-incr', 0.35), ('eyebrows/eyebrows-angle-down', 0.3), ('mouth/mouth-scale-horiz-incr', 0.1)], + human=dict(skin='middleage_caucasian_male', brows='eyebrow005', hair='short04', eyes='brown'), + clothes=['male_elegantsuit01', 'shoes04'], tex=1024, hair_col='#1b1512', + suit=dict(wool='#23252b', lapel=None, tie='#0e0f12'), shoe=('#0d0d0e', 0.35), + layout=[('male_elegantsuit01', (0, 0, 1, 1)), ('shoes04', (1515 / 2048, 960 / 2048, 515 / 2048, 480 / 2048))]), + # Halcyon's tactical guards: black tee, plate carrier, grey cargo trousers, boots + 'tac': dict(name='Tac', macro=man(0.58, 0.8, 0.55, 0.8), face=HEAVY + [('head/head-oval', 0.3), ('nose/nose-hump-incr', 0.4), + ('cheek/l-cheek-volume-decr', 0.3), ('cheek/r-cheek-volume-decr', 0.3), ('chin/chin-prominent-incr', 0.3)], + human=dict(skin='young_caucasian_male2', brows='eyebrow009', hair='short01', eyes='brownlight'), + clothes=['male_casualsuit06', 'shoes03'], tex=1024, hair_col='#1e1915', + cols=dict(top='#1a1b1e', bottom='#4a4c4f'), vest='#2b2c28', shoe=('#141414', 0.55), + layout=[('male_casualsuit06', (0, 0, 1, 0.75)), ('shoes03', (0, 0.75, 0.5, 0.25)), ('vest', (0.5, 0.75, 0.5, 0.25))]), + # summer visitors and townspeople + 'civm1': dict(name='CivM1', macro=man(0.5, 0.5, 0.55, 0.75, 'caucasian'), face=[('head/head-round', 0.3), ('nose/nose-scale-vert-incr', 0.2), + ('eyebrows/eyebrows-trans-up', 0.2), ('mouth/mouth-scale-horiz-incr', 0.15)], + human=dict(skin='middleage_caucasian_male', brows='eyebrow002', hair='short03', eyes='blue'), + clothes=['male_casualsuit01', 'shoes01'], tex=1024, hair_col='#6b4e36', + cols=dict(top='#eceae2', bottom='#c9b897'), weave='linen', shoe=('#5a3a22', 0.45), + layout=[('male_casualsuit01', (0, 0, 1, 0.75)), ('shoes01', (0, 0.75, 0.5, 0.25))]), + 'civm2': dict(name='CivM2', macro=man(0.45, 0.55, 0.45, 0.8, 'african'), face=[('head/head-oval', 0.3), ('chin/chin-width-incr', 0.2)], + human=dict(skin='young_african_male', brows='eyebrow003', hair='short01', eyes='brown'), + clothes=['male_casualsuit06', 'shoes05'], tex=1024, hair_col='#0f0c0b', + cols=dict(top='#f3f1ea', bottom='#2f3d55'), stripes=('top', '#22345c', 0.018), shoe=('#efefea', 0.6), + layout=[('male_casualsuit06', (0, 0, 1, 0.75)), ('shoes05', (0, 0.75, 0.5, 0.25))]), + 'civf1': dict(name='CivF1', macro=woman(0.5, 0.45, 0.45, 0.85), face=[('nose/nose-scale-horiz-decr', 0.2), ('mouth/mouth-scale-horiz-decr', 0.1)], + human=dict(skin='young_caucasian_female', brows='eyebrow011', hair='ponytail01', eyes='green', lashes='eyelashes02'), + clothes=['female_elegantsuit01', 'shoes05'], tex=1024, hair_col='#4a2f1e', female=True, + cols=dict(top='#f6f3ec', bottom='#d9674e'), weave='linen', shoe=('#e9e2d4', 0.6), + layout=[('female_elegantsuit01', (0, 0, 1, 0.75)), ('shoes05', (0, 0.75, 0.5, 0.25))]), + 'civf2': dict(name='CivF2', macro=woman(0.45, 0.45, 0.5, 0.8, 'asian'), face=[('head/head-round', 0.2)], + human=dict(skin='young_asian_female', brows='eyebrow010', hair='bob02', eyes='brown', lashes='eyelashes02'), + clothes=['female_casualsuit01', 'shoes06'], tex=1024, hair_col='#14100e', female=True, + cols=dict(top='#e8c55a', bottom='#f2efe6'), shoe=('#b88a5a', 0.55), + layout=[('female_casualsuit01', (0, 0, 1, 0.75)), ('shoes06', (0, 0.75, 0.5, 0.25))]), +} + +def dress(kind, spec, H, worn, td): + size = spec.get('tex', 1024) + mats = {} + alb, nrm, orm = skin_set(H['skin_png'], td + '/skin', size) + P.set_mat(H['body'], P.material(kind + '_skin', alb, nrm, orm)) + for item, ob in worn: + if item == 'male_elegantsuit01': a, n, o = tex_male_elegantsuit01(td + '/' + item, size, spec) + elif item.startswith('shoes'): a, n, o = tex_shoes(item, td + '/' + item, size, spec) + else: a, n, o = tex_generic(item, td + '/' + item, size, spec, ob, H) + P.set_mat(ob, P.material(kind + '_' + item, a, n, o)) + if item == 'male_elegantsuit01': print('jacket tail verts', jacket_tail(ob, H)) + if item == 'male_elegantsuit01' and spec['suit'].get('tie') == 'front': + masks = np.load(td + '/' + item + '_masks.npy').astype(np.float32) + print('tie flattened', flatten_tie(ob, masks[2] > 0.5, H)) + if spec.get('bow'): bow_tie(ob, H, mats.setdefault('satin', satin_mat(kind))) + if spec.get('vest'): + top = [ob for item, ob in worn if not item.startswith('shoes')][0] + v = plate_carrier(top, H, td, spec) + if H.get('hair'): + P.set_mat(H['hair'], P.material(kind + '_hair', tint_hair(H['hair_png'], td + '/hair.png', spec.get('hair_col')), alpha=True, rough=0.45)) + P.set_mat(H['brows'], P.material(kind + '_brows', H['brows_png'], alpha=True)) + P.set_mat(H['lashes'], P.material(kind + '_lashes', H['lashes_png'], alpha=True)) + P.set_mat(H['eyes'], P.material(kind + '_eyes', H['eye_png'], rough=0.1)) + +def skin_set(png, base, size): + src = P.img_np(png, size) + src = np.clip(src * np.array([1.0, 0.93, 0.85], np.float32) ** 0.6 * 0.97, 0, 1) # a Mediterranean summer tan + lum = src.mean(-1) + hp = lum - P.blur(lum, 3) + pores = P.fbm(size, 6, seed=3, oct=2) + h = hp * 0.8 + (pores - 0.5) * 0.04 + n = P.normal_from_height(h, 6.0 * size / 2048) + rough = np.clip(0.5 + (pores - 0.5) * 0.25 - hp * 1.5, 0.35, 0.7) + orm = np.stack([np.ones_like(rough), rough, np.zeros_like(rough)], -1) + return P.save(src, base + '_albedo.jpg', 92), P.save(n, base + '_normal.jpg', 92), P.save(orm, base + '_orm.jpg', 88) + +def tex_male_elegantsuit01(base, size, spec): + """Black tuxedo: wool jacket and trousers, satin-faced lapels, white dress shirt, studs, patent shoes.""" + src = P.img_np(L.MHA + '/clothes/male_elegantsuit01/male_elegantsuit01_diffuse.png', size, 'RGBA') + rgb = src[..., :3]; lum = rgb.mean(-1) + mx, mn = rgb.max(-1), rgb.min(-1); sat = (mx - mn) / np.maximum(mx, 1e-3) + bg = np.median(rgb[: size // 64, size // 2: size // 2 + size // 16].reshape(-1, 3), 0) + island = (np.abs(rgb - bg).max(-1) > 3 / 255).astype(np.float32) + island = np.clip(P.blur(island, 2) * 3, 0, 1) + shirt = ((lum > 0.5) & (sat < 0.3)).astype(np.float32) + tie = ((sat > 0.22) & (rgb[..., 2] > rgb[..., 0] + 0.05)).astype(np.float32) + tie = np.clip(P.blur(tie, 4) * 4, 0, 1) + shoe = P.poly_mask(size, [[(1490, 956), (2010, 956), (2010, 1444), (1490, 1444)]]) + lapel = P.poly_mask(size, [[(1000, 185), (1005, 330), (1100, 565), (1132, 565), (1132, 185)], + [(1250, 185), (1245, 330), (1150, 565), (1118, 565), (1118, 185)]]) * (1 - shirt) + lapel = P.blur(lapel, 1.2) + detail = np.clip(lum / np.maximum(P.blur(lum, 10), 1e-3), 0.55, 1.5) + fold = np.clip(P.blur(lum, 18) / np.maximum(np.median(P.blur(lum, 18)[island > 0.5]), 1e-3), 0.6, 1.35) + weave = P.fbm(size, 1.5, seed=7, oct=2) + SU = spec['suit'] + if SU.get('lapel') != 'satin': lapel = lapel * 0 + if SU.get('tie') != 'front': tie_keep = tie.copy() + wool = P.hex3(SU['wool']) * (detail ** 0.9 * (0.75 + 0.25 * fold) * (0.93 + 0.14 * weave))[..., None] + satin = P.hex3('#0c0c0f') * (detail ** 0.25 * (0.8 + 0.2 * fold))[..., None] + shirt_c = P.hex3('#f1f0ea') * np.clip(lum / 0.85, 0.55, 1.05)[..., None] + # the tie becomes the shirt front: a pleated bib with a placket and three black studs, laid out along the tie's + # own axis in the texture (the tie island is drawn at a slant) + ys, xs = np.nonzero(tie > 0.5) + front = shirt_c.copy() + bib = np.clip(P.blur(tie, 10) * 3, 0, 1) + if len(xs): + k = size / 2048 + cx, cy = xs.mean(), ys.mean() + cov = np.cov(np.stack([xs - cx, ys - cy])) + w, vec = np.linalg.eigh(cov); ax = vec[:, 1] # long axis (down the tie) + if ax[1] < 0: ax = -ax + X = np.arange(size)[None, :].repeat(size, 0) - cx; Y = np.arange(size)[:, None].repeat(size, 1) - cy + along = X * ax[0] + Y * ax[1]; across = -X * ax[1] + Y * ax[0] + a0, a1 = (xs - cx) * ax[0] + (ys - cy) * ax[1], None + lo, hi = a0.min(), a0.max() + pleat = 0.95 + 0.05 * np.cos(across / (9 * k) * math.pi) ** 2 + front = P.hex3('#f5f4ef') * pleat[..., None] * (1 - 0.05 * (np.abs(across) < 6 * k))[..., None] + for i in range(3): + t = lo + (hi - lo) * (0.28 + 0.24 * i) + d = np.hypot(along - t, across) + stud = np.clip(1 - d / (5.5 * k), 0, 1) + front = np.where((stud > 0)[..., None], P.hex3('#0b0b0d') + 0.35 * (stud ** 6)[..., None], front) + tie = bib + shoes = P.hex3('#0a0a0b') * (0.6 + 0.4 * np.clip(lum / max(lum[shoe > 0.5].mean(), 1e-3), 0.5, 1.6))[..., None] + out = wool + out = out * (1 - lapel[..., None]) + satin * lapel[..., None] + out = out * (1 - shirt[..., None]) + shirt_c * shirt[..., None] + if SU.get('tie') == 'front': out = out * (1 - tie[..., None]) + front * tie[..., None] + else: + tk = np.clip(P.blur(tie_keep, 1.5) * 2, 0, 1) + tiec = P.hex3(SU['tie']) * (0.7 + 0.3 * detail ** 2)[..., None] + out = out * (1 - tk[..., None]) + tiec * tk[..., None]; tie = tk * 0 + out = out * (1 - shoe[..., None]) + shoes * shoe[..., None] + rough = 0.82 - 0.08 * weave + rough = rough * (1 - lapel) + 0.3 * lapel + rough = rough * (1 - shirt) + 0.62 * shirt + rough = rough * (1 - tie) + 0.55 * tie + rough = rough * (1 - shoe) + 0.16 * shoe + h = (detail - 1) * 0.12 * (1 - lapel * 0.8) + (weave - 0.5) * 0.04 * (1 - lapel) * (1 - shoe) + nrm = P.normal_from_height(h, 9 * size / 2048) + orm = np.stack([np.ones_like(rough), rough, np.zeros_like(rough)], -1) + np.save(base + '_masks.npy', np.stack([lapel, shirt, tie, shoe], 0).astype(np.float16)) + return P.save(out, base + '_albedo.jpg', 92), P.save(nrm, base + '_normal.jpg', 92), P.save(orm, base + '_orm.jpg', 88) + +def tint_hair(png, out, col): + from PIL import Image + im = P.img_np(png, None, 'RGBA') + if col: + lum = im[..., :3].mean(-1, keepdims=True) + lum = lum / max(np.percentile(lum[im[..., 3] > 0.5], 90), 1e-3) + im[..., :3] = np.clip(P.hex3(col) * (0.55 + 0.75 * lum), 0, 1) + Image.fromarray(np.clip(im * 255 + 0.5, 0, 255).astype(np.uint8), 'RGBA').save(out) + return out + +def drop_faces_uv(ob, mask): + """Delete faces whose UV centre lands inside mask (size x size, y down).""" + import bmesh + n = mask.shape[0] + bm = bmesh.new(); bm.from_mesh(ob.data); uv = bm.loops.layers.uv['UVMap'] + kill = [] + for f in bm.faces: + u = sum(l[uv].uv.x for l in f.loops) / len(f.loops); v = sum(l[uv].uv.y for l in f.loops) / len(f.loops) + x, y = int(min(n - 1, max(0, u * n))), int(min(n - 1, max(0, (1 - v) * n))) + if mask[y, x]: kill.append(f) + bmesh.ops.delete(bm, geom=kill, context='FACES') + bm.to_mesh(ob.data); bm.free() + return len(kill) + +def satin_mat(kind): + m = bpy.data.materials.new(kind + '_satin'); m.use_nodes = True + b = m.node_tree.nodes['Principled BSDF'] + b.inputs['Base Color'].default_value = (0.006, 0.006, 0.007, 1); b.inputs['Roughness'].default_value = 0.38 + return m + +def bow_tie(collar, H, mat): + """A black satin bow tie at the front of the shirt collar: two pinched lobes, a knot and the band ends.""" + import bmesh + me = collar.data + # the collar front: the most forward (-Y) collar vertex near x=0 high on the neck + neck = H['J']['neck_01'][0] + best = None + for v in me.vertices: + p = v.co + if abs(p.x) < 0.012 and neck.z - 0.07 < p.z < neck.z + 0.03: + if best is None or p.y < best.y: best = p.copy() + c = Vector((0, best.y - 0.012, best.z - 0.028)) + bm = bmesh.new() + def lobe(side): + r = bmesh.ops.create_uvsphere(bm, u_segments=14, v_segments=8, radius=1.0) + for v in r['verts']: + x, y, z = v.co + ax = (x + 1) / 2 # 0 at the knot, 1 at the outer end + pinch = 0.32 + 0.68 * math.sin(min(1, ax * 1.15) * math.pi / 2) ** 0.8 + flare = 1 + 0.25 * max(0, ax - 0.6) + v.co = Vector((side * (0.008 + ax * 0.05), y * 0.0055 * pinch, z * 0.022 * pinch * flare)) + # the outer edge dips in the middle, like a tied butterfly + if ax > 0.85: v.co.x -= side * 0.004 * (1 - abs(z)) + lobe(1); lobe(-1) + k = bmesh.ops.create_uvsphere(bm, u_segments=10, v_segments=6, radius=1.0) + for v in k['verts']: v.co = Vector((v.co.x * 0.0085, v.co.y * 0.0075 - 0.002, v.co.z * 0.012)) + for v in bm.verts: v.co += c + ob = G.mesh_obj('BowTie', [], []) + bm.to_mesh(ob.data); bm.free() + for p in ob.data.polygons: p.use_smooth = True + ob.data.materials.append(mat) + ob.data.uv_layers.new(name='UVMap') + G.transfer_weights(ob, collar) + return ob + +def tex_shoes(item, base, size, spec): + """Shoes in the outfit's colour, keeping the source's light and shade (patent finish for the agent).""" + s = size // 2 + src = P.img_np(L.MHA + '/clothes/%s/%s_diffuse.png' % (item, item), s) + lum = src.mean(-1) + col, r0 = spec.get('shoe', ('#0b0b0c', 0.3)) + rel = np.clip(lum / max(np.median(lum[lum > 0.02]), 1e-3), 0.3, 2.0) + out = np.clip(P.hex3(col) * (0.55 + 0.45 * rel)[..., None], 0, 1) + sole = (lum > np.percentile(lum, 97)).astype(np.float32) + rough = np.full_like(lum, r0) + 0.3 * sole + nrm = P.normal_from_height((lum - P.blur(lum, 3)) * 0.2, 4) + orm = np.stack([np.ones_like(rough), rough, np.zeros_like(rough)], -1) + return P.save(out, base + '_albedo.jpg', 92), P.save(nrm, base + '_normal.jpg', 92), P.save(orm, base + '_orm.jpg', 88) + +def flatten_tie(ob, mask, H): + """The suit's long tie becomes a flat shirt front: its vertices are pressed back onto the chest (the body's + surface measured before the covered body was removed), so the bib texture lies where the tie hung.""" + n = mask.shape[0]; me = ob.data; uv = me.uv_layers['UVMap'].data + tie = set() + for p in me.polygons: + u = sum(uv[li].uv.x for li in p.loop_indices) / p.loop_total; v = sum(uv[li].uv.y for li in p.loop_indices) / p.loop_total + if mask[int(min(n - 1, max(0, (1 - v) * n))), int(min(n - 1, max(0, u * n)))]: tie.update(p.vertices) + bvh = H['chest_bvh'] + moved = 0 + for i in tie: + co = me.vertices[i].co + hit = bvh.ray_cast(Vector((co.x, co.y - 0.2, co.z)), Vector((0, 1, 0)), 0.5) + if hit[0] is not None: + me.vertices[i].co.y = hit[0].y - 0.007; moved += 1 + return moved + +def uv_islands(ob): + """Per face: an island id (faces joined by edges whose UVs match).""" + import bmesh + bm = bmesh.new(); bm.from_mesh(ob.data); uv = bm.loops.layers.uv['UVMap']; bm.faces.ensure_lookup_table() + par = list(range(len(bm.faces))) + def f(x): + while par[x] != x: par[x] = par[par[x]]; x = par[x] + return x + for e in bm.edges: + ls = e.link_loops + if len(ls) != 2: continue + a, b = ls + ua = (a[uv].uv.copy(), a.link_loop_next[uv].uv.copy()); ub = (b.link_loop_next[uv].uv.copy(), b[uv].uv.copy()) + if (ua[0] - ub[0]).length < 1e-5 and (ua[1] - ub[1]).length < 1e-5: + par[f(a.face.index)] = f(b.face.index) + ids = [f(i) for i in range(len(bm.faces))] + polys = [[(l[uv].uv.x, l[uv].uv.y) for l in fc.loops] for fc in bm.faces] + zs = [fc.calc_center_median().z for fc in bm.faces] + bm.free() + return ids, polys, zs + +def raster_labels(ob, size, H): + """Texture-space label image: 1 where the UV island belongs to the top (shirt, blouse), 2 for the bottom.""" + from PIL import Image, ImageDraw + ids, polys, zs = uv_islands(ob) + import collections + acc = collections.defaultdict(list) + for i, z in zip(ids, zs): acc[i].append(z) + cut = H['J']['pelvis'][0].z + 0.02 + lab = {i: (1 if np.mean(v) > cut else 2) for i, v in acc.items()} + im = Image.new('L', (size, size), 0); d = ImageDraw.Draw(im) + for i, p in zip(ids, polys): + d.polygon([(u * size, (1 - v) * size) for u, v in p], fill=lab[i]) + lab_img = np.asarray(im.filter(__import__('PIL.ImageFilter', fromlist=['x']).MaxFilter(5))) + return lab_img + +def tex_generic(item, base, size, spec, ob, H): + """Any MakeHuman outfit: each UV island takes the top or bottom colour of the spec, keeping the source's folds + and seams (its light and shade relative to the island), with linen slub or stripes added in code. Logos and + prints in the source (saturated texels) are flattened out.""" + src = P.img_np(L.MHA + '/clothes/%s/%s_diffuse.png' % (item, item), size, 'RGB') + lum = src.mean(-1); mx, mn = src.max(-1), src.min(-1); sat = (mx - mn) / np.maximum(mx, 1e-3) + lab = raster_labels(ob, size, H) + smooth = P.blur(lum, 14) + logo = np.clip((sat - 0.3) * 5, 0, 1); logo = np.clip(P.blur(logo, 6) * 3, 0, 1) + local = lum * (1 - logo) + smooth * logo + rel = np.clip(local / np.maximum(P.blur(local, 40), 1e-3), 0.5, 1.4) + out = np.zeros((size, size, 3), np.float32); rough = np.full((size, size), 0.8, np.float32) + weave = P.fbm(size, 1.2, seed=11, oct=2) + slub = P.fbm(size, 0.6, seed=5, oct=1) if spec.get('weave') == 'linen' else np.full_like(lum, 0.5) + for k, name in ((1, 'top'), (2, 'bottom')): + m = (lab == k) + c = P.hex3(spec['cols'][name]) + shade = rel ** 1.1 * (0.94 + 0.12 * weave) * (0.95 + 0.1 * slub) + out[m] = (c[None, :] * shade[m][:, None]) + if spec.get('stripes'): + part, sc, w = spec['stripes']; k = 1 if part == 'top' else 2 + Y = np.arange(size)[:, None].repeat(size, 1) / size + st = (np.sin(Y / w * math.pi) > 0.25) & (lab == k) + out[st] = P.hex3(sc)[None, :] * (rel[st] ** 1.1)[:, None] + h = (rel - 1) * 0.15 + (weave - 0.5) * 0.05 + (slub - 0.5) * 0.04 + nrm = P.normal_from_height(h, 8 * size / 2048) + orm = np.stack([np.ones_like(rough), rough, np.zeros_like(rough)], -1) + return P.save(np.clip(out, 0, 1), base + '_albedo.jpg', 92), P.save(nrm, base + '_normal.jpg', 92), P.save(orm, base + '_orm.jpg', 88) + +def plate_carrier(top, H, td, spec): + """A plate carrier made from the shirt's torso: faces of the chest and back between the waist and the armpits are + copied, pushed out 2.5 cm and given thickness; nylon texture with pouches and a name-tape panel drawn in code.""" + import bmesh + J = H['J']; z0 = J['pelvis'][0].z + 0.17; z1 = J['clavicle_l'][0].z - 0.03 + sx = abs(J['upperarm_l'][0].x) - 0.035 + me = top.data + bm = bmesh.new(); bm.from_mesh(me) + z0 -= 0.05 + def wid(z): return sx * (0.55 if z > z1 - 0.11 else 1.0) + keep = set() + for f in bm.faces: + if any(z0 - 0.03 < v.co.z < z1 + 0.03 and abs(v.co.x) < wid(v.co.z) + 0.03 for v in f.verts): keep.add(f.index) + kill = [f for f in bm.faces if f.index not in keep] + bmesh.ops.delete(bm, geom=kill, context='FACES') + bm.normal_update() + # clamp onto a clean outline (straight hem and top, armholes) so the cut edges are not stair-stepped + for v in bm.verts: + v.co.z = min(max(v.co.z, z0), z1) + w = wid(v.co.z) + if abs(v.co.x) > w: v.co.x = math.copysign(w, v.co.x) + for v in bm.verts: v.co += v.normal * 0.024 + vm = bpy.data.meshes.new('vest'); bm.to_mesh(vm); bm.free() + ob = bpy.data.objects.new('C_vest', vm); bpy.context.scene.collection.objects.link(ob) + # weights from the shirt + for vg in top.vertex_groups: ob.vertex_groups.new(name=vg.name) + G.transfer_weights(ob, top) + sol = ob.modifiers.new('s', 'SOLIDIFY'); sol.thickness = 0.018; sol.offset = 1 + L.set_active(ob); bpy.ops.object.modifier_apply(modifier=sol.name) + # planar UVs: front and back projected (x, z) into the vest rect + zs = [v.co.z for v in vm.vertices]; zmin, zmax = min(zs), max(zs) + uvl = vm.uv_layers.new(name='UVMap') if 'UVMap' not in vm.uv_layers else vm.uv_layers['UVMap'] + for p in vm.polygons: + back = p.normal.y > 0 + for li in p.loop_indices: + co = vm.vertices[vm.loops[li].vertex_index].co + u = (co.x / (2 * sx) + 0.5) * 0.5 + (0.5 if back else 0) + uvl.data[li].uv = (u, (co.z - zmin) / (zmax - zmin)) + # texture: nylon weave, MOLLE rows, two front pouches, edge binding + size = 512 + X = np.arange(size)[None, :].repeat(size, 0) / size; Y = 1 - np.arange(size)[:, None].repeat(size, 1) / size + base = P.hex3(spec['vest']); weave = P.fbm(size, 1.0, seed=2, oct=2) + lum = 0.9 + 0.12 * weave + molle = ((np.sin(Y * 60) > 0.6) & (Y < 0.55)).astype(np.float32) * 0.18 + pouch = np.zeros_like(X) + for cx in (0.13, 0.25, 0.37): + pouch += ((np.abs(X - cx) < 0.05) & (Y > 0.08) & (Y < 0.42)).astype(np.float32) + edge = ((Y < 0.03) | (Y > 0.97)).astype(np.float32) + shade = lum - molle + pouch * 0.08 - edge * 0.15 + alb = np.clip(base[None, None, :] * shade[..., None], 0, 1) + h = weave * 0.04 + pouch * 0.6 - molle * 0.3 + P.save(alb, td + '/vest_albedo.jpg'); P.save(P.normal_from_height(P.blur(h, 1), 6), td + '/vest_normal.jpg') + rough = np.full((size, size), 0.85, np.float32) + P.save(np.stack([np.ones_like(rough), rough, np.zeros_like(rough)], -1), td + '/vest_orm.jpg') + P.set_mat(ob, P.material('vest', td + '/vest_albedo.jpg', td + '/vest_normal.jpg', td + '/vest_orm.jpg')) + return ob + +def jacket_tail(ob, H): + """A jacket's skirt hangs from the waist: below the waist its vertices take most of their weight from the pelvis + instead of the thighs (MakeHuman's fitted weights make it hug the hips like a skirt). The trousers, a separate + piece of the mesh, keep their own weights.""" + me = ob.data + # connected pieces: the biggest is the jacket and shirt, the other the trousers + par = list(range(len(me.vertices))) + def f(x): + while par[x] != x: par[x] = par[par[x]]; x = par[x] + return x + for e in me.edges: par[f(e.vertices[0])] = f(e.vertices[1]) + import collections + cnt = collections.Counter(f(i) for i in range(len(me.vertices))) + jacket = cnt.most_common(1)[0][0] + pz = H['J']['pelvis'][0].z + gi = {g.index: g.name for g in ob.vertex_groups} + pel = ob.vertex_groups.get('pelvis') or ob.vertex_groups.new(name='pelvis') + legs = ('thigh_l', 'thigh_r', 'calf_l', 'calf_r', 'thigh_twist_01_l', 'thigh_twist_01_r') + n = 0 + for v in me.vertices: + if f(v.index) != jacket: continue + t = min(1.0, max(0.0, (pz + 0.12 - v.co.z) / 0.16)) + t = t * t * (3 - 2 * t) * 0.8 + if t <= 0: continue + moved = 0.0 + for g in v.groups: + if gi[g.group] in legs: + d = g.weight * t; ob.vertex_groups[g.group].add([v.index], g.weight - d, 'REPLACE'); moved += d + if moved > 0: pel.add([v.index], moved, 'ADD'); n += 1 + return n diff --git a/e63334287a3deaa3/blacktie/tools/chars/people.py b/e63334287a3deaa3/blacktie/tools/chars/people.py new file mode 100644 index 00000000..0f8282ef --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/people.py @@ -0,0 +1,155 @@ +# Shared helpers for build_people.py: MakeHuman clothes (CC0) fitted to the body, body vertices under the clothes +# removed, code-made texture sets for each outfit, the bow tie, export. Runs in Blender as a module (bpy). +import bpy, os, sys, math, glob +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 + +HERE = os.path.dirname(os.path.abspath(__file__)) +CL = L.MHA + '/clothes' + +def read_delete_verts(path): + out, on = set(), False + for ln in open(path): + s = ln.strip() + if s.startswith('delete_verts'): on = True; continue + if not on: continue + if not s or not (s[0].isdigit()): + if s and not s[0].isdigit(): on = False + continue + a = s.split(); i = 0 + while i < len(a): + if i + 2 < len(a) and a[i + 1] == '-': + out.update(range(int(a[i]), int(a[i + 2]) + 1)); i += 3 + else: + out.add(int(a[i])); i += 1 + return out + +def wear(H, V, item, name): + """Fit one MakeHuman clothes item to the human. Returns (obj, set of base verts it hides).""" + path = CL + '/%s/%s.mhclo' % (item, item) + ob, refs = L.fit_mhclo(path, V, name) + L.add_proxy_weights(ob, refs) + return ob, read_delete_verts(path) + +def delete_body_verts(body, used, dele): + import bmesh + bm = bmesh.new(); bm.from_mesh(body.data) + bm.verts.ensure_lookup_table() + kill = [bm.verts[i] for i, b in enumerate(used) if b in dele] + bmesh.ops.delete(bm, geom=kill, context='VERTS') + bm.to_mesh(body.data); bm.free() + return len(kill) + +def img_np(path, size=None, mode='RGB'): + from PIL import Image + im = Image.open(path).convert(mode) + if size and im.size != (size, size): im = im.resize((size, size), Image.LANCZOS) + return np.asarray(im).astype(np.float32) / 255 + +def save(arr, path, q=90): + from PIL import Image + a = np.clip(arr * 255 + 0.5, 0, 255).astype(np.uint8) + Image.fromarray(a).save(path, quality=q) + return path + +def blur(a, r): + from PIL import Image, ImageFilter + if a.ndim == 2: + im = Image.fromarray((np.clip(a, 0, 1) * 65535).astype(np.uint16).astype(np.int32), mode='I') + im = Image.fromarray(np.clip(a * 255, 0, 255).astype(np.uint8)) + return np.asarray(im.filter(ImageFilter.GaussianBlur(r))).astype(np.float32) / 255 + return np.stack([blur(a[..., k], r) for k in range(a.shape[2])], -1) + +def normal_from_height(h, strength): + gy, gx = np.gradient(h) + n = np.stack([-gx * strength, gy * strength, np.ones_like(h)], -1) + n /= np.linalg.norm(n, axis=-1, keepdims=True) + return n * 0.5 + 0.5 + +def poly_mask(size, polys): + """Polygons in texture pixel coords of a 2048 image (y down), scaled to size.""" + from PIL import Image, ImageDraw + im = Image.new('L', (size, size), 0); d = ImageDraw.Draw(im); k = size / 2048 + for p in polys: d.polygon([(x * k, y * k) for x, y in p], fill=255) + return np.asarray(im).astype(np.float32) / 255 + +def hex3(h): + h = h.lstrip('#'); return np.array([int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)], np.float32) + +def fbm(size, scale, seed=0, oct=4): + rng = np.random.default_rng(seed); out = np.zeros((size, size), np.float32); amp = 1.0; tot = 0 + from PIL import Image + for o in range(oct): + n = max(2, int(size / scale * 2 ** o)) + r = rng.random((n, n)).astype(np.float32) + im = Image.fromarray((r * 255).astype(np.uint8)).resize((size, size), Image.BICUBIC) + out += np.asarray(im).astype(np.float32) / 255 * amp; tot += amp; amp *= 0.5 + return out / tot + +def material(name, albedo, normal=None, orm=None, alpha=False, rough=0.6): + 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(albedo) + nt.links.new(tex.outputs[0], b.inputs['Base Color']) + if alpha: + nt.links.new(tex.outputs[1], b.inputs['Alpha']) + try: m.blend_method = 'CLIP' + except Exception: pass + try: m.surface_render_method = 'DITHERED' + except Exception: pass + if normal: + nm = nt.nodes.new('ShaderNodeNormalMap'); t2 = nt.nodes.new('ShaderNodeTexImage') + t2.image = bpy.data.images.load(normal); t2.image.colorspace_settings.name = 'Non-Color' + nt.links.new(t2.outputs[0], nm.inputs['Color']); nt.links.new(nm.outputs[0], b.inputs['Normal']) + if orm: + o = nt.nodes.new('ShaderNodeTexImage'); o.image = bpy.data.images.load(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 + return m + +def set_mat(ob, m): + ob.data.materials.clear(); ob.data.materials.append(m) + for p in ob.data.polygons: p.material_index = 0 + + +def smooth_shoulders(ob, H, radius=0.2, iters=10): + """The rest pose is a T-pose; with the arms down, MakeHuman's tight shoulder weights fold the deltoid into the + chest and leave the top of the shoulder standing as a ridge (boxy jacket shoulders). Average every vertex group's + weights with the neighbours' for the vertices round each shoulder joint, so the bend is spread over the shoulder.""" + me = ob.data + centres = [H['J']['upperarm_l'][0], H['J']['upperarm_r'][0]] + sel = [v.index for v in me.vertices if min((v.co - c).length for c in centres) < radius] + if not sel: return 0 + selset = set(sel) + adj = {i: set() for i in sel} + for e in me.edges: + a, b = e.vertices + if a in selset: adj[a].add(b) + if b in selset: adj[b].add(a) + ng = len(ob.vertex_groups) + W = {} + need = set(sel) + for i in sel: need |= adj[i] + for i in need: + W[i] = {g.group: g.weight for g in me.vertices[i].groups} + for _ in range(iters): + new = {} + for i in sel: + acc = dict(W[i]); n = 1 + for j in adj[i]: + for g, w in W[j].items(): acc[g] = acc.get(g, 0) + w + n += 1 + # blend less at the edge of the region so it joins the untouched weights + k = max(0.0, 1 - min((me.vertices[i].co - c).length for c in centres) / radius) + k = min(1.0, k * 2.5) * 0.7 + new[i] = {g: W[i].get(g, 0) * (1 - k) + (w / n) * k for g, w in acc.items()} + for i in sel: W[i] = new[i] + for i in sel: + tot = sum(W[i].values()) or 1 + for g, w in W[i].items(): + ob.vertex_groups[g].add([i], w / tot, 'REPLACE') + return len(sel) diff --git a/e63334287a3deaa3/blacktie/tools/chars/preview.py b/e63334287a3deaa3/blacktie/tools/chars/preview.py new file mode 100644 index 00000000..dc0f6fe2 --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/preview.py @@ -0,0 +1,31 @@ +# Cycles stills of a .blend made by build_people.py, for checking by eye. +# python preview.py file.blend out.png [full|face|back] [object-name-prefix] +import bpy, sys, math +from mathutils import Vector +blend, out = sys.argv[1], sys.argv[2] +view = sys.argv[3] if len(sys.argv) > 3 else 'full' +only = sys.argv[4] if len(sys.argv) > 4 else '' +bpy.ops.wm.open_mainfile(filepath=blend) +sc = bpy.context.scene +if only: + for o in sc.objects: + if o.type == 'MESH' and not o.name.startswith(tuple(only.split(','))): o.hide_render = True +sc.render.engine = 'CYCLES'; sc.cycles.samples = 24; sc.cycles.device = 'CPU' +try: sc.cycles.use_denoising = True +except Exception: pass +sc.render.resolution_x, sc.render.resolution_y = (700, 1000) if view != 'face' else (700, 700) +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.68, 1); w.node_tree.nodes['Background'].inputs[1].default_value = 0.35 +def light(name, loc, e, size=1.5, col=(1, 0.95, 0.88)): + d = bpy.data.lights.new(name, 'AREA'); d.energy = e; d.size = size; d.color = col + o = bpy.data.objects.new(name, d); sc.collection.objects.link(o); o.location = loc + o.rotation_euler = (Vector((0, 0, 1.2)) - Vector(loc)).to_track_quat('-Z', 'Y').to_euler() +light('key', (-2.2, -3.0, 2.8), 450); light('fill', (2.5, -2.0, 1.6), 110, col=(0.8, 0.88, 1)); light('rim', (1.5, 3, 2.5), 350) +cam = bpy.data.objects.new('cam', bpy.data.cameras.new('cam')); sc.collection.objects.link(cam); sc.camera = cam +if view == 'full': cam.location = (0.9, -3.6, 1.05); tgt = Vector((0, 0, 0.92)); cam.data.lens = 50 +elif view == 'back': cam.location = (-0.9, 3.6, 1.05); tgt = Vector((0, 0, 0.92)); cam.data.lens = 50 +elif view == 'torso': cam.location = (0.5, -1.6, 1.45); tgt = Vector((0, 0, 1.32)); cam.data.lens = 60 +else: cam.location = (0.3, -0.95, 1.74); tgt = Vector((0, 0, 1.70)); cam.data.lens = 85 +cam.rotation_euler = (tgt - cam.location).to_track_quat('-Z', 'Y').to_euler() +sc.render.filepath = out +bpy.ops.render.render(write_still=True) diff --git a/e63334287a3deaa3/blacktie/tools/chars/webp_glb.py b/e63334287a3deaa3/blacktie/tools/chars/webp_glb.py new file mode 100644 index 00000000..96a9152f --- /dev/null +++ b/e63334287a3deaa3/blacktie/tools/chars/webp_glb.py @@ -0,0 +1,98 @@ +"""Re-encode the images inside a .glb as WebP (EXT_texture_webp), in place. + +Run after export_people.py: python3 webp_glb.py ../../assets/*.glb +Colour and normal maps become lossy WebP (quality 88; alpha kept, for hair). Images already WebP are left alone. +three.js's GLTFLoader reads EXT_texture_webp; every browser the site supports decodes WebP (Safari 14+). +""" +import io +import json +import struct +import sys + +from PIL import Image + +QUALITY = 88 + + +def read_glb(path): + d = open(path, 'rb').read() + magic, ver, total = struct.unpack(' %.2f MB' % (path, len(new_bytes), before / 1e6, len(out) / 1e6)) + + +if __name__ == '__main__': + for p in sys.argv[1:]: + convert(p) diff --git a/e63334287a3deaa3/d06440218d1813a3/index.html b/e63334287a3deaa3/d06440218d1813a3/index.html index 5638e2ae..1f9a5d26 100644 --- a/e63334287a3deaa3/d06440218d1813a3/index.html +++ b/e63334287a3deaa3/d06440218d1813a3/index.html @@ -222,7 +222,7 @@

Admin