chore: prepare the repository for public release

Removes operator-private material from the shipped tree, corrects documentation
that had drifted from the code, deletes dead code, and applies a consistent
prose style.

Private material moved out of the public tree (docs/private/, git-ignored):
  - the wallet keyfile recovery runbook and its helper scripts, which together
    published the mainnet wallet file path, the service account, backup snapshot
    filenames, and the wallet RPC listener state. The helper duplicated the same
    constants, so relocating the document alone would not have removed them.
  - the stagenet parallel-candidate runbook and its fixtures.
  - the dated production-state record, the internal remediation plan, and the
    TODO list. None are reference documentation for an outside reader.

Redacted or genericised:
  - operator home-directory paths in shipped scripts and units. The asset build
    script now takes KENNEY_ASSETS_DIR instead of a hard-coded path.
  - private LAN addresses in tests, env examples and deploy docs, replaced with
    RFC 5737 documentation addresses.
  - the default alert sender and the notification hub example.
  - the Monero wallet unit now matches the Wownero one: a dedicated service
    account and a config file, instead of the operator's login account with the
    wallet password in argv where any local user can read it from /proc.

Ignore rules now cover every .env variant rather than the bare name, plus local
agent state. The deployment docs instruct operators to create .env.mainnet and
.env.stagenet, which the exact-name rule would have allowed to be committed.

Documentation corrected against the code: per-chain dungeon level counts, the
premium unlock rule, Tavern chat scope, backup retention, the chain-profile
fallback, the environment template location, and several sections describing
shipped work as pending.

Dead code removed: configPersistence, rpccalls, a duplicate vendored ROT.js
bundle, the unused tile-picker overlay, the unreachable legacy game-size path
and its vestigial parameter, spectator stubs that shadowed the real
SpectatorManager, and commented-out debugging. nip98 now imports the shared
nostr loader rather than duplicating it.

Prose style: em-dashes removed throughout in favour of colons, semicolons and
commas; comments restated as present-tense descriptions of the code rather than
narration of past changes.

127 suites / 1015 tests pass.
This commit is contained in:
jwinterm
2026-07-27 06:40:38 -04:00
parent 1cbbae73b2
commit ed24d43b56
207 changed files with 5023 additions and 8332 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
// AsciiRenderer — draws a Scene as a monospace glyph grid on a 2D canvas.
// AsciiRenderer: draws a Scene as a monospace glyph grid on a 2D canvas.
// The always-available fallback tier: tiny, legible, accessible.
(function (root) {
'use strict';
@@ -111,7 +111,7 @@
}
}
// Camera focus — centre the SP camera on the player cell (same convention as the tiled
// Camera focus: centre the SP camera on the player cell (same convention as the tiled
// renderer). Sticky: only update when the player is present, so switching TO ascii mid-game
// doesn't leave focusPoint null (which pinned the whole grid to the corner → black screen).
var focusFallback = null;
+61 -62
View File
@@ -45,10 +45,10 @@
data = data || {};
var prev = RK.entitlements || {};
// Consume the server-authoritative catalog (migration 024). This retires the hardcoded
// client pack list as the source of truth: operator-added packs appear, and existing packs
// pick up server definitions (label/projection/tier). Merged (not replaced) so any client
// fallback a render mode relies on is preserved if the operator's catalog omits it.
// The server catalog is authoritative over the client pack list: operator-added packs
// appear, and existing packs pick up server definitions (label/projection/tier). Merged
// rather than replaced so a client fallback a render mode relies on survives an operator
// catalog that omits it.
if (Array.isArray(data.catalog) && data.catalog.length) {
var merged = {};
for (var k in RK.PACKS) merged[k] = RK.PACKS[k];
@@ -130,15 +130,15 @@
};
RK.THEMES = {
// FREE baseline pack — the game's original bare tiles. Only the essentials are mapped
// (floor/wall/door/torch/features); furniture kinds (bar/keg/table/chair/…) are absent, so
// they fall back to floor and the free tavern reads plain — the intended "reason to unlock".
// Free baseline pack: the game's bare tiles. Only the essentials are mapped
// (floor/wall/door/torch/features); furniture kinds (bar/keg/table/chair, ...) are absent,
// so they fall back to floor and the free tavern reads plain, which is the reason to unlock.
'original': {
id: 'original',
label: 'Original Tiles',
// The game's ORIGINAL tileset (html/tiles.png, 32px, no spacing) — the exact tiles the
// ROT instructions + waiting screens use, so the free pack IS the classic look. Grid
// coords = the legacy pixel coords / 32 (see options.js tileMap).
// html/tiles.png, 32px, no spacing: the same tiles the ROT instructions and waiting
// screens use, so the free pack carries the classic look. Grid coords are the legacy
// pixel coords divided by 32 (see options.js tileMap).
tileset: { url: 'tiles.png', tile: 32, spacing: 0 },
tiles: {
floor: [0, 0],
@@ -149,58 +149,57 @@
exit: [1, 0],
treasure: [30, 0], // $W gold coin
torch: [32, 1],
// Classic entities too (the tiled renderer prefers a pack's player/monster tile over
// the sprite when present) — the blue-robe @ hero and the green ~ goblin.
// The tiled renderer prefers a pack's player/monster tile over the sprite when
// present: the blue-robe @ hero and the green ~ goblin.
player: [2, 0],
monster: [31, 1]
// No furniture kinds → tavern furniture falls back to floor (bare, as intended).
// No furniture kinds, so tavern furniture falls back to floor.
}
},
'roguelike-interior': {
id: 'roguelike-interior',
label: 'Kenney Roguelike Interior',
tileset: { url: 'assets/kenney/roguelikeSheet.png', tile: 16, spacing: 1 },
// Default tile picks from the sheet metadata ( roguelikeSheet_meta.json).
// Default tile picks from the sheet metadata (roguelikeSheet_meta.json).
// The tile-picker overlay can override these per-user via localStorage.
// Each kind maps to a single [col,row] on the sheet (cols = 57). Per-cell "variant"
// arrays were tried but mixing wood/stone/plank tiles per cell read as noise, so we
// keep one coherent tile per kind. (TileRenderer still accepts an array here if a
// future theme wants subtle, same-material variation.)
// Each kind maps to a single [col,row] on the sheet (cols = 57). One coherent tile per
// kind: mixing wood/stone/plank variants per cell reads as noise. TileRenderer still
// accepts an array here for a theme wanting subtle, same-material variation.
tiles: {
floor: [5, 2], // 119 — wood floor
floor2: [6, 2], // 120 — stone floor (accent)
wall: [13, 12], // 697 — stone masonry
floor: [5, 2], // 119 wood floor
floor2: [6, 2], // 120 stone floor (accent)
wall: [13, 12], // 697 stone masonry
// Tavern furnishings (coords from roguelikeSheet_meta.json labels: index -> [i%57, i/57]).
window: [42, 2], // 156 — window (in the wall)
bar: [29, 0], // 29 — bar counter
keg: [23, 0], // 23 — barrel / beer keg (behind the bar)
shelf: [30, 1], // 87 — shelf of bottles (behind the bar)
table: [20, 3], // 191 — table (191 reads wooden; 312 rendered green)
chair: [19, 3], // 190 — chair
barrel: [23, 0], // 23 — barrel (decor)
crate: [25, 0], // 25 — crate (decor)
rug: [11, 16], // 923 — rug
door: [37, 9], // 550 — door
window: [42, 2], // 156 window (in the wall)
bar: [29, 0], // 29 bar counter
keg: [23, 0], // 23 barrel / beer keg (behind the bar)
shelf: [30, 1], // 87 shelf of bottles (behind the bar)
table: [20, 3], // 191 table, reads wooden; 312 renders green
chair: [19, 3], // 190 chair
barrel: [23, 0], // 23 barrel (decor)
crate: [25, 0], // 25 crate (decor)
rug: [11, 16], // 923 rug
door: [37, 9], // 550 door
// Dungeon features drawn as real tiles instead of monospace glyphs.
entrance: [37, 9], // 550 — door
exit: [37, 9], // 550 — door
treasure: [42, 15], // 897 — item
torch: [50, 10] // 620 — rubble / prop
entrance: [37, 9], // 550 door
exit: [37, 9], // 550 door
treasure: [42, 15], // 897 item
torch: [50, 10] // 620 rubble / prop
}
},
// Second topdown pack — same sheet, a DUNGEON palette (stone floors, barrels/crates instead
// of the wood-interior furniture). A distinct look with zero new assets, and it's the
// "interchangeable dungeon" style (the tiled renderer's lighting/shadows are the built-in FX).
// Second topdown pack: same sheet, dungeon palette (stone floors, barrels/crates instead of
// the wood-interior furniture). A distinct look with zero new assets; the tiled renderer's
// lighting/shadows supply the FX.
'roguelike-dungeon': {
id: 'roguelike-dungeon',
label: 'Roguelike Dungeon',
tileset: { url: 'assets/kenney/roguelikeSheet.png', tile: 16, spacing: 1 },
fx: true,
tiles: {
floor: [6, 2], // 120 — stone floor
floor2: [13, 17], // 982 — plank accent
wall: [13, 12], // 697 — masonry
window: [42, 2], // 156 — window
floor: [6, 2], // 120 stone floor
floor2: [13, 17], // 982 plank accent
wall: [13, 12], // 697 masonry
window: [42, 2], // 156 window
bar: [23, 0], // barrels (a dungeon has no bar)
keg: [23, 0],
shelf: [25, 0], // crate
@@ -315,15 +314,15 @@
tile: { w: 84, h: 42, imageW: 92, imageH: 184 },
tiles: {
// Floors / ground
floor: 'assets/kenney/iso-dungeon/tiles/planks_S.png', // wood — tavern interior
floor2: 'assets/kenney/iso-dungeon/tiles/stone_S.png', // stone — dungeon
floor: 'assets/kenney/iso-dungeon/tiles/planks_S.png', // wood, tavern interior
floor2: 'assets/kenney/iso-dungeon/tiles/stone_S.png', // stone, dungeon
dirt: 'assets/kenney/iso-dungeon/tiles/dirt_S.png',
rug: 'assets/kenney/iso-dungeon/tiles/planks_S.png',
// Architecture (full-height tiles). Iso walls have a facing: a wall running along the
// grid-x axis needs the _S rotation, one running along grid-y needs the perpendicular
// _W rotation, and true corners get the corner tile. The renderer picks per-cell from
// neighbours, choosing `<kind>Y` for y-running segments (that's what fixes the "thin
// slabs" look on the top-left / bottom-right edges).
// neighbours, choosing `<kind>Y` for y-running segments; without that the top-left and
// bottom-right edges read as thin slabs.
wall: 'assets/kenney/iso-dungeon/tiles/stoneWall_S.png',
wallY: 'assets/kenney/iso-dungeon/tiles/stoneWall_W.png',
wallCorner: 'assets/kenney/iso-dungeon/tiles/stoneWallCorner_S.png',
@@ -332,15 +331,15 @@
door: 'assets/kenney/iso-dungeon/tiles/stoneWallDoorOpen_S.png',
doorY: 'assets/kenney/iso-dungeon/tiles/stoneWallDoorOpen_W.png',
archway: 'assets/kenney/iso-dungeon/tiles/stoneWallArchway_S.png',
// Floor variety — the renderer sprinkles these deterministically so the ground isn't a
// Floor variety: the renderer sprinkles these deterministically so the ground isn't a
// flat sea of identical planks.
floorAlt: 'assets/kenney/iso-dungeon/tiles/planksBroken_S.png',
floor2Alt: 'assets/kenney/iso-dungeon/tiles/stoneUneven_S.png',
stoneTile: 'assets/kenney/iso-dungeon/tiles/stoneTile_S.png',
column: 'assets/kenney/iso-dungeon/tiles/stoneColumnWood_S.png',
stairs: 'assets/kenney/iso-dungeon/tiles/stairs_S.png',
// Furniture props (drawn over a floor base) — each kind now has distinct art.
bar: 'assets/kenney/iso-dungeon/tiles/barrelsStacked_S.png', // stacked barrels = the bar counter
// Furniture props, drawn over a floor base; each kind has distinct art.
bar: 'assets/kenney/iso-dungeon/tiles/barrelsStacked_S.png', // stacked barrels as the bar counter
keg: 'assets/kenney/iso-dungeon/tiles/barrel_S.png',
barrel: 'assets/kenney/iso-dungeon/tiles/barrel_S.png',
table: 'assets/kenney/iso-dungeon/tiles/tableShortChairs_S.png', // real table + chairs
@@ -350,11 +349,11 @@
chest: 'assets/kenney/iso-dungeon/tiles/chestClosed_S.png',
fallback: 'assets/kenney/iso-dungeon/tiles/planks_S.png'
},
// The Kenney files named Male_0..Male_7 are directional renders of the same body,
// not different character classes. The customizer exposes one honest Iso body for now.
// These sprites are angled CLOCKWISE from NE: 0=NE, 2=SE, 4=SW, 6=NW (verified against live
// movement). In this iso projection a grid step moves visually up->NE, down->SW, left->NW,
// right->SE, so each facing uses the sprite pointing that way — face the way you move.
// The Kenney files named Male_0..Male_7 are directional renders of the same body, not
// different character classes, so the customizer exposes one Iso body. The sprites are
// angled clockwise from NE: 0=NE, 2=SE, 4=SW, 6=NW. In this iso projection a grid step
// moves visually up->NE, down->SW, left->NW, right->SE, so each facing uses the sprite
// pointing that way and the character faces its direction of travel.
character: isoMale(3), // idle faces roughly toward the camera (S)
directions: {
up: isoMale(0), // NE (up-right)
@@ -368,10 +367,10 @@
}
};
// Second iso pack — Kenney Isometric Medieval Town (a coherent, DIFFERENT environment). Strong on
// architecture (floor/walls/door/window/banner); no medieval furniture at this scale, so furniture
// kinds fall back to floor for now. Reuses the dungeon-pack characters. Its tiles are shorter
// (210x244) than the dungeon set, so its own tile geometry.
// Second iso pack: Kenney Isometric Medieval Town, a separate environment. Strong on
// architecture (floor/walls/door/window/banner); it has no medieval furniture at this scale, so
// furniture kinds fall back to floor. Reuses the dungeon-pack characters. Its tiles are shorter
// (210x244) than the dungeon set, hence its own tile geometry.
RK.isoMedievalAssets = {
pack: 'iso-medieval',
avatar: 'char-villager',
@@ -408,10 +407,10 @@
}
};
// Register the built-in RENDER packs in the pack registry (packRegistry.js) so iso/3D become
// multi-pack like topdown themes already are. Each maps to its catalog id; the active pack per
// projection is entitlement-gated + user-selectable. Adding a pack later = registerPack(...) +
// assets + a catalog row. Backward-compatible: one pack per projection resolves to these.
// Register the built-in render packs in the pack registry (packRegistry.js) so iso and 3D are
// multi-pack like topdown themes. Each maps to its catalog id; the active pack per projection
// is entitlement-gated and user-selectable. Adding a pack takes registerPack(...), assets, and
// a catalog row. With one pack per projection, resolution falls through to these.
if (RK.registerPack) {
RK.registerPack({ id: 'original', label: 'Original Tiles', projection: 'topdown', kind: 'tiles', assets: RK.THEMES['original'] });
RK.registerPack({ id: 'roguelike-interior', label: 'Roguelike Interior', projection: 'topdown', kind: 'tiles', assets: RK.THEMES['roguelike-interior'] });
+1 -1
View File
@@ -1,4 +1,4 @@
// TilesetAtlas — loads a tileset image and serves individual tiles to either a 2D canvas
// TilesetAtlas: loads a tileset image and serves individual tiles to either a 2D canvas
// (TileRenderer) or PixiJS (FancyRenderer). Source-agnostic: any pack's sheet loads through it.
(function (root) {
'use strict';
+1 -1
View File
@@ -91,7 +91,7 @@
// A player who never customized arrives as avatar 'default' (or an unknown id), which is not
// a char/skin/model and would fall to the grey circle. On the TAVERN canvas path, coerce it
// to a real Kenney character so nobody is a grey dot in a room of people. But NOT on
// 'legacy-rot' (the single-player dungeon) — there RenderEngine falls back to the original @
// 'legacy-rot' (the single-player dungeon): there RenderEngine falls back to the original @
// hero TILE, which is what an un-customized player expects (grey circle was a canvas-only
// problem). iso/3d keep their own fallbacks below.
if (ap && projection !== 'iso' && projection !== '3d' && projection !== 'legacy-rot') {
+1 -1
View File
@@ -28,7 +28,7 @@
var frame = Math.floor((now || 0) / FRAME_MS) % FRAMES;
var sx = frame * FW;
// The cat occupies only ~40% of its 50x50 frame (lots of transparent padding), so scale
// the frame well past the cell and centre it — the visible cat then reads about tile-sized.
// the frame well past the cell and centre it; the visible cat then reads about tile-sized.
var size = cell * 2.7;
var dx = e.x * cell + (cell - size) / 2;
var dy = e.y * cell + (cell - size) / 2 + cell * 0.28; // centred, nudged down onto the tile
+12 -15
View File
@@ -1,9 +1,7 @@
// ChainAmbience — the live chain, drifting around the edges of a stage.
// ChainAmbience: the live chain, drifting around the edges of a stage.
//
// The Tavern sits on top of a real blockchain, and the game's whole clock is "when does the next
// block land". This makes that visible without putting a dashboard on screen: fragments of the top
// block hash fade in around the border and drift away, a corner readout tracks the height, and a
// new block sends a ripple around the frame.
// Fragments of the top block hash fade in around the border and drift away, a corner readout
// tracks the height, and a new block sends a ripple around the frame.
//
// Purely decorative. It reads the public `blockheight` broadcast and never influences gameplay, so
// a missing or stale tip just means fewer motes.
@@ -85,11 +83,10 @@
var self = this;
this.timer = root.setInterval(function () { self._spawn(); }, this.spawnMs);
// A hidden tab pauses CSS animations, so `animationend` never fires and nothing is ever
// removed — while the spawn interval keeps ticking. Left alone, a tavern tab parked in the
// background accrues motes indefinitely and then plays a pile of stale ones all at once when
// the player comes back. Spawning is skipped while hidden (below) and the backlog is dropped
// here; these are decorations, so discarding them costs nothing.
// A hidden tab pauses CSS animations, so `animationend` never fires and motes are never
// removed. Spawning is skipped while hidden and any backlog is dropped here, otherwise a
// backgrounded tab accrues motes indefinitely and replays them all at once on return.
// These are decorations, so discarding them costs nothing.
this._onVisibility = function () {
if (!self.el || !self.doc.hidden) return;
self._clearMotes();
@@ -121,9 +118,9 @@
ChainAmbience.prototype._spawn = function (burst) {
if (!this.el || reducedMotion()) return;
if (this.doc.hidden) return; // paused animations would never clean themselves up
// Count the DOM, not a counter: a missed animationend must not permanently inflate the tally
// and silently stop all further spawning.
if (this.doc.hidden) return; // paused animations never clean themselves up
// Count the DOM, not `this.motes`: a missed animationend would permanently inflate the
// tally and silently stop all further spawning.
if (!burst && this.el.querySelectorAll('.rk-cm').length >= this.maxMotes) return;
var text = this._fragment();
if (!text) return;
@@ -132,8 +129,8 @@
m.className = 'rk-cm rk-drift';
m.textContent = text;
// Hug the border: pick an edge, then a position along it. The middle of the stage is where
// the game is — the chain lives in the margins.
// Hug the border: pick an edge, then a position along it. The middle of the stage belongs
// to the game, so the chain lives in the margins.
var edge = Math.floor(Math.random() * 4);
var along = 6 + Math.random() * 84;
var dx = 0, dy = 0;
+2 -2
View File
@@ -725,7 +725,7 @@
}
// Sprite tinting (cloth / skin / hair / gear colour) is disabled for the top-down
// Tiles view — characters render in native Kenney art. Only equipment PIECE selection
// Tiles view: characters render in native Kenney art. Only equipment PIECE selection
// remains here; the '@' colour for ASCII mode is still pickable in the ascii/colour
// branch above.
sectionTitle('Equipment', editSection);
@@ -791,7 +791,7 @@
}
function buildAvatarGrid() {
// Don't auto-switch the avatar when the render mode changes — only an explicit
// Don't auto-switch the avatar when the render mode changes; only an explicit
// click on a different avatar card should change the saved identity. If the current
// avatar isn't native to this projection, it stays selected (the resolver handles
// fallback rendering) so browsing render modes never silently mutates the identity.
+1 -1
View File
@@ -229,7 +229,7 @@
// Sprite recoloring (skin / hair / cloth-base / gear tinting) is intentionally disabled:
// characters and equipment render in their native Kenney art. Returning null makes every
// caller (drawCharTileCanvas, charTileTexture) fall through to the untinted sprite. The
// ASCII '@' colour is unaffected — it uses colors.base via avatarVisuals.tintColorFor,
// ASCII '@' colour is unaffected: it uses colors.base via avatarVisuals.tintColorFor,
// a separate path. To restore tinting, delete this early return.
return null;
var a = RK.charAtlas();
+1 -1
View File
@@ -1,4 +1,4 @@
// Designed room — loads an imported Tiled room (from tmx_import.py): layered tile-index grids
// Designed room: loads an imported Tiled room (from tmx_import.py): layered tile-index grids
// + a tileset, and draws the layers (back-to-front) beneath the avatars. The server uses the
// same room's walkability/dims for collision, so visuals and movement match.
(function (root) {
+3 -3
View File
@@ -1,5 +1,5 @@
// FancyRenderer — WebGL tier via PixiJS (v7). Beyond flat shapes: a real blurred bloom on
// entities, warm flickering lights along the bar, drifting dust motes, and a vignette — all
// FancyRenderer: WebGL tier via PixiJS (v7). Beyond flat shapes: a real blurred bloom on
// entities, warm flickering lights along the bar, drifting dust motes, and a vignette, all
// programmatic (no art assets). Requires a global PIXI (loaded from CDN, with @pixi/unsafe-eval
// so shaders compile under a strict CSP); the factory falls back to tiled if PIXI is missing.
(function (root) {
@@ -77,7 +77,7 @@
FancyRenderer.prototype._buildTiles = function (scene) {
this.tileLayer.removeChildren();
var cell = this.cell;
// A designed room is loaded — draw its layered tiles as sprites from the room atlas.
// A designed room is loaded: draw its layered tiles as sprites from the room atlas.
if (window.RK && RK.roomReady && RK.roomReady()) {
var d = RK.activeRoom.desc, a = RK.activeRoom.atlas;
for (var li = 0; li < d.layerOrder.length; li++) {
+2 -2
View File
@@ -1,8 +1,8 @@
// fxLayer.js — the shared "juice" engine (RK.fx). Pure-canvas animated FX (no WebGL, no shaders,
// fxLayer.js: the shared "juice" engine (RK.fx). Pure-canvas animated FX (no WebGL, no shaders,
// CSP-safe) used by BOTH the top-down tiled renderer and the iso renderer so a scene lights up the
// same way in either projection: dancing torch/hearth flame + warm glow, and pulsing hazard tiles
// (lava / poison / spikes) for the dungeon. Everything is a function of `now` (ms) so callers just
// keep a RAF loop alive and pass the clock — no per-particle state to thread through.
// keep a RAF loop alive and pass the clock: no per-particle state to thread through.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
+59 -63
View File
@@ -1,4 +1,4 @@
// IsoRenderer — canvas isometric projection using Kenney's Isometric Miniature Dungeon pack.
// IsoRenderer: canvas isometric projection using Kenney's Isometric Miniature Dungeon pack.
// It draws the same Scene as the top-down renderers, preserving the shared Room contract.
(function (root) {
'use strict';
@@ -75,7 +75,8 @@
};
// Map a dungeon FEATURE entity (entrance/exit/treasure/item) to a pack tile: stairs for the
// entrance/exit, a chest for treasure/items. Null if the pack has no fitting tile (→ glyph).
// entrance/exit, a chest for treasure/items. Null if the pack has no fitting tile, which falls
// back to a glyph.
IsoRenderer.prototype._featureTileUrl = function (e) {
var tiles = this.assets.tiles || {};
var c = e.char;
@@ -84,8 +85,8 @@
return null;
};
// A stroked iso diamond outline — used to flag the floor cells the player can actually step to,
// so ambiguous wall gaps are never mistaken for openings.
// Stroked iso diamond outline, used to flag the floor cells the player can actually step to so
// ambiguous wall gaps are never mistaken for openings.
IsoRenderer.prototype._diamondOutline = function (cx, cy, color) {
var ctx = this.ctx, hw = this.tileW / 2, hh = this.tileH / 2;
ctx.save();
@@ -109,8 +110,8 @@
ctx.restore();
};
// A flat iso diamond in the legend colour — the placeholder a tile draws while its pack image
// loads (or if an image is missing), so the view shows the dungeon shape instead of going black.
// Flat iso diamond in the legend colour: the placeholder a tile draws while its pack image loads
// (or if an image is missing), so the view shows the dungeon shape instead of going black.
IsoRenderer.prototype._diamond = function (cx, cy, color) {
var ctx = this.ctx, hw = this.tileW / 2, hh = this.tileH / 2;
ctx.beginPath();
@@ -132,13 +133,13 @@
ctx.restore();
};
// Warm pool of light cast onto the scene by a torch / the player's lantern / a beacon. Drawn
// additively after the tiles so it lights the floor, the props AND the characters standing in
// Warm pool of light cast onto the scene by a torch, the player's lantern or a beacon. Drawn
// additively after the tiles so it lights the floor, the props and the characters standing in
// it, which is what separates a lit room from a flat sprite collage.
IsoRenderer.prototype._lightPool = function (cx, cy, radius, inner, outer) {
var ctx = this.ctx;
// A non-finite emitter would throw out of createRadialGradient and abandon the frame
// half-drawn. Lighting is decoration — skip the bad pool, keep the dungeon.
// A non-finite emitter throws out of createRadialGradient and abandons the frame half-drawn.
// Lighting is decoration, so skip the bad pool and keep the dungeon.
if (!isFinite(cx) || !isFinite(cy) || !isFinite(radius) || radius <= 0) return;
var g = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius);
g.addColorStop(0, inner);
@@ -177,7 +178,7 @@
ctx.restore();
};
// Crevice darkening on floor cells that touch a wall — a cheap ambient-occlusion cue. The
// Crevice darkening on floor cells that touch a wall: a cheap ambient-occlusion cue. The
// gradient is clear in the middle of the cell and dark at its rim, so tiles tucked into a corner
// sit in shadow instead of looking like stickers laid on top of the ground.
IsoRenderer.prototype._wallAO = function (cx, cy, strength) {
@@ -195,8 +196,8 @@
ctx.restore();
};
// Warm radial vignette — an ambient tavern glow that darkens the edges and lifts the centre,
// the "juice" that makes the flat canvas feel lit rather than pasted.
// Warm radial vignette: an ambient tavern glow that darkens the edges and lifts the centre, so
// the flat canvas feels lit rather than pasted.
IsoRenderer.prototype._vignette = function () {
var ctx = this.ctx, w = this.canvas.width, h = this.canvas.height;
var g = ctx.createRadialGradient(w / 2, h * 0.46, Math.min(w, h) * 0.18,
@@ -265,12 +266,10 @@
return cv;
};
// Darkened copy of a tile image, cached at quantized levels.
//
// Fog-of-war used to dim tiles with globalAlpha, which made remembered walls TRANSLUCENT — you
// could see the tiles behind them, so the dungeon read as a haze of overlapping ghosts instead
// of solid stone in the dark. Multiplying the sprite's own pixels toward black keeps every tile
// opaque and just unlit, which is what "you remember this room, it isn't lit" should look like.
// Darkened copy of a tile image, cached at quantized levels. Fog-of-war multiplies the sprite's
// own pixels toward black rather than dimming with globalAlpha: alpha makes remembered walls
// translucent, so the tiles behind them show through and the dungeon reads as a haze of
// overlapping ghosts. Shading keeps every tile opaque and merely unlit.
IsoRenderer.prototype._shadedImage = function (img, level) {
if (!img) return img;
var step = Math.max(0, Math.min(5, Math.round(level * 5)));
@@ -284,7 +283,7 @@
var ctx = cv.getContext('2d');
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = 'source-atop';
// A touch of blue in the shadow rather than flat black — unlit stone reads cold.
// A touch of blue in the shadow rather than flat black, so unlit stone reads cold.
ctx.fillStyle = 'rgba(6,10,20,' + (1 - step / 5).toFixed(3) + ')';
ctx.fillRect(0, 0, cv.width, cv.height);
ctx.globalCompositeOperation = 'source-over';
@@ -307,7 +306,7 @@
return tiles[kind] || tiles.fallback || tiles.floor;
};
// Deterministic per-cell hash (no RNG — stable across frames/reloads).
// Deterministic per-cell hash: no RNG, so it is stable across frames and reloads.
function cellHash(x, y) {
var h = (x * 73856093) ^ (y * 19349663);
h = (h ^ (h >>> 13)) >>> 0;
@@ -324,8 +323,8 @@
// Iso walls have a facing. A segment running along grid-x uses the base (_S) rotation; one
// running along grid-y uses the perpendicular (`<kind>Y`, _W) rotation; a true corner (both
// axes present) uses the corner tile. This is what makes enclosing walls read as continuous
// faces instead of thin disconnected slabs on the y-running edges.
// axes present) uses the corner tile. Without the per-axis rotation, enclosing walls read as
// thin disconnected slabs on the y-running edges instead of continuous faces.
IsoRenderer.prototype._wallVariant = function (scene, x, y, kind) {
var tiles = this.assets.tiles || {};
var xRun = this._isWall(scene, x - 1, y) || this._isWall(scene, x + 1, y);
@@ -361,9 +360,8 @@
var key = e.id || 'anon';
var st = this.last[key] || (this.last[key] = { x: e.x, y: e.y, t: 0, facing: 'down' });
if (st.x !== e.x || st.y !== e.y) {
// Infer facing from the actual movement delta — the SP game doesn't send player.facing
// (only the tavern does), so without this the character always faced 'down' (SW) no matter
// which way it moved. Explicit e.facing (tavern) still wins below.
// Facing is inferred from the movement delta because the SP game does not send
// player.facing; only the tavern does. Explicit e.facing (tavern) wins below.
var ddx = e.x - st.x, ddy = e.y - st.y;
if (Math.abs(ddx) >= Math.abs(ddy)) st.facing = ddx > 0 ? 'right' : 'left';
else st.facing = ddy > 0 ? 'down' : 'up';
@@ -386,10 +384,10 @@
var originY = margin + this.imageH;
var wantW = Math.ceil((scene.cols + scene.rows) * this.tileW / 2 + margin * 2 + this.tileW * 2);
var wantH = Math.ceil((scene.cols + scene.rows) * this.tileH / 2 + this.imageH + margin * 2);
// Only ASSIGN width/height when they actually change. Assigning either one reallocates and
// Assign width/height only when they actually change. Assigning either one reallocates and
// clears the whole backing buffer, and this renderer re-runs every animation frame (the
// walkable pulse and the flames keep `_animating` set) — so the old unconditional assignment
// was throwing away and re-allocating a multi-megapixel canvas 60 times a second.
// walkable pulse and the flames keep `_animating` set), so an unconditional assignment
// re-allocates a multi-megapixel canvas 60 times a second.
if (this.canvas.width !== wantW || this.canvas.height !== wantH) {
this.canvas.width = wantW;
this.canvas.height = wantH;
@@ -415,8 +413,8 @@
if (PROP[kind]) {
items.push({ type: 'prop', kind: kind, x: x, y: y, sx: p.x, sy: p.y, depth: x + y + 0.25 });
}
// Fire fixtures (torch/hearth) & hazard tiles (lava/poison/spikes): a floor tile is
// the base (drawn above via fallback); RK.fx paints the animated flame / pulse.
// Fire fixtures (torch/hearth) and hazard tiles (lava/poison/spikes): a floor tile is
// the base, drawn above via fallback; RK.fx paints the animated flame or pulse.
if (def && (def.fx === 'fire' || def.hazard)) {
items.push({ type: 'fx', def: def, x: x, y: y, sx: p.x, sy: p.y, depth: x + y + 0.3 });
}
@@ -426,21 +424,21 @@
var e = scene.entities[i];
p = this._project(e.x, e.y, originX, originY);
items.push({ type: 'entity', e: e, sx: p.x, sy: p.y, depth: e.x + e.y + 0.55 });
// Sticky camera target (keep last if the player is momentarily absent). Multiplayer
// scenes explicitly mark one racer as cameraTarget; never let a later rival steal it.
// Sticky camera target: the last value is kept if the player is momentarily absent.
// Multiplayer scenes mark one racer as cameraTarget so a later rival cannot steal it.
if (e.you || e.cameraTarget) { this.focusPoint = { x: p.x, y: p.y + this.tileH }; this._plx = e.x; this._ply = e.y; }
}
items.sort(function (a, b) { return a.depth === b.depth ? (a.y || 0) - (b.y || 0) : a.depth - b.depth; });
var now = Date.now();
// Light emitters collected while drawing, applied additively in one pass afterwards so the
// pools land on the floor, the props AND the characters standing in them.
// pools land on the floor, the props and the characters standing in them.
var lights = [];
for (i = 0; i < items.length; i++) {
var it = items[i];
if (it.type === 'tile') {
// FOG OF WAR: never render unexplored cells. Without this they fell back to the floor
// tile (`_tileUrl('dark')` → tiles.floor) and revealed the ENTIRE map from move 0.
// Fog of war: unexplored cells are never rendered. They would otherwise fall back to
// the floor tile (`_tileUrl('dark')` resolves to tiles.floor) and reveal the whole map.
if (it.kind === 'dark') continue;
var tileKind = PROP[it.kind] ? 'floor' : it.kind;
if (WALLISH[tileKind]) tileKind = this._wallVariant(scene, it.x, it.y, tileKind);
@@ -453,11 +451,11 @@
it.x >= this._plx && it.y >= this._ply &&
(it.x + it.y) > (this._plx + this._ply) &&
((it.x - this._plx) + (it.y - this._ply)) <= 3;
// Fog fade: dim explored-but-distant tiles toward the (near-black) background so the
// remembered area melts into the dark with distance — parity with the 2D modes.
// Fog fade: dim explored-but-distant tiles toward the near-black background so the
// remembered area melts into the dark with distance, matching the 2D modes.
var lb = (scene.lightGrid && scene.lightGrid[it.y] && scene.lightGrid[it.y][it.x] != null) ? scene.lightGrid[it.y][it.x] : 1;
// Cutaway walls stay ALPHA-faded (you need to see the floor through them). Everything
// else is shaded opaque, so distant stone is dark stone rather than a ghost.
// Cutaway walls stay alpha-faded so the floor shows through them. Everything else is
// shaded opaque, so distant stone is dark stone rather than a ghost.
ctx.globalAlpha = cut ? 0.28 : 1;
if (rec && rec.ready) {
var img = cut ? rec.img : this._shadedImage(rec.img, Math.max(0.16, lb));
@@ -466,11 +464,11 @@
ctx.globalAlpha = cut ? 0.28 : Math.max(0.16, lb);
this._diamond(it.sx, it.sy + this.tileH * 0.5, (legend[it.kind] && legend[it.kind].color) || '#3a4048');
}
// Walkable-floor pip: mark every visible floor cell with a soft dot so the WALKABLE
// ground is explicit everywhere. A dark gap with no pip is unambiguously NOT floor —
// that's what stops iso wall-gaps/voids from reading as holes you can walk into.
// Walkable-floor pip: every visible floor cell gets a soft dot so walkable ground is
// explicit everywhere. A dark gap with no pip is unambiguously not floor, which stops
// iso wall gaps and voids from reading as holes you can walk into.
if (it.kind === 'floor' || it.kind === 'floor2') {
// Crevice shadow where this floor cell abuts stone. Cheap AO — the more walls
// Crevice shadow where this floor cell abuts stone. Cheap AO: the more walls
// around it, the deeper the cell sits in shadow.
var adj = (this._isWall(scene, it.x - 1, it.y) ? 1 : 0) + (this._isWall(scene, it.x + 1, it.y) ? 1 : 0) +
(this._isWall(scene, it.x, it.y - 1) ? 1 : 0) + (this._isWall(scene, it.x, it.y + 1) ? 1 : 0);
@@ -513,10 +511,9 @@
});
}
} else if (it.type === 'entity') {
// Dungeon FEATURES/ITEMS (entrance/exit/treasure/items) are tiles/glyphs, NOT avatars.
// The iso renderer is shared with the tavern (where every entity is an avatar); without
// this branch the entrance was drawn as a male character — the "copy of the player at
// the start" the map origin showed.
// Dungeon features and items (entrance/exit/treasure/items) draw as tiles or glyphs,
// not avatars. The iso renderer is shared with the tavern, where every entity is an
// avatar, so without this branch the entrance draws as a character sprite.
if (it.e.kind === 'feature' || it.e.kind === 'item') {
var furl = this._featureTileUrl(it.e);
var frec = furl && this._load(furl);
@@ -524,14 +521,14 @@
else this._glyph(it.sx, it.sy + this.tileH * 0.4, it.e.char || '?', it.e.color || '#fff');
// Objectives beacon. Stairs and treasure are the only two things in the dungeon
// worth crossing a room for, so they get a slow breathing glow in their own
// colour — findable from across a dark hall without leaking the layout.
// colour: findable from across a dark hall without leaking the layout.
var beaconRGB = it.e.char === '<' ? '63,185,80'
: it.e.char === '>' ? '210,153,34'
: it.e.char && it.e.char.charAt(0) === '$' ? '251,191,36' : null;
if (beaconRGB) {
this._animating = true;
// NB: entity items carry the cell on `it.e`, not `it.x` (that is only set on
// tile items) — reading it.x here produced a NaN radius and threw.
// Entity items carry the cell on `it.e`; `it.x` is set only on tile items, so
// reading it here would give a NaN radius.
var breathe = 0.55 + Math.sin(now / 620 + it.e.x) * 0.45;
lights.push({
x: it.sx, y: it.sy + this.tileH, r: this.tileW * (1.1 + breathe * 0.35),
@@ -546,8 +543,8 @@
rec = this._load(frame && frame.url);
if (rec && rec.ready) {
var ch = frame.character || this.assets.character || {};
// Monsters use the same character art — tint them RED so they don't read as a
// second player following you around.
// Monsters use the same character art, so they are tinted red to avoid reading as
// a second player following you around.
var tint = it.e.kind === 'monster' ? '#f85149' : this._skinTintFor(frame.visual);
this._drawSpriteImage(this._tintedImage(rec.img, tint), it.sx, it.sy + this.tileH * 0.95, ch.imageH || 92);
} else {
@@ -573,9 +570,8 @@
}
// Walkability affordance: the iso wall tiles leave ambiguous gaps that read as doorways, so
// flag the floor cells the player can actually step to (orthogonally adjacent, walkable +
// explored) with a soft pulsing outline — a reliable "you can go here" cue independent of how
// the walls render.
// the floor cells the player can actually step to (orthogonally adjacent, walkable and
// explored) get a soft pulsing outline. That cue holds regardless of how the walls render.
if (this._plx != null) {
var pulse = 0.30 + Math.sin(now / 320) * 0.18;
var nbrs = [[0, -1], [0, 1], [-1, 0], [1, 0]];
@@ -605,9 +601,9 @@
var L = lights[lg];
this._lightPool(L.x, L.y, L.r, L.inner, L.outer);
}
// Colour-temperature separation: everything the player can currently SEE is warm torchlight;
// the explored-but-remembered parts get a cold blue wash. Alpha alone made memory read as
// "far away"; the temperature shift makes it read as "remembered", which is what it is.
// Colour-temperature separation: everything the player can currently see is warm torchlight,
// while explored-but-remembered parts get a cold blue wash. Alpha alone reads as "far away";
// the temperature shift reads as "remembered".
this._memoryWash(scene, originX, originY);
this._vignette();
@@ -621,16 +617,16 @@
var ctx = this.ctx, hw = this.tileW / 2, hh = this.tileH / 2;
ctx.save();
ctx.globalCompositeOperation = 'source-atop';
// A DARK blue. A mid-tone blue at 20% actually lifted the already-darkened memory tiles
// brighter than the torchlit centre, inverting the whole depth hierarchy — remembered rooms
// glowed and the room you were standing in receded.
// The wash must be a dark blue. A mid-tone blue lifts the already-darkened memory tiles
// brighter than the torchlit centre, inverting the depth hierarchy so remembered rooms glow
// and the room the player stands in recedes.
ctx.fillStyle = 'rgba(16,28,52,1)';
for (var y = 0; y < scene.rows; y++) {
for (var x = 0; x < scene.cols; x++) {
var kind = scene.grid[y] && scene.grid[y][x];
if (!kind || kind === 'dark') continue;
var lb = (light[y] && light[y][x] != null) ? light[y][x] : 1;
if (lb >= 0.3) continue; // currently lit — leave it warm
if (lb >= 0.3) continue; // currently lit, so leave it warm
var p = this._project(x, y, originX, originY), cy = p.y + hh;
ctx.globalAlpha = 0.45 * (1 - lb / 0.3);
ctx.beginPath();
+2 -2
View File
@@ -1,8 +1,8 @@
// Pack registry — the engine behind "add more 2D tilesets / iso packs / 3D skins as products".
// Pack registry: the engine behind "add more 2D tilesets / iso packs / 3D skins as products".
//
// A PACK is a rich, self-contained render environment for a projection (topdown | iso | 3d). Because
// every scene (tavern OR dungeon) is kind-based (floor/wall/table/torch/monster…), the SAME pack
// renders both — packs are interchangeable across town and dungeon. Each pack maps 1:1 to a catalog
// renders both; packs are interchangeable across town and dungeon. Each pack maps 1:1 to a catalog
// entry (id/tier/threshold), so it's a monetizable product gated by entitlements.
//
// This module makes packs MULTI (like RK.THEMES already is for topdown) and adds active-pack
+3 -3
View File
@@ -18,11 +18,11 @@
return true;
};
// Render tiers. `premium` marks modes intended to be unlocked with credits — a cosmetic
// Render tiers. `premium` marks modes intended to be unlocked with credits: a cosmetic
// entitlement gated by Operator Policy, the same pattern as avatar unlocks. NOTE: rendering
// is client-side, so this is a soft/honour gate for cosmetics, not a hard security boundary.
// Modes are TECHNIQUES (how a scene is drawn). Packs are the SETS/styles within a projection
// (chosen via the pack picker) — so "Fancy" (tiles + FX) is a topdown PACK, not a mode. A
// (chosen via the pack picker), so "Fancy" (tiles + FX) is a topdown PACK, not a mode. A
// premium mode unlocks once the user has ANY unlocked pack for its projection.
RK.RENDER_MODES = [
{ id: 'tiles', label: 'Tiled', premium: false, projection: 'topdown' },
@@ -33,7 +33,7 @@
RK.entitlements = RK.entitlements || { premium: false, level: 'free', packs: {} };
// Per-session QA bypass for premium render-mode gating (Fancy/Iso/3D). Default OFF. A tester
// opts IN for their own browser only via ?unlock=1 (persisted) — nobody else is affected:
// opts IN for their own browser only via ?unlock=1 (persisted); nobody else is affected:
// ?unlock=1 -> on (sticky) ?unlock=0 -> off
RK.RENDER_MODE_TEST_UNLOCKS = false;
try {
+27 -27
View File
@@ -9,21 +9,21 @@
// Tile kinds and how each renderer treats them (glyph for ASCII, colour for tiled/fancy).
// `over` names the ground tile an object sits on, so the renderer composites the object over it
// (its transparent areas show the floor/wall, not the dark canvas). Ground tiles (wall/floor/rug)
// have no `over` — they fill the cell.
// have no `over`; they fill the cell.
var TAVERN_LEGEND = {
wall: { char: '#', color: '#3a3f4b', solid: true },
window: { char: 'W', color: '#4a6a8a', solid: true, over: 'wall' },
floor: { char: '·', color: '#6b4d33', solid: false }, // warm wood, not the old dark green
floor: { char: '·', color: '#6b4d33', solid: false }, // warm wood
rug: { char: 'r', color: '#7a3b39', solid: false, over: 'floor' },
bar: { char: '=', color: '#6a4a2a', solid: true, over: 'floor' },
keg: { char: 'k', color: '#5a4028', solid: true, over: 'floor' },
shelf: { char: 'h', color: '#4a3a28', solid: true, over: 'floor' },
table: { char: 'T', color: '#6a4a2a', solid: true, over: 'floor' },
chair: { char: 'c', color: '#5a4028', solid: false, over: 'floor' }, // walkable — stand on it to "sit"
chair: { char: 'c', color: '#5a4028', solid: false, over: 'floor' }, // walkable: stand on it to "sit"
barrel: { char: 'B', color: '#5a4028', solid: true, over: 'floor' },
crate: { char: 'C', color: '#7a5a38', solid: true, over: 'floor' },
door: { char: 'D', color: '#3fb950', solid: false, over: 'floor' },
// Fire fixtures — the base tile is floor; RK.fx paints the animated flame + glow on top.
// Fire fixtures: the base tile is floor; RK.fx paints the animated flame + glow on top.
torch: { char: 'i', color: '#d29922', solid: true, over: 'floor', fx: 'fire', fxScale: 0.34 },
hearth: { char: 'F', color: '#e0742a', solid: true, over: 'floor', fx: 'fire', fxScale: 0.7 }
};
@@ -95,7 +95,7 @@
// ---- Dungeon game-state adapter ------------------------------------------------
// Converts a game state (from the server's game_start/game_update/spectator_update) into a
// renderer-agnostic Scene, so the render kit can draw the dungeon just like the tavern.
// This is the bridge for milestone R1 (main game → render kit) and T2b (tavern spectator).
// Used by both the main game and the tavern spectator view.
var DUNGEON_LEGEND = {
wall: { char: '#', color: '#2a2f38', solid: true },
@@ -107,8 +107,8 @@
// The generator only places torches on WALL cells adjacent to floor, so the fixture is
// wall-mounted: base on `wall`, draw the torch sprite over it, then RK.fx animates the flame.
torch: { char: 'i', color: '#d29922', solid: false, over: 'wall', fx: 'fire', fxScale: 0.34 },
// Hazard zones. The base tile stays walkable/ground; RK.fx paints the pulsing overlay. These
// render as soon as the dungeon generator emits their chars (L/P/^) in the tile stream.
// Hazard zones. The base tile stays walkable/ground; RK.fx paints the pulsing overlay.
// Keyed off the dungeon generator's chars (L/P/^) in the tile stream.
lava: { char: '≈', color: '#7a2a0e', solid: false, hazard: 'lava' },
poison: { char: '≈', color: '#1c4a24', solid: false, hazard: 'poison' },
spikes: { char: '^', color: '#3a3f48', solid: false, hazard: 'spikes' },
@@ -130,7 +130,7 @@ function dungeonTileKind(ch) {
return 'floor';
}
// Grid dimensions from array grids OR sparse {y:{x:v}} maps (the single-player client uses the
// Grid dimensions from array grids or sparse {y:{x:v}} maps (the single-player client uses the
// latter). Returns the max seen index + 1 across every supplied map.
function maxDims(maps) {
var rows = 0, cols = 0;
@@ -156,8 +156,8 @@ function maxDims(maps) {
}
function normalizeGameStateOpts(opts) {
// Older multiplayer callers passed a socket id directly. Keep that path working while the
// public API moves to an options object (`{ viewerId, playerAppearance, cryptoType }`).
// Accepts either a bare socket id (multiplayer callers) or an options object
// (`{ viewerId, playerAppearance, cryptoType }`).
if (typeof opts === 'string') return { viewerId: opts };
return (opts && typeof opts === 'object') ? opts : {};
}
@@ -188,7 +188,7 @@ function pickCameraPlayer(players, state, opts) {
p = players[i];
if (p && state.winnerId && p.id === state.winnerId) return p;
}
// Spectators follow a live contender by default, then gracefully fall back to the first racer.
// Spectators follow a live contender by default, then fall back to the first racer.
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && p.alive !== false && !p.finished) return p;
@@ -219,7 +219,7 @@ function sceneFromGameState(state, opts) {
var visible = state.visibleTiles || {};
var explored = state.exploredTiles || {};
var lighting = state.lighting || {};
// Array grids expose .length; the SP client uses sparse {y:{x:v}} maps — fall back to the max
// Array grids expose .length; the SP client uses sparse {y:{x:v}} maps, so fall back to the max
// seen index. Explicit dungeonRows/Cols (server) always win.
var dims = maxDims([visible, explored, state.map]);
var rows = state.dungeonRows || visible.length || dims.rows;
@@ -228,8 +228,8 @@ function sceneFromGameState(state, opts) {
var matchPlayers = Array.isArray(state.players) ? state.players : [];
var cameraPlayer = pickCameraPlayer(matchPlayers, state, opts);
// Player cell — explored MEMORY fades to black with distance from here (see below). Multiplayer
// states use `players[]`, while the original single-player protocol uses singular `player`.
// Player cell. Explored memory fades to black with distance from here. Multiplayer states use
// `players[]`; the single-player protocol uses singular `player`.
var _pl = state.player || cameraPlayer || {};
var _plx = typeof _pl.x === 'number' ? _pl.x : (cols / 2);
var _ply = typeof _pl.y === 'number' ? _pl.y : (rows / 2);
@@ -256,9 +256,9 @@ function sceneFromGameState(state, opts) {
var la = (lighting[y] && lighting[y][x]) || 0;
lrow.push(Math.max(0.15, 1 - Math.min(la, 0.8)));
} else {
// Explored MEMORY (seen before, not currently visible): dim, and fading toward black
// with distance from the player, so the remembered area melts into the dark instead
// of forming a hard-edged grey block that outlines the map's shape/edge (a FoW leak).
// Explored memory (seen before, not currently visible): dim, fading toward black with
// distance from the player. A flat dim value would form a hard-edged grey block that
// outlines the map's shape, leaking information through the fog of war.
row.push(dungeonTileKind(ch));
var _dx = x - _plx, _dy = y - _ply;
lrow.push(Math.max(0, 0.26 - Math.sqrt(_dx * _dx + _dy * _dy) * 0.019));
@@ -272,11 +272,11 @@ function sceneFromGameState(state, opts) {
// Fog of war: a cell is `seen` once explored (grid isn't 'dark'); `inView` only while currently
// visible. Features (exit/treasure/entrance) show once discovered; the monster only shows while
// in view — otherwise the exit stairs leak through the fog before you've found them.
// in view, so its position does not leak through the fog.
function seen(x, y) { return !!(grid[y] && grid[y][x] && grid[y][x] !== 'dark'); }
function inView(x, y) { return !!(visible[y] && visible[y][x] !== undefined); }
// Entrance / exit / treasure as entities (so they layer above tiles) — only once explored.
// Entrance / exit / treasure as entities (so they layer above tiles), only once explored.
// Solo uses `[x,y]`; match state uses `{x,y}` for treasure, so accept both point shapes.
var entrance = pointOf(state.entrance);
var exit = pointOf(state.exit);
@@ -292,7 +292,7 @@ function sceneFromGameState(state, opts) {
entities.push({ id: 'treasure', x: treasure.x, y: treasure.y, kind: 'feature', char: tChar, color: '#fbbf24', label: null });
}
// Items — only once explored.
// Items, only once explored.
if (state.items) {
for (var key in state.items) {
if (state.items.hasOwnProperty(key)) {
@@ -304,7 +304,7 @@ function sceneFromGameState(state, opts) {
}
}
// Monster — only while it's actually in view.
// Monster, only while it is in view.
if (state.monster && inView(state.monster.x, state.monster.y)) {
entities.push({
id: 'monster', x: state.monster.x, y: state.monster.y,
@@ -331,13 +331,13 @@ function sceneFromGameState(state, opts) {
hasTreasure: !!rp.hasTreasure, placement: rp.placement == null ? null : rp.placement
});
}
// Original single-player protocol.
// Single-player protocol.
} else if (state.player) {
var playerEntity = {
id: 'player', x: state.player.x, y: state.player.y,
kind: 'player', char: '@', color: '#9aa4b2',
// No bogus default: the SP server doesn't send facing, so leave it null and let the iso/3D
// renderers INFER facing from movement. A hardcoded 'down' made them always face down/SW.
// The SP server does not send facing. Leaving it null lets the iso/3D renderers infer
// facing from movement; any hardcoded default would pin the sprite to one direction.
facing: state.player.facing || null, label: null,
you: !state.isSpectating, cameraTarget: true
};
@@ -369,9 +369,9 @@ function sceneFromGameState(state, opts) {
root.RK = root.RK || {};
root.RK.scene = api;
// Convenience aliases on RK directly — several callers (matchClient, tavern spectator, the SP
// render bridge) reference RK.sceneFromGameState / RK.sceneFromTavern; without these they were
// silently undefined (guarded → no-op). Expose them so those paths actually render.
// Convenience aliases on RK directly. matchClient, the tavern spectator and the SP render bridge
// reference RK.sceneFromGameState / RK.sceneFromTavern; without these they are undefined and
// those guarded call sites silently render nothing.
root.RK.sceneFromGameState = root.RK.sceneFromGameState || sceneFromGameState;
if (api.sceneFromTavern) root.RK.sceneFromTavern = root.RK.sceneFromTavern || api.sceneFromTavern;
if (typeof module !== 'undefined' && module.exports) module.exports = api;
+2 -3
View File
@@ -1,6 +1,5 @@
// Character skins for the render kit. A skin is an animated sprite sheet (rows = facing
// directions, cols = animation frames) produced by the sprite pipeline
// (~/src/docs/animated-sprite-pipeline.md). Sheets are HEAVY and PREMIUM, so they are:
// Character skins for the render kit. A skin is an animated sprite sheet: rows are facing
// directions, columns are animation frames. Sheets are large and premium, so they are:
// - lazy-loaded (only fetched when an entity actually uses the skin, in a sprite-capable mode),
// - gated by entitlement (RK.entitlements.premium),
// - delivered as WebP.
+38 -39
View File
@@ -1,9 +1,9 @@
// SP game render bridge (RK.SPGame) — renders the single-player DUNGEON through the render kit
// (Tiled / ASCII / Iso / 3D + unlocked packs) instead of the legacy ROT display, so a pack you
// bought applies in actual gameplay, not just the tavern. It mounts a renderer in a dedicated host
// SP game render bridge (RK.SPGame): renders the single-player dungeon through the render kit
// (Tiled / ASCII / Iso / 3D + unlocked packs) rather than the legacy ROT display, so a purchased
// pack applies in gameplay and not only in the tavern. It mounts a renderer in a dedicated host
// inside #game-display and hides the legacy ROT canvases while a game is live; the retro splash /
// win / lose text screens still use ROT. If anything here is unavailable it returns false and the
// caller falls back to the legacy RenderEngine, so the live game can never hard-break.
// win / lose text screens still use ROT. When anything here is unavailable it returns false and the
// caller falls back to the legacy RenderEngine, so a live game can never hard-break.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
@@ -29,9 +29,8 @@
return doc().activeElement === gd;
};
// A dedicated, SELF-SIZING child host so the RK canvas doesn't collide with the ROT canvas and
// doesn't depend on the ROT canvas for its dimensions (it's an aspect-ratio viewport the camera
// transform is clipped to).
// A dedicated, self-sizing child host so the RK canvas neither collides with the ROT canvas nor
// depends on it for dimensions; it is the viewport the camera transform is clipped to.
function rkHost() {
var gd = gameDisplay();
if (!gd) return null;
@@ -39,12 +38,12 @@
if (!host) {
host = doc().createElement('div');
host.id = 'rk-game-host';
// FILL #game-display exactly (inset:0). #game-display is a definite, grid-bounded height
// (the .container is height:100vh; overflow:hidden), so filling it gives the camera
// reliable clientWidth/clientHeight every frame. The earlier `min(78vh)` + translate(-50%)
// centering could resolve to a wrong/transient size, stranding the view in a top band.
// Pure-black background so the area BEYOND the map edge is the SAME black as an
// unexplored ('dark') in-bounds tile — otherwise the shade difference outlines the map.
// inset:0 fills #game-display exactly. #game-display is a definite, grid-bounded height
// (.container is height:100vh; overflow:hidden), so filling it gives the camera reliable
// clientWidth/clientHeight every frame. Height caps plus translate(-50%) centering resolve
// to a wrong or transient size and strand the view in a top band, so avoid them.
// Pure-black background keeps the area beyond the map edge the same black as an
// unexplored ('dark') in-bounds tile; any shade difference outlines the map.
host.style.cssText = 'display:none; position:absolute; inset:0;' +
' overflow:hidden; background:#000; z-index:6; touch-action:none; cursor:grab;';
gd.appendChild(host);
@@ -131,8 +130,8 @@
if (!host || !RK.createRenderer) return null;
var mode = SP.mode();
// 3D needs THREE, lazy-loaded from the pinned same-origin vendor route (or the explicitly
// enabled CDN fallback). The sync createRenderer() returns Tiled until it is ready; remount
// as real 3D after loading so the screen never goes blank.
// enabled CDN fallback). The sync createRenderer() returns Tiled until it is ready, so the
// renderer is remounted as real 3D once loading finishes and the screen never goes blank.
if (mode === '3d' && RK.ensureThree && RK.threeReady && !RK.threeReady()) {
if (!SP._threePending) {
SP._threePending = true;
@@ -146,17 +145,17 @@
}
}
SP._renderer = RK.createRenderer(mode, host, { cell: 24 });
// The camera owns the canvas transform (centre on the player), so position it absolutely
// and let it overflow — do NOT use RK.attachZoom (it fights this transform).
// The camera owns the canvas transform (centre on the player), so the canvas is positioned
// absolutely and allowed to overflow. RK.attachZoom fights this transform; do not use it.
if (SP._renderer && SP._renderer.canvas) {
var c = SP._renderer.canvas;
c.style.position = 'absolute'; c.style.top = '0'; c.style.left = '0';
// Beat the `.rotdis canvas { max-width/height:100%; object-fit:contain }` rules (meant for
// the legacy ROT canvas) so the render-kit buffer maps 1:1 to the element and the CAMERA
// transform is the SOLE controller of scale/position. WITHOUT the max-height/object-fit
// override, a canvas TALLER than the host got object-fit-shrunk and the camera translate —
// computed in buffer space — pushed the player far off-screen (iso went fully BLACK; tiled's
// shorter canvas usually fit the host so it escaped the bug).
// Overrides the `.rotdis canvas { max-width/height:100%; object-fit:contain }` rules meant
// for the legacy ROT canvas, so the render-kit buffer maps 1:1 to the element and the
// camera transform is the sole controller of scale and position. Without these overrides a
// canvas taller than the host is object-fit-shrunk while the camera translate is computed
// in buffer space, pushing the player off-screen (iso canvases are tall enough to hit this;
// tiled canvases usually fit the host).
c.style.setProperty('max-width', 'none', 'important');
c.style.setProperty('max-height', 'none', 'important');
c.style.setProperty('object-fit', 'fill', 'important');
@@ -166,9 +165,9 @@
host._rkZoomBound = true;
host.addEventListener('wheel', function (ev) {
ev.preventDefault();
// Base the step on the CURRENT effective zoom (mode-aware default if not yet set),
// NOT a hardcoded 1.7 — otherwise the first scroll on iso (default 1.0) jumped up to
// 1.7 and BOTH directions read as "zoom in".
// The step is based on the current effective zoom (mode-aware default when unset).
// A hardcoded base makes the first scroll in a mode with a different default jump to
// that base, so both directions read as "zoom in".
var base = (SP._zoom != null) ? SP._zoom : SP._defaultZoom();
SP._setZoom(base * Math.exp(-ev.deltaY * 0.0015));
}, { passive: false });
@@ -208,14 +207,14 @@
return 1.7;
};
// Centre the (whole-scene) canvas on the player via a CSS transform, clipped to the host —
// renderer-agnostic (works for tiled / iso / 3d, each of which reports its own focusPoint).
// Centre the whole-scene canvas on the player via a CSS transform, clipped to the host. This is
// renderer-agnostic: tiled, iso and 3d each report their own focusPoint.
SP._applyCamera = function () {
var r = SP._renderer;
var host = doc() && doc().getElementById('rk-game-host');
if (!r || !r.canvas || !host) return;
// The 3D renderer fills the host itself (setSize) and its OWN THREE camera follows the
// player — so DON'T apply a CSS transform (it would double-transform the WebGL view).
// The 3D renderer fills the host itself (setSize) and its own THREE camera follows the
// player, so it takes no CSS transform; one would double-transform the WebGL view.
if (r.name === '3d') {
if (r.setZoom) r.setZoom((SP._zoom != null) ? SP._zoom : SP._defaultZoom());
r.canvas.style.transform = 'none';
@@ -225,10 +224,10 @@
}
var scale = (SP._zoom != null) ? SP._zoom : SP._defaultZoom();
var fp = r.focusPoint;
// ROBUSTNESS: if the renderer hasn't reported a focus this frame — a race at game start, or a
// camera tick reading a just-(re)created renderer instance before its first render — derive the
// focus straight from the last known player cell (tiled coords). Without this the camera falls
// back to a scale-only transform that pins the whole level to the top-left corner.
// A renderer can lack a focus for a frame: at game start, or when a camera tick reads a
// just-created renderer instance before its first render. In that case the focus is derived
// from the last known player cell (tiled coords); otherwise the camera falls back to a
// scale-only transform that pins the whole level to the top-left corner.
if (!fp && (r.name === 'tiles' || r.name === 'ascii') && SP._lastState && SP._lastState.player &&
typeof SP._lastState.player.x === 'number') {
var _c = r.cell || 24;
@@ -238,8 +237,8 @@
if (!fp) { r.canvas.style.transform = 'scale(' + scale + ')'; return; }
var w = host.clientWidth || host.offsetWidth || 640, h = host.clientHeight || host.offsetHeight || 400;
var tx = w / 2 - fp.x * scale, ty = h / 2 - fp.y * scale;
// Smooth follow: glide toward the target so single steps aren't jerky; SNAP on a big jump
// (level-change teleport / a stale-then-updated focus) rather than slowly panning the map.
// Smooth follow: glide toward the target so single steps aren't jerky, but snap on a big jump
// (level-change teleport, or a stale focus that then updates) rather than panning the map.
if (SP._camX == null || Math.abs(tx - SP._camX) > w || Math.abs(ty - SP._camY) > h) {
SP._camX = tx; SP._camY = ty;
} else {
@@ -272,8 +271,8 @@
return true;
};
// Re-apply the camera every frame while live — robust against the renderer resizing its canvas
// or a transient focusPoint, which was making the view snap to the corner mid-run.
// Re-applies the camera every frame while live, so a renderer resizing its canvas or a transient
// focusPoint cannot leave the view snapped to a corner mid-run.
SP._startCameraLoop = function () {
if (SP._camRaf != null) return;
function tick() {
+10 -10
View File
@@ -1,6 +1,6 @@
// TavernLife — client-side NPCs (bartender, patrons, cat) + speech bubbles that make the
// TavernLife: client-side NPCs (bartender, patrons, cat) + speech bubbles that make the
// tavern feel alive. NPCs are decorative: they wander, sit, and chat. They're client-side
// only (no server round-trips), so each client sees its own lively room — the real players
// only (no server round-trips), so each client sees its own lively room; the real players
// come from the server snapshot. Speech bubbles pop above any occupant (NPC or real player)
// when they speak.
(function (root) {
@@ -26,9 +26,9 @@
// ---- Speech lines -----------------------------------------------------------
var BARTENDER_LINES = [
"What'll it be, traveler?", "Ale's fresh today.", "Tab's full, friend.",
"Watch the monsters out there.", "Block's coming — hurry back.",
"Watch the monsters out there.", "Block's coming, hurry back.",
"I've seen braver than you not return.", "House special: liquid courage.",
"No credit — coin on the barrel.", "Heard someone found treasure last block.",
"No credit: coin on the barrel.", "Heard someone found treasure last block.",
"The dungeon's hungry tonight.", "Keep your wits about you.", "One ale, coming up."
];
var PATRON_LINES = [
@@ -40,7 +40,7 @@
"You new here?", "Don't go in unprepared.", "The exit was so close..."
];
var CAT_LINES = ["meow", "mrrrow", "prrrrp", "hisss", "...", "mew"];
var WELCOME_LINES = ["Welcome!", "Pull up a stool.", "New face — nice.", "Come in, sit down."];
var WELCOME_LINES = ["Welcome!", "Pull up a stool.", "New face, nice.", "Come in, sit down."];
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
@@ -80,7 +80,7 @@
return { minY: 3, maxY: rows - 2, minX: 1, maxX: cols - 2 };
}
function catArea(cols, rows) {
// The customer floor (in front of the bar) — not behind the counter, not the walls.
// The customer floor (in front of the bar): not behind the counter, not the walls.
return { minY: 4, maxY: rows - 2, minX: 1, maxX: cols - 2 };
}
@@ -223,7 +223,7 @@
}));
}
// A tavern cat — a random pixel cat from the Pet Cats Pack that wanders the floor.
// A tavern cat: a random pixel cat from the Pet Cats Pack that wanders the floor.
var catSpot = findFloor(4, rows - 4);
var cat = makeNPC('cat', 'cat', null, catSpot.x, catSpot.y, {
label: null, color: '#e8a060', role: 'cat', roamArea: catArea(cols, rows)
@@ -281,7 +281,7 @@
else if (stepY < 0) npc.facing = 'up';
else if (stepY > 0) npc.facing = 'down';
} else {
// Blocked — pick a new target.
// Blocked: pick a new target.
this._pickTarget(npc, scene);
}
// Cat moves faster; bartender slower.
@@ -350,7 +350,7 @@
y: originY + (e.x + e.y) * tileH / 2
};
} else if (mode === '3d') {
// 3D renderer uses Three.js — we can't easily get screen coords.
// 3D renderer uses Three.js; we can't easily get screen coords.
// Skip speech bubbles for 3D mode.
return null;
} else {
@@ -396,7 +396,7 @@
}
};
// Main update — called every frame via rAF.
// Main update: called every frame via rAF.
TavernLife.prototype.update = function (scene, cell, mode) {
if (!scene || !this._spawned) return;
var now = Date.now();
+35 -36
View File
@@ -1,5 +1,5 @@
// ThreeRenderer — a lit, textured 3D projection of the shared Scene. It uses generated GLB avatars
// when available and falls back to low-poly pieces so the mode remains usable during asset work.
// ThreeRenderer: a lit, textured 3D projection of the shared Scene. It uses GLB avatars when
// available and falls back to low-poly pieces so the mode stays usable without them.
//
// The level is drawn with three InstancedMeshes (walls / ground / props) so a 70x35 dungeon costs
// three draw calls instead of ~2500 individual meshes, and per-instance colour carries the same
@@ -16,8 +16,8 @@
return fallback || null;
}
// Deterministic PRNG — generated textures are byte-identical every session, so the dungeon
// doesn't subtly re-skin itself on reload.
// Deterministic PRNG: generated textures are byte-identical every session, so the dungeon
// does not subtly re-skin itself on reload.
function lcg(seed) {
var s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
@@ -55,7 +55,7 @@
});
}
// Irregular flagstones — a broken grout grid plus grain, so a large floor never shows an
// Irregular flagstones: a broken grout grid plus grain, so a large floor never shows an
// obvious repeat.
function groundCanvas(size) {
return makeCanvas(size, function (c, s) {
@@ -115,7 +115,7 @@
};
var HAZARD_GLOW = { lava: 0.85, poison: 0.5, spikes: 0.12 };
// Ground tints. The scene legend colours are tuned for flat 2D fills and read almost black in a
// lit 3D scene, so wall/floor use material-appropriate values and everything else falls back to
// lit 3D scene, so wall/floor use material-appropriate values; everything else falls back to
// the legend.
var KIND_TINT = {
wall: '#a49a8b', window: '#7d94a8', door: '#9c7a4a', archway: '#a49a8b',
@@ -153,9 +153,9 @@
// Fog-of-war parity with the 2D modes: the camera follows the player, so distance fog fades
// explored tiles to black away from you, and _buildTiles skips unexplored ('dark') tiles so
// they never render. Together: unexplored = hidden, explored fades with distance, no map leak.
// Fog is measured from the CAMERA, which sits ~17 units back along the isometric offset —
// not from the player. A band tuned as if it started at the player put the player themselves
// a quarter of the way into fog and crushed the whole scene to near-black.
// The fog band is measured from the CAMERA, which sits ~17 units back along the isometric
// offset, not from the player. Tuning it as if it started at the player puts the player a
// quarter of the way into fog and crushes the scene to near-black.
this.scene.fog = new T.Fog(0x05060a, 21, 46);
this.camera = new T.OrthographicCamera(-10, 10, 10, -10, 0.1, 120);
this.camera.position.set(9, 11, 9);
@@ -180,7 +180,7 @@
var hemi = new T.HemisphereLight(0x9fb4d8, 0x161a24, 0.5);
this.scene.add(hemi);
this.keyLight = new T.DirectionalLight(0xffd9a8, 2.3);
this.keyLight.position.set(10, 8.5, 4); // low sun — long, readable wall shadows
this.keyLight.position.set(10, 8.5, 4); // low sun: long, readable wall shadows
this.keyLight.castShadow = true;
this.keyLight.shadow.mapSize.set(1024, 1024);
this.keyLight.shadow.camera.near = 1;
@@ -250,7 +250,7 @@
map: groundMap, bumpMap: groundBump, bumpScale: 0.35, roughness: 0.96, metalness: 0.0
});
this.propMat = new T.MeshStandardMaterial({ roughness: 0.8, metalness: 0.05 });
// Hazards/fire glow on their own so they stay legible in an unlit corridor.
// Hazards/fire glow on their own so they stay legible in an unlit corridor.
this.glowMat = new T.MeshStandardMaterial({
roughness: 0.55, metalness: 0.0, emissive: new T.Color(0xffffff), emissiveIntensity: 0.9
});
@@ -282,16 +282,16 @@
this.scene.add(this.motes);
};
// Fill the host and frame a fixed "screenful" around the player. The camera FOLLOWS the player
// Fill the host and frame a fixed "screenful" around the player. The camera follows the player
// (see _animate) instead of framing the whole level, so 3D behaves like the other modes. Only
// does work when the host size actually changed (cheap to call every frame).
// does work when the host size actually changed, so it is cheap to call every frame.
ThreeRenderer.prototype._fitToHost = function () {
var host = this.host;
var w = (host && (host.clientWidth || host.offsetWidth)) || 640;
var h = (host && (host.clientHeight || host.offsetHeight)) || 400;
if (w === this._cw && h === this._ch) return;
this._cw = w; this._ch = h;
this.renderer.setSize(w, h, true); // updateStyle:true → the canvas CSS-fills the host
this.renderer.setSize(w, h, true); // updateStyle:true so the canvas CSS-fills the host
var aspect = w / h, span = 6.6 / (this.zoom || 1); // fixed screenful, user-adjustable zoom
this.camera.left = -span * aspect;
this.camera.right = span * aspect;
@@ -308,9 +308,9 @@
this._fitToHost();
};
// `attachCamera` reports drag pan in viewport pixels. Keep that contract for 3D and convert the
// `attachCamera` reports drag pan in viewport pixels. 3D keeps that contract and converts the
// offset to ground-plane world units in _animate(), where the followed player's current smoothed
// position is available. Bound it to one viewport so a stray gesture cannot lose the dungeon.
// position is available. The bound of one viewport keeps a stray gesture from losing the dungeon.
ThreeRenderer.prototype.setPan = function (x, y) {
var w = (this.host && (this.host.clientWidth || this.host.offsetWidth)) || 640;
var h = (this.host && (this.host.clientHeight || this.host.offsetHeight)) || 400;
@@ -336,8 +336,8 @@
});
};
// One InstancedMesh per bucket, grown geometrically. Reusing the mesh across rebuilds is what
// keeps a fog-of-war update from re-allocating the whole level every time the player steps.
// One InstancedMesh per bucket, grown geometrically. Reusing the mesh across rebuilds keeps a
// fog-of-war update from re-allocating the whole level every time the player steps.
ThreeRenderer.prototype._bucket = function (name, geom, mat, needed) {
var T = this.THREE;
var b = this.buckets[name];
@@ -374,13 +374,13 @@
for (y = 0; y < scene.rows; y++) {
for (x = 0; x < scene.cols; x++) {
kind = scene.grid[y] && scene.grid[y][x];
if (!kind || kind === 'dark') continue; // unexplored — never render it (fog-of-war)
if (!kind || kind === 'dark') continue; // unexplored: never rendered (fog-of-war)
var def = legend[kind] || {};
var lb = (light && light[y] && light[y][x] != null) ? light[y][x] : 1;
// Unlike the 2D modes — where lightGrid IS the lighting — 3D has real point lights
// doing the falloff, so applying the grid at full strength to the albedo as well
// double-darkened every surface into near-black. Compress it into a gentle range and
// let the lamps shape the scene.
// In the 2D modes lightGrid IS the lighting; here real point lights do the falloff.
// Applying the grid at full strength to the albedo as well would double-darken every
// surface into near-black, so it is compressed into a gentle range and the lamps
// shape the scene.
var b = 0.38 + 0.62 * Math.max(0, Math.min(1, lb));
var tint = KIND_TINT[kind] || def.color || '#6d6558';
var cell = { x: x - cx, z: y - cz, gx: x, gy: y, b: b, tint: tint, kind: kind };
@@ -427,7 +427,7 @@
p.set(cell.x, h / 2, cell.z);
m.compose(p, q, s);
b.mesh.setMatrixAt(i, m);
// Hazards keep near-full brightness — a lava pool you can barely see is a trap, not a
// Hazards keep near-full brightness: a lava pool you can barely see is a trap, not a
// difficulty curve.
var hb = cell.hazard ? Math.max(0.7, cell.b) : cell.b;
c.set(colorNum(cell.tint)).multiplyScalar(hb);
@@ -438,7 +438,7 @@
if (b.mesh.instanceColor) b.mesh.instanceColor.needsUpdate = true;
};
// Walls are rewritten whenever the player's cell changes so the cutaway can follow them: walls
// Walls are rewritten whenever the player's cell changes so the cutaway follows them: walls
// sitting between the isometric camera (+x/+z) and the player are squashed and darkened, the 3D
// equivalent of the iso renderer's fade. Without it the near wall of every corridor hides you.
ThreeRenderer.prototype._writeWalls = function () {
@@ -467,9 +467,9 @@
if (b.mesh.instanceColor) b.mesh.instanceColor.needsUpdate = true;
};
// Braziers on the torch walls. Only the cells that newly appeared get geometry — the tile
// buckets are rewritten on every move (that is how remembered tiles keep dimming), and building
// a fresh mesh per torch per step would churn the GPU for no visual gain.
// Braziers on the torch walls. Only newly appeared cells get geometry: the tile buckets are
// rewritten on every move (that is how remembered tiles keep dimming), and building a fresh mesh
// per torch per step would churn the GPU for no visual gain.
ThreeRenderer.prototype._syncFixtures = function () {
var T = this.THREE;
this._flames = this._flames || {};
@@ -550,9 +550,8 @@
return g;
};
// Dungeon FEATURES/ITEMS (entrance/exit/treasure/pickups) are set dressing, not avatars. Before
// this branch existed every one of them was drawn as a humanoid capsule, so the entrance looked
// like a second player standing at the map origin.
// Dungeon features and items (entrance/exit/treasure/pickups) are set dressing, not avatars, so
// they get their own geometry rather than the humanoid capsule an avatar would draw.
ThreeRenderer.prototype._makeFeature = function (e) {
var T = this.THREE;
var g = new T.Group();
@@ -771,10 +770,10 @@
if (pcell) { this._plx = pcell.x; this._ply = pcell.y; }
// Rewrite the level every render. `render` is called on game updates (a keypress), not per
// frame, and the buckets are three reused InstancedMeshes — so this is a few thousand matrix
// frame, and the buckets are three reused InstancedMeshes, so this is a few thousand matrix
// writes, not an allocation. It has to be unconditional: `lightGrid` re-shades remembered
// tiles on EVERY step, so keying the rebuild on the grid alone froze the fog-of-war fade at
// whatever it was when a cell was first seen.
// tiles on every step, so keying the rebuild on the grid alone would freeze the fog-of-war
// fade at whatever it was when a cell was first seen.
this._buildTiles(scene);
var seen = {}, cx = (scene.cols - 1) / 2, cz = (scene.rows - 1) / 2;
@@ -866,7 +865,7 @@
}
this._playAction(o, moving ? 'run' : 'idle');
// Face the way you move. Prefer explicit facing (tavern); else infer from the world delta
// (the SP game doesn't send player.facing). world x=grid x, world z=grid y.
// (the SP game does not send player.facing). world x=grid x, world z=grid y.
var face = ent.e && ent.e.facing;
if (!face && moving) { face = Math.abs(dx) >= Math.abs(dz) ? (dx > 0 ? 'right' : 'left') : (dz > 0 ? 'down' : 'up'); ent._face = face; }
face = face || ent._face;
@@ -877,7 +876,7 @@
}
// Player-follow camera: keep the fixed iso offset but re-target the player's world position
// each frame. The player mesh itself lerps, so the camera glides smoothly with it.
this._fitToHost(); // pick up any host resize
this._fitToHost(); // picks up any host resize
var pcam = null;
for (var pid in this.entities) {
var pen = this.entities[pid];
-82
View File
@@ -1,82 +0,0 @@
// Tile-picker — a dev overlay to map a theme's tileset cells to game tile-kinds by CLICKING.
// Pick a kind (floor/wall/bar/table), click the matching cell in the sheet; it's saved to
// localStorage and the tavern re-renders live. Works for any pack, so no coordinate-guessing.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
RK.openTilePicker = function (onChange) {
var themeId = RK.activeThemeId;
var atlas = RK.themeAtlas(themeId);
if (!atlas) return;
atlas.onReady(function () { build(themeId, atlas, onChange); });
};
function build(themeId, atlas, onChange) {
var SCALE = 2;
var stride = atlas.tile + atlas.spacing;
var wrap = document.createElement('div');
wrap.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.82);z-index:9999;overflow:auto;padding:16px;font-family:ui-monospace,monospace;color:#d7dbe0;';
var bar = document.createElement('div');
bar.style.cssText = 'display:flex;gap:8px;align-items:center;margin-bottom:8px;flex-wrap:wrap;';
var active = RK.TILE_KINDS[0];
var status = document.createElement('span');
status.style.cssText = 'font-size:13px;color:#9cf;';
RK.TILE_KINDS.forEach(function (k) {
var b = document.createElement('button');
b.textContent = k; b.dataset.kind = k;
b.style.cssText = 'font:inherit;padding:6px 10px;border:1px solid #2a313a;border-radius:4px;background:#0a0c0f;color:#d7dbe0;cursor:pointer;';
b.onclick = function () { active = k; refresh(); status.textContent = 'Click the tile for: ' + k; };
bar.appendChild(b);
});
var done = document.createElement('button');
done.textContent = 'Done';
done.style.cssText = 'font:inherit;padding:6px 12px;border:0;border-radius:4px;background:#3fb950;color:#08130a;cursor:pointer;font-weight:600;margin-left:auto;';
done.onclick = function () { document.body.removeChild(wrap); };
bar.appendChild(status); bar.appendChild(done);
function refresh() {
Array.prototype.forEach.call(bar.querySelectorAll('button[data-kind]'), function (b) {
b.style.outline = b.dataset.kind === active ? '2px solid #3fb950' : 'none';
});
}
wrap.appendChild(bar);
var cv = document.createElement('canvas');
cv.width = atlas.img.width * SCALE; cv.height = atlas.img.height * SCALE;
cv.style.cssText = 'image-rendering:pixelated;border:1px solid #2a313a;background:#111;cursor:crosshair;';
var ctx = cv.getContext('2d');
function draw() {
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, cv.width, cv.height);
ctx.drawImage(atlas.img, 0, 0, cv.width, cv.height);
ctx.strokeStyle = 'rgba(63,185,80,0.22)'; ctx.lineWidth = 1;
for (var c = 0; c <= atlas.cols; c++) { ctx.beginPath(); ctx.moveTo(c * stride * SCALE, 0); ctx.lineTo(c * stride * SCALE, cv.height); ctx.stroke(); }
for (var r = 0; r <= atlas.rows; r++) { ctx.beginPath(); ctx.moveTo(0, r * stride * SCALE); ctx.lineTo(cv.width, r * stride * SCALE); ctx.stroke(); }
var map = RK.tileMap(themeId);
RK.TILE_KINDS.forEach(function (k) {
var co = map[k]; if (!co) return;
ctx.strokeStyle = '#ffb800'; ctx.lineWidth = 2;
ctx.strokeRect(co[0] * stride * SCALE, co[1] * stride * SCALE, atlas.tile * SCALE, atlas.tile * SCALE);
ctx.fillStyle = '#ffb800'; ctx.font = 'bold 11px monospace';
ctx.fillText(k[0].toUpperCase(), co[0] * stride * SCALE + 2, co[1] * stride * SCALE + 11);
});
}
cv.onclick = function (e) {
var rect = cv.getBoundingClientRect();
var col = Math.floor(((e.clientX - rect.left) / SCALE) / stride);
var row = Math.floor(((e.clientY - rect.top) / SCALE) / stride);
if (col < 0 || row < 0 || col >= atlas.cols || row >= atlas.rows) return;
RK.setTile(themeId, active, col, row);
draw();
if (onChange) onChange();
};
wrap.appendChild(cv);
document.body.appendChild(wrap);
refresh(); status.textContent = 'Click the tile for: ' + active; draw();
}
})(window);
+31 -38
View File
@@ -1,4 +1,4 @@
// TileRenderer — draws a Scene as tiled sprites + entity sprites on a 2D canvas.
// TileRenderer: draws a Scene as tiled sprites + entity sprites on a 2D canvas.
// The default tier. Pulls tiles from the theme atlas (Kenney roguelikeSheet) when loaded,
// with a flat-colour fallback for any unmapped kind. Adds torch-lit dungeon atmosphere:
// per-cell tile variation, drop shadows, a warm torch light on the player + edge vignette,
@@ -90,10 +90,9 @@
var tmap = (window.RK && RK.tileMap) ? RK.tileMap() : {};
var useAtlas = !!(atlas && atlas.ready);
// The atlas image loads async. If you switch INTO this renderer (e.g. entering the tavern
// in Tiled mode) before it's ready, the first paint uses the flat-colour fallback — which
// looks like plain blocks. Without a re-render it stays stuck there until the next scene
// update. Hook the atlas so we repaint the moment it's ready.
// The atlas image loads async. Switching into this renderer before it is ready paints the
// flat-colour fallback, and nothing repaints until the next scene update. Hooking onReady
// forces a repaint as soon as the atlas is available.
if (atlas && !atlas.ready && !this._atlasHooked && typeof atlas.onReady === 'function') {
this._atlasHooked = true;
var self = this;
@@ -101,7 +100,7 @@
}
if (!scene.isDungeon && window.RK && RK.roomReady && RK.roomReady()) {
// A designed room (imported .tmx) is loaded — draw its layered tiles.
// A designed room (imported .tmx) is loaded: draw its layered tiles.
RK.drawRoomCanvas(ctx, cell);
} else {
for (var y = 0; y < scene.rows; y++) {
@@ -109,9 +108,11 @@
var kind = scene.grid[y][x];
var px = x * cell, py = y * cell;
var def = scene.legend[kind] || { color: '#333' };
// Fire fixtures (torch/hearth) & hazard tiles (lava/poison/spikes) draw only
// their ground base here; RK.fx paints the animated flame / pulse over the
// snapshot in the flicker loop so they actually move. Skip the solid colour block.
// Fire fixtures (torch/hearth) and hazard tiles (lava/poison/spikes) draw only
// their ground base here (a wall for a dungeon torch); RK.fx paints the animated
// flame / pulse over the snapshot in the flicker loop so they move. The pack's
// torch SPRITE is deliberately skipped: several sheets place it off-center or
// rotated, so a procedural flame on a plain base reads correctly in every pack.
if (def.fx === 'fire' || def.hazard) {
var baseKind = def.over || 'floor';
var bco = useAtlas ? pickVariant(tmap[baseKind], x, y) : null;
@@ -121,20 +122,15 @@
ctx.fillStyle = bdef.color || def.color;
ctx.fillRect(px, py, cell, cell);
}
// Fire fixtures draw ONLY their base (wall for a dungeon torch) here; RK.fx
// paints the animated flame + warm glow centered on the cell in the flicker
// loop. We deliberately skip the pack's torch SPRITE — several sheets place it
// off-center / rotated, which read as misaligned; the procedural flame on a wall
// base is a clean wall-mounted torch that looks right in every pack.
applyCellLight(ctx, scene, x, y, px, py, cell);
continue;
}
var coord = useAtlas ? pickVariant(tmap[kind], x, y) : null;
if (coord) {
// Object tiles (furniture, windows, torches, treasure…) are transparent
// around the object. Legend `over` names the ground they sit on (floor/wall);
// draw that first so the transparency shows the room, not the dark canvas.
// Pipeline-level: any scene can declare it, not a tavern one-off.
// Object tiles (furniture, windows, torches, treasure) are transparent around
// the object. Legend `over` names the ground they sit on (floor/wall); drawing
// that first makes the transparency show the room, not the dark canvas. Any
// scene can declare `over`; it is not a tavern-only path.
if (def.over && tmap[def.over]) {
var base = pickVariant(tmap[def.over], x, y);
if (base) atlas.draw(ctx, base[0], base[1], px, py, cell);
@@ -177,7 +173,7 @@
var now = Date.now();
for (var i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i];
// Dungeon features (entrance / exit / treasure) — real tiles, glyph fallback.
// Dungeon features (entrance / exit / treasure): real tiles, glyph fallback.
if (e.kind === 'feature') {
var fpx = e.x * cell, fpy = e.y * cell;
var fc = useAtlas ? pickVariant(featureCoord(tmap, e), e.x, e.y) : null;
@@ -200,7 +196,6 @@
}
continue;
}
// Dungeon items.
if (e.kind === 'item') {
var ipx = e.x * cell, ipy = e.y * cell;
var ic = useAtlas ? pickVariant(tmap.treasure, e.x, e.y) : null;
@@ -212,12 +207,10 @@
}
continue;
}
// Dungeon monster — draw the Goblin character sprite (same path the tavern draws
// characters through), falling back to a red orb only if the sprite is unavailable.
if (e.kind === 'monster') {
drawEntityShadow(ctx, e.x * cell + cell / 2, e.y * cell + cell * 0.9, cell * 0.32, cell * 0.13);
// Prefer the active pack's monster TILE (e.g. the Original pack's ~ goblin) so a
// classic tile pack renders classic; else the character sprite; else a red orb.
// Preference order: the active pack's monster TILE, so a classic tile pack renders
// classic; then the Goblin character sprite; then a red orb.
var mCoord = useAtlas ? pickVariant(tmap.monster, e.x, e.y) : null;
if (mCoord) { atlas.draw(ctx, mCoord[0], mCoord[1], e.x * cell, e.y * cell, cell); continue; }
var mAvatar = e.avatar || 'char-goblin';
@@ -236,15 +229,15 @@
ctx.stroke();
continue;
}
// Tavern cat — a standalone animated sprite (Pet Cats Pack), not a char-atlas avatar.
// Tavern cat: a standalone animated sprite (Pet Cats Pack), not a char-atlas avatar.
if (e.kind === 'cat') {
drawEntityShadow(ctx, e.x * cell + cell / 2, e.y * cell + cell * 0.9, cell * 0.28, cell * 0.11);
if (window.RK && RK.drawCatCanvas && RK.drawCatCanvas(ctx, e, cell, now)) continue;
}
// Character-like entity: soft ground shadow, then the sprite (or fallback circle).
drawEntityShadow(ctx, e.x * cell + cell / 2, e.y * cell + cell * 0.92, cell * 0.34, cell * 0.14);
// In the DUNGEON, prefer the active pack's player TILE (Original pack's @ hero) over the
// sprite so a classic pack is fully classic. The tavern keeps character sprites.
// In the dungeon the active pack's player TILE wins over the character sprite so a
// classic pack is fully classic. The tavern keeps character sprites.
if (scene.isDungeon && (e.you || e.kind === 'player') && useAtlas) {
var pCoord = pickVariant(tmap.player, e.x, e.y);
if (pCoord) { atlas.draw(ctx, pCoord[0], pCoord[1], e.x * cell, e.y * cell, cell); continue; }
@@ -293,9 +286,9 @@
// Snapshot the base scene, then composite the torch light + vignette on top, and keep
// an animation loop running so the light flickers and embers drift between renders.
// Where the player is on this canvas — the SP camera centers on it. Sticky: keep the last
// point if the player is momentarily absent (level transition), so the view never snaps to
// the corner.
// focusPoint is where the player is on this canvas; the SP camera centers on it. It is
// sticky: while the player is momentarily absent (level transition) the last point stands,
// so the view never snaps to the corner.
var _fp = findPlayer(scene);
if (_fp) this.focusPoint = { x: (_fp.x + 0.5) * cell, y: (_fp.y + 0.5) * cell };
@@ -375,8 +368,8 @@
};
TileRenderer.prototype._ensureEmbers = function (scene) {
// Embers belong to the dungeon torch the player carries — never in the tavern (or any
// non-dungeon scene), where they'd make the "you" avatar look like a flaming dot.
// Embers belong to the dungeon torch the player carries, never to the tavern or any other
// non-dungeon scene, where they would make the "you" avatar look like a flaming dot.
if (!scene || !scene.isDungeon) { this._embers = []; return; }
var p = findPlayer(scene);
if (!p) { this._embers = []; return; }
@@ -414,14 +407,15 @@
}
};
// Warm torch light on the player cell + drifting embers + an edge vignette. Ported from
// the FancyRenderer recipe to flat 2D canvas (no Pixi, no shaders).
// Warm torch light on the player cell + drifting embers + an edge vignette, on flat 2D
// canvas (no Pixi, no shaders).
TileRenderer.prototype._composite = function (scene) {
var ctx = this.ctx;
if (!ctx) return;
var w = this.canvas.width, h = this.canvas.height, cell = this.cell;
// The warm torch light + embers are a DUNGEON effect (the player carries the torch). In the
// tavern there's no torch, so skip it — otherwise the "you" cell glows like a flaming dot.
// The warm torch light + embers are a dungeon effect (the player carries the torch). The
// tavern has no torch, so it is skipped there; otherwise the "you" cell glows like a
// flaming dot.
var p = (scene && scene.isDungeon) ? findPlayer(scene) : null;
if (p) {
var cx = p.x * cell + cell / 2, cy = p.y * cell + cell / 2;
@@ -437,7 +431,6 @@
ctx.beginPath();
ctx.arc(cx, cy, rad, 0, Math.PI * 2);
ctx.fill();
// Embers.
for (var i = 0; i < this._embers.length; i++) {
var m = this._embers[i];
var a = Math.max(0, Math.min(1, m.life / m.max)) * 0.6;
@@ -463,7 +456,7 @@
ctx.fillRect(0, 0, w, h);
ctx.restore();
// Animated fire fixtures + hazard tiles — drawn over the vignette so their light punches
// Animated fire fixtures + hazard tiles draw over the vignette so their light punches
// through the dark edges rather than being dimmed by it.
var em = this._emitters;
if (em && em.length && root.RK && RK.fx) {