Wownerogue

A browser-based roguelike synchronized with crypto block timing. A run is a race
against the next block: reach the exit before the block lands, or the house wins.
The same codebase runs the solo dungeon, the social Tavern, and operator-selected
PvP and race rulesets, with separate free and paid leaderboards.

Self-hostable under the MIT License. See README.md to run it, docs/ARCHITECTURE.md
for the design, and docs/DEPLOY.md to operate an instance.
This commit is contained in:
jwinterm
2026-07-27 08:23:01 -04:00
commit fad2a695bd
578 changed files with 102281 additions and 0 deletions
+158
View File
@@ -0,0 +1,158 @@
// 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';
function AsciiRenderer(host, opts) {
opts = opts || {};
this.name = 'ascii';
this.host = host;
this.cell = opts.cell || 22;
this.canvas = document.createElement('canvas');
this.canvas.className = 'rk-canvas';
this.ctx = this.canvas.getContext('2d');
host.appendChild(this.canvas);
}
AsciiRenderer.prototype.render = function (scene) {
if (!scene) return;
this.lastScene = scene;
var cell = this.cell, ctx = this.ctx, now = Date.now(), hasTorch = false;
this.canvas.width = scene.cols * cell;
this.canvas.height = scene.rows * cell;
ctx.fillStyle = scene.background || '#000';
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
var glyphFont = (cell - 4) + "px 'Courier New', monospace";
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = glyphFont;
// For a designed room, ASCII shows a floor-plan from the walkability grid.
var room = (!scene.isDungeon && window.RK && RK.roomReady && RK.roomReady()) ? RK.activeRoom.desc : null;
for (var y = 0; y < scene.rows; y++) {
for (var x = 0; x < scene.cols; x++) {
if (room) {
var walk = room.walkable[y] && room.walkable[y][x];
ctx.fillStyle = walk ? '#2f4030' : '#39404c';
ctx.fillText(walk ? '·' : '#', x * cell + cell / 2, y * cell + cell / 2);
} else {
var kind = scene.grid[y][x];
var def = scene.legend[kind] || { char: '?', color: '#555' };
var gx = x * cell + cell / 2, gy = y * cell + cell / 2;
if (def.fx === 'fire') {
// Torches are ACTUAL light sources: a warm radial glow behind the glyph that
// gently flickers; the glyph itself stays at full brightness (never dimmed).
hasTorch = true;
var seed = x * 7 + y * 13;
var fl = 0.7 + Math.sin(now / 170 + seed) * 0.3;
var rad = cell * (1.9 + Math.sin(now / 240 + seed) * 0.18);
var g = ctx.createRadialGradient(gx, gy, 0, gx, gy, rad);
g.addColorStop(0, 'rgba(255,196,96,' + (0.6 * fl) + ')');
g.addColorStop(0.45, 'rgba(255,140,44,' + (0.24 * fl) + ')');
g.addColorStop(1, 'rgba(255,120,30,0)');
ctx.globalAlpha = 1;
ctx.fillStyle = g;
ctx.fillRect(gx - rad, gy - rad, rad * 2, rad * 2);
ctx.fillStyle = '#ffd9a0';
ctx.fillText(def.char, gx, gy);
} else {
// Brighter glyph colours for readability: the dungeon legend colours are
// near-black (tuned for TILE fog, not glyphs), which made ASCII walls/floors
// almost invisible. Features (entrance/exit/treasure) keep their own colours.
ctx.fillStyle = kind === 'wall' ? '#8b95a6'
: (kind === 'floor' || kind === 'floor2') ? '#5b6472'
: def.color;
// Dungeon lighting: dim tiles in shadow.
if (scene.lightGrid && scene.lightGrid[y] && scene.lightGrid[y][x] != null) {
var b = scene.lightGrid[y][x];
if (b < 1) ctx.globalAlpha = b;
}
ctx.fillText(def.char, gx, gy);
ctx.globalAlpha = 1;
}
}
}
}
for (var i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i];
var cx = e.x * cell + cell / 2, cy = e.y * cell + cell / 2;
ctx.font = glyphFont;
ctx.fillStyle = e.color || '#fff';
// Dungeon features and entities use their own char/color.
if (e.kind === 'feature' || e.kind === 'item' || e.kind === 'monster') {
ctx.fillStyle = e.color || '#fff';
ctx.fillText(e.char || '?', cx, cy);
if (e.you) {
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1;
ctx.strokeRect(e.x * cell + 2, e.y * cell + 2, cell - 4, cell - 4);
}
if (e.label) {
ctx.font = '10px monospace';
ctx.fillStyle = '#d7dbe0';
ctx.fillText(e.label, cx, e.y * cell - 1);
}
continue;
}
ctx.fillStyle = e.color || '#fff';
ctx.fillText(e.char || '@', cx, cy);
if (e.you) {
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1;
ctx.strokeRect(e.x * cell + 2, e.y * cell + 2, cell - 4, cell - 4);
}
if (e.label) {
ctx.font = '10px monospace';
ctx.fillStyle = '#d7dbe0';
ctx.fillText(e.label, cx, e.y * cell - 1);
}
}
// 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;
for (var pj = 0; pj < scene.entities.length; pj++) {
var pe = scene.entities[pj];
if (pe.kind === 'player' && !focusFallback) focusFallback = pe;
if (pe.you || pe.cameraTarget) {
this.focusPoint = { x: pe.x * cell + cell / 2, y: pe.y * cell + cell / 2 };
focusFallback = null;
break;
}
}
if (focusFallback) this.focusPoint = { x: focusFallback.x * cell + cell / 2, y: focusFallback.y * cell + cell / 2 };
// Keep a light RAF alive so the torch glows flicker between game updates (~22fps).
this._hasTorches = hasTorch;
if (hasTorch) this._scheduleFlicker();
};
// Re-render on a throttled RAF so torch glows breathe even when the game isn't updating.
AsciiRenderer.prototype._scheduleFlicker = function () {
if (this._flickerRaf || !this._hasTorches || !this.ctx) return;
var self = this;
this._flickerRaf = requestAnimationFrame(function () {
self._flickerRaf = null;
if (!self.ctx || !self._hasTorches || !self.lastScene) return;
var t = Date.now();
if (self._lastFlick && t - self._lastFlick < 45) { self._scheduleFlicker(); return; }
self._lastFlick = t;
self.render(self.lastScene);
});
};
AsciiRenderer.prototype.destroy = function () {
this._hasTorches = false;
if (this._flickerRaf) { cancelAnimationFrame(this._flickerRaf); this._flickerRaf = null; }
if (this.canvas && this.canvas.parentNode) this.canvas.parentNode.removeChild(this.canvas);
this.canvas = null;
this.ctx = null;
};
root.RK = root.RK || {};
root.RK.AsciiRenderer = AsciiRenderer;
})(window);
+469
View File
@@ -0,0 +1,469 @@
// Themes / packs / entitlement policy for the render kit. Packs are resolved by capability
// (top-down, isometric, 3D) so the same `appearance` identity can render through different
// visual projections without changing Room state or join flow.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
RK.TILE_KINDS = ['floor', 'wall', 'bar', 'table'];
var FREE_EQUIPMENT = { body: 'none', head: 'none', shield: 'none', weapon: 'none' };
var FREE_COLORS = { base: 'none', skin: 'natural', hair: 'copper', body: 'none', head: 'none', shield: 'none', weapon: 'none' };
RK.PACKS = {
'roguelike-interior': {
id: 'roguelike-interior',
label: 'Kenney Roguelike Interior',
premium: false,
projection: 'topdown'
},
'iso-dungeon': {
id: 'iso-dungeon',
label: 'Kenney Isometric Dungeon',
premium: true,
projection: 'iso',
unlock: { kind: 'credits_purchase', minTotalCreditsPurchased: 1 }
},
'kenney-3d-characters': {
id: 'kenney-3d-characters',
label: 'Kenney Animated 3D Characters',
premium: true,
projection: '3d',
unlock: { kind: 'credits_purchase', minTotalCreditsPurchased: 1 }
},
'generated-skins': {
id: 'generated-skins',
label: 'Premium Generated Skins',
premium: true,
projection: 'topdown',
unlock: { kind: 'credits_purchase', minTotalCreditsPurchased: 1 }
}
};
RK.entitlements = RK.entitlements || { premium: false, level: 'free', packs: {}, credits: 0, totalCreditsPurchased: 0 };
RK.setEntitlementSnapshot = function (data) {
data = data || {};
var prev = RK.entitlements || {};
// 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];
for (var ci = 0; ci < data.catalog.length; ci++) {
var c = data.catalog[ci];
if (!c || !c.id) continue;
var ex = merged[c.id] || {};
merged[c.id] = {
id: c.id,
label: c.label || ex.label || c.id,
premium: c.premium != null ? !!c.premium : !!ex.premium,
projection: c.projection || ex.projection || null,
tier: c.tier != null ? c.tier : ex.tier,
unlockMinCredits: c.unlockMinCredits != null ? c.unlockMinCredits : ex.unlockMinCredits,
unlock: ex.unlock
};
}
RK.PACKS = merged;
}
var hasTotal = data.totalCreditsPurchased != null || data.total_credits_purchased != null;
var hasPremium = data.premium != null;
var hasPacks = !!data.packs;
var hasCredits = data.credits != null || data.balance != null;
var total = hasTotal
? Number(data.totalCreditsPurchased || data.total_credits_purchased || 0)
: Number(prev.totalCreditsPurchased || 0);
var credits = hasCredits
? Number(data.credits != null ? data.credits : data.balance)
: Number(prev.credits || 0);
var premium = hasPremium ? !!data.premium : (hasTotal ? total > 0 : !!prev.premium);
var packs = {};
for (var id in RK.PACKS) {
var p = RK.PACKS[id];
if (!p.premium) {
packs[id] = true;
} else if (hasPacks && Object.prototype.hasOwnProperty.call(data.packs, id)) {
packs[id] = !!data.packs[id];
} else if (!hasTotal && !hasPacks && prev.packs && Object.prototype.hasOwnProperty.call(prev.packs, id)) {
packs[id] = !!prev.packs[id];
} else {
packs[id] = premium;
}
}
for (var pid in packs) {
if (packs[pid] && RK.PACKS[pid] && RK.PACKS[pid].premium) premium = true;
}
RK.entitlements = {
premium: premium,
level: data.level || (premium ? ((prev.level && prev.level !== 'free') ? prev.level : 'credits') : 'free'),
packs: packs,
credits: credits,
totalCreditsPurchased: total
};
try { localStorage.setItem('rk_entitlements', JSON.stringify(RK.entitlements)); } catch (_) {}
return RK.entitlements;
};
RK.loadEntitlements = function () {
try {
var raw = JSON.parse(localStorage.getItem('rk_entitlements') || 'null');
if (raw) return RK.setEntitlementSnapshot(raw);
} catch (_) {}
return RK.entitlements;
};
RK.loadEntitlements();
RK.pack = function (id) { return RK.PACKS[id] || null; };
RK.canUsePack = function (id) {
var p = RK.pack(id);
if (!p) return false;
if (!p.premium) return true;
// Production QA switch: when enabled, all premium packs are available for testing.
if (RK.renderModeTestUnlocks && RK.renderModeTestUnlocks()) return true;
return !!(RK.entitlements && RK.entitlements.packs && RK.entitlements.packs[id]);
};
RK.canUseAppearance = function (a) {
if (!a || !a.premium) return true;
return a.pack ? RK.canUsePack(a.pack) : !!(RK.entitlements && RK.entitlements.premium);
};
RK.THEMES = {
// 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',
// 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],
floor2: [32, 0], // alt/dirt floor
wall: [2, 1], // stone brick wall
door: [1, 0], // wooden door
entrance: [0, 1],
exit: [1, 0],
treasure: [30, 0], // $W gold coin
torch: [32, 1],
// 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, 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).
// The tile-picker overlay can override these per-user via localStorage.
// 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
// 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, 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
}
},
// 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
bar: [23, 0], // barrels (a dungeon has no bar)
keg: [23, 0],
shelf: [25, 0], // crate
table: [25, 0], // crate as a table
chair: [23, 0], // barrel as a stool
barrel: [23, 0],
crate: [25, 0],
rug: [6, 2], // stone (no rug)
door: [37, 9],
entrance: [37, 9], exit: [37, 9], treasure: [42, 15], torch: [50, 10]
}
}
};
RK.activeThemeId = 'roguelike-interior';
RK.theme = function (id) {
// With no explicit id, use the active topdown pack (registry-selected + entitlement-gated).
if (!id && RK.activePackId) {
var ap = RK.activePackId('topdown');
if (ap && RK.THEMES[ap]) return RK.THEMES[ap];
}
return RK.THEMES[id || RK.activeThemeId] || null;
};
// Effective tile map = theme defaults merged with localStorage overrides from the picker.
RK.tileMap = function (id) {
var t = RK.theme(id); if (!t) return {};
var map = {};
for (var k in t.tiles) map[k] = t.tiles[k];
try {
var ov = JSON.parse(localStorage.getItem('rk_tilemap_' + t.id) || '{}');
for (var kk in ov) map[kk] = ov[kk];
} catch (_) { /* ignore */ }
return map;
};
RK.setTile = function (id, kind, col, row) {
var t = RK.theme(id); if (!t) return;
var key = 'rk_tilemap_' + t.id, ov = {};
try { ov = JSON.parse(localStorage.getItem(key) || '{}'); } catch (_) {}
ov[kind] = [col, row];
try { localStorage.setItem(key, JSON.stringify(ov)); } catch (_) {}
};
// Lazy tileset atlas per theme.
var atlases = {};
RK.themeAtlas = function (id) {
var t = RK.theme(id); if (!t || !t.tileset) return null;
if (!atlases[t.id]) {
atlases[t.id] = new RK.TilesetAtlas(t.tileset.url, { tile: t.tileset.tile, spacing: t.tileset.spacing });
}
return atlases[t.id];
};
RK.loadTheme = function (id, cb) {
var a = RK.themeAtlas(id);
if (!a) { if (cb) cb(null); return; }
a.onReady(function () { if (cb) cb(a); });
};
RK.EXTRA_APPEARANCES = {
'kenney-survivor-male': {
id: 'kenney-survivor-male',
label: 'Survivor',
kind: 'model3d',
premium: true,
pack: 'kenney-3d-characters'
},
'kenney-survivor-female': {
id: 'kenney-survivor-female',
label: 'Survivor Scout',
kind: 'model3d',
premium: true,
pack: 'kenney-3d-characters'
}
};
function normalizeEquipment(eq) {
eq = eq || {};
var out = {};
for (var k in FREE_EQUIPMENT) out[k] = eq[k] || 'none';
return out;
}
function normalizeColors(colors, tint) {
if (RK.normalizeCharColors) return RK.normalizeCharColors(colors, tint);
colors = colors || {};
var out = {};
for (var k in FREE_COLORS) out[k] = colors[k] || (k === 'base' ? (tint || FREE_COLORS[k]) : FREE_COLORS[k]);
return out;
}
RK.packAppearances = function () {
var out = [];
for (var id in RK.EXTRA_APPEARANCES) out.push(RK.EXTRA_APPEARANCES[id]);
return out;
};
function isoMale(n) {
var base = 'assets/kenney/iso-dungeon/characters/male' + n + '/Male_' + n + '_';
var run = [];
for (var i = 0; i < 10; i++) run.push(base + 'Run' + i + '.png');
return {
idle: base + 'Idle0.png',
run: run,
imageW: 48,
imageH: 92
};
}
RK.isoAssets = {
pack: 'iso-dungeon',
avatar: 'char-villager',
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
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; 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',
window: 'assets/kenney/iso-dungeon/tiles/stoneWallWindow_S.png',
windowY: 'assets/kenney/iso-dungeon/tiles/stoneWallWindow_W.png',
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
// 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 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
shelf: 'assets/kenney/iso-dungeon/tiles/woodenCrates_S.png',
crate: 'assets/kenney/iso-dungeon/tiles/woodenCrate_S.png',
chair: 'assets/kenney/iso-dungeon/tiles/chair_S.png',
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, 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)
down: isoMale(4), // SW (down-left)
left: isoMale(6), // NW (up-left)
right: isoMale(2) // SE (down-right)
},
characters: {
fallback: isoMale(3),
'char-villager': isoMale(3)
}
};
// 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',
tile: { w: 84, h: 42, imageW: 84, imageH: 98 },
tiles: {
floor: 'assets/kenney/iso-medieval/floor.png',
floor2: 'assets/kenney/iso-medieval/floor2.png',
wall: 'assets/kenney/iso-medieval/wall.png',
window: 'assets/kenney/iso-medieval/window.png',
door: 'assets/kenney/iso-medieval/door.png',
banner: 'assets/kenney/iso-medieval/banner.png',
fallback: 'assets/kenney/iso-medieval/floor.png'
},
character: RK.isoAssets.character,
directions: RK.isoAssets.directions,
characters: RK.isoAssets.characters
};
RK.threeAssets = {
pack: 'kenney-3d-characters',
models: {
'kenney-survivor-male': {
url: 'assets/generated/3d/kenney-animated-characters/survivorMaleB.glb',
clips: { idle: 'idle', run: 'run', jump: 'jump' }
},
'kenney-survivor-female': {
url: 'assets/generated/3d/kenney-animated-characters/survivorFemaleA.glb',
clips: { idle: 'idle', run: 'run', jump: 'jump' }
},
fallback: {
url: 'assets/generated/3d/kenney-animated-characters/survivorMaleB.glb',
clips: { idle: 'idle', run: 'run', jump: 'jump' }
}
}
};
// 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'] });
RK.registerPack({ id: 'roguelike-dungeon', label: 'Roguelike Dungeon', projection: 'topdown', kind: 'tiles', assets: RK.THEMES['roguelike-dungeon'] });
RK.registerPack({ id: 'iso-dungeon', label: 'Isometric Dungeon', projection: 'iso', kind: 'tiles', assets: RK.isoAssets });
RK.registerPack({ id: 'iso-medieval', label: 'Medieval Town', projection: 'iso', kind: 'tiles', assets: RK.isoMedievalAssets });
RK.registerPack({ id: 'kenney-3d-characters', label: 'Animated 3D', projection: '3d', kind: 'skin', assets: RK.threeAssets });
}
// Active-pack resolvers the renderers read (fall back to the single default if the registry is absent).
RK.activeIsoAssets = function () { return (RK.activePackAssets && RK.activePackAssets('iso')) || RK.isoAssets; };
RK.activeThreeAssets = function () { return (RK.activePackAssets && RK.activePackAssets('3d')) || RK.threeAssets; };
RK.packForProjection = function (projection) {
for (var id in RK.PACKS) {
if (RK.PACKS[id].projection === projection) return RK.PACKS[id];
}
return null;
};
RK.resolveAppearance = function (entity, projection) {
entity = entity || {};
var baseAppearance = entity.appearance || { avatar: entity.avatar || 'default', tint: 'none', equipment: FREE_EQUIPMENT };
if (RK.avatarVisuals && RK.avatarVisuals.resolve) {
return RK.avatarVisuals.resolve(baseAppearance, {
projection: projection || 'topdown',
context: 'room-entity',
entity: entity
});
}
var appearance = entity.appearance || { avatar: entity.avatar || 'default', tint: 'none', equipment: FREE_EQUIPMENT };
var avatar = appearance.avatar || entity.avatar || 'default';
if (projection === 'iso') {
return {
projection: 'iso',
pack: 'iso-dungeon',
avatar: avatar,
tint: appearance.tint || 'none',
equipment: normalizeEquipment(appearance.equipment),
colors: normalizeColors(appearance.colors, appearance.tint),
character: RK.isoAssets.character
};
}
if (projection === '3d') {
return {
projection: '3d',
pack: 'kenney-3d-characters',
avatar: avatar,
model: RK.threeAssets.models[avatar] || RK.threeAssets.models.fallback,
tint: appearance.tint || 'none',
equipment: normalizeEquipment(appearance.equipment),
colors: normalizeColors(appearance.colors, appearance.tint)
};
}
return { projection: 'topdown', avatar: avatar, appearance: appearance };
};
})(window);
+74
View File
@@ -0,0 +1,74 @@
// 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';
function TilesetAtlas(url, opts) {
opts = opts || {};
this.url = url;
this.tile = opts.tile || 16;
this.spacing = opts.spacing != null ? opts.spacing : 1;
this.margin = opts.margin || 0;
this.ready = false;
this.cols = 0;
this.rows = 0;
this._cbs = [];
var self = this;
this.img = new Image();
this.img.onload = function () {
self.ready = true;
var stride = self.tile + self.spacing;
self.cols = Math.floor((self.img.width - self.margin + self.spacing) / stride);
self.rows = Math.floor((self.img.height - self.margin + self.spacing) / stride);
var cbs = self._cbs; self._cbs = [];
cbs.forEach(function (cb) { try { cb(self); } catch (_) { /* ignore */ } });
};
this.img.onerror = function () { self.ready = false; };
this.img.src = url;
}
TilesetAtlas.prototype.onReady = function (cb) {
if (this.ready) cb(this); else this._cbs.push(cb);
};
// Source pixel of tile (col,row).
TilesetAtlas.prototype.px = function (col, row) {
var stride = this.tile + this.spacing;
return { x: this.margin + col * stride, y: this.margin + row * stride };
};
// Canvas: draw tile (col,row) at (dx,dy) scaled to `size`. Returns false if not ready.
TilesetAtlas.prototype.draw = function (ctx, col, row, dx, dy, size) {
if (!this.ready) return false;
var p = this.px(col, row);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(this.img, p.x, p.y, this.tile, this.tile, dx, dy, size, size);
return true;
};
// Canvas: draw by flat tile index (row-major across the tileset's columns).
TilesetAtlas.prototype.drawIndex = function (ctx, idx, dx, dy, size) {
if (idx < 0 || !this.ready) return false;
return this.draw(ctx, idx % this.cols, Math.floor(idx / this.cols), dx, dy, size);
};
// Pixi: a cached Texture for tile (col,row), sharing one BaseTexture (nearest-neighbour).
TilesetAtlas.prototype.texture = function (col, row) {
if (typeof PIXI === 'undefined' || !this.ready) return null;
if (!this._base) {
this._base = PIXI.BaseTexture.from(this.img);
this._base.scaleMode = PIXI.SCALE_MODES.NEAREST;
this._texCache = {};
}
var key = col + ',' + row;
if (!this._texCache[key]) {
var p = this.px(col, row);
this._texCache[key] = new PIXI.Texture(this._base, new PIXI.Rectangle(p.x, p.y, this.tile, this.tile));
}
return this._texCache[key];
};
root.RK = root.RK || {};
root.RK.TilesetAtlas = TilesetAtlas;
})(window);
+314
View File
@@ -0,0 +1,314 @@
// AvatarVisuals is the render-kit resolver for turning a saved appearance identity into a
// drawable visual for a specific projection/context. Legacy ROT screens can use fallback tiles;
// canvas-capable renderers can draw the same identity as a composed character or premium skin.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
var DEFAULT_EQUIPMENT = { body: 'none', head: 'none', shield: 'none', weapon: 'none' };
var DEFAULT_APPEARANCE = { avatar: 'default', tint: 'none', equipment: DEFAULT_EQUIPMENT };
var loading = {};
function normalize(appearance) {
if (RK.normalizeAppearance) return RK.normalizeAppearance(appearance || DEFAULT_APPEARANCE);
return DEFAULT_APPEARANCE;
}
function topdownPackFor(appearance, kind) {
if (kind === 'skin') {
var skin = RK.SKINS && RK.SKINS[appearance.avatar];
return (skin && skin.pack) || 'generated-skins';
}
if (kind === 'model3d') return 'kenney-3d-characters';
return 'roguelike-interior';
}
function kindFor(appearance, projection) {
if (!appearance) return 'legacy';
if (projection === 'iso') return 'iso';
if (projection === '3d') return 'model3d';
if (RK.isChar && RK.isChar(appearance.avatar)) return 'char';
if (RK.isSkin && RK.isSkin(appearance.avatar)) return 'skin';
if (appearance.avatar && /^kenney-/.test(appearance.avatar)) return 'model3d';
return 'legacy';
}
function fallbackTile(opts) {
opts = opts || {};
if (opts.fallbackTile) return opts.fallbackTile;
if (root.GameTiles && root.GameTiles.getPlayerTile) return root.GameTiles.getPlayerTile();
return '@';
}
function labelFor(appearance) {
if (RK.appearance) {
var info = RK.appearance(appearance);
if (info && info.label) return info.label;
}
return 'Character';
}
function tintColorFor(appearance, fallback) {
var ap = normalize(appearance);
var base = ap && ap.colors && ap.colors.base;
var tint = base || (ap && ap.tint);
if (tint && tint !== 'none' && RK.CHAR_TINTS && RK.CHAR_TINTS[tint] && RK.CHAR_TINTS[tint].color) {
return RK.CHAR_TINTS[tint].color;
}
if (RK.appearance) {
var info = RK.appearance(ap);
if (info && info.color) return info.color;
}
return fallback || null;
}
function packFor(appearance, kind, projection) {
if (projection === 'iso') return 'iso-dungeon';
if (projection === '3d') return 'kenney-3d-characters';
return topdownPackFor(appearance, kind);
}
function canUsePack(id) {
return !id || !RK.canUsePack || RK.canUsePack(id);
}
function isoCharacterFor(appearance) {
var assets = (RK.activeIsoAssets && RK.activeIsoAssets()) || RK.isoAssets || {};
var chars = assets.characters || {};
return chars[appearance.avatar] || chars.fallback || assets.character || null;
}
function modelFor(appearance) {
var assets = (RK.activeThreeAssets && RK.activeThreeAssets()) || RK.threeAssets || {};
var models = assets.models || {};
return models[appearance.avatar] || models.fallback || null;
}
function resolve(appearance, opts) {
opts = opts || {};
var ap = normalize(appearance);
var projection = opts.projection || 'legacy-rot';
// 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 @
// 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') {
var a = ap.avatar;
var known = (RK.isChar && RK.isChar(a)) || (RK.isSkin && RK.isSkin(a)) || (a && /^kenney-/.test(a));
if (!known) ap = Object.assign({}, ap, { avatar: 'char-villager' });
}
var kind = kindFor(ap, projection);
var pack = packFor(ap, kind, projection);
var visual = {
appearance: ap,
kind: kind,
projection: projection,
context: opts.context || 'player',
label: labelFor(ap),
pack: pack,
allowed: canUsePack(pack),
fallbackTile: fallbackTile(opts),
canvas: kind === 'char' || kind === 'skin',
entity: opts.entity || null
};
if (projection === 'iso') {
visual.assets = RK.isoAssets || null;
visual.character = isoCharacterFor(ap);
visual.canvas = false;
} else if (projection === '3d') {
visual.assets = RK.threeAssets || null;
visual.model = modelFor(ap);
visual.canvas = false;
visual.three = true;
}
return visual;
}
function rememberLoad(key, start, onReady) {
if (loading[key]) {
if (onReady) loading[key].push(onReady);
return;
}
loading[key] = onReady ? [onReady] : [];
start(function () {
var cbs = loading[key] || [];
delete loading[key];
cbs.forEach(function (cb) { try { cb(); } catch (_) { /* ignore */ } });
});
}
function ensureCanvasReady(visual, onReady) {
visual = visual && visual.appearance ? visual : resolve(visual);
if (!visual.allowed) return false;
if (visual.kind === 'char') {
if (RK.charAtlas && RK.charAtlas()) return true;
if (!RK.loadCharAtlas) return false;
rememberLoad('char-atlas', function (done) { RK.loadCharAtlas(done); }, onReady);
return false;
}
if (visual.kind === 'skin') {
if (RK.skinSheet && RK.skinSheet(visual.appearance.avatar)) return true;
if (!RK.loadSkin) return false;
rememberLoad('skin:' + visual.appearance.avatar, function (done) {
var rec = RK.loadSkin(visual.appearance.avatar);
if (rec && rec.cbs) rec.cbs.push(done);
}, onReady);
return false;
}
return false;
}
function drawCharIcon(ctx, visual, x, y, size) {
if (!RK.drawCharCompositeCanvas) return false;
return RK.drawCharCompositeCanvas(ctx, visual.appearance, x, y, size);
}
function drawSkinIcon(ctx, visual, x, y, size) {
var rec = RK.skinSheet && RK.skinSheet(visual.appearance.avatar);
var skin = RK.SKINS && RK.SKINS[visual.appearance.avatar];
if (!rec || !skin) return false;
var row = (skin.dirRows && skin.dirRows.down) || 0;
var dh = size;
var dw = dh * (skin.frameW / skin.frameH);
ctx.imageSmoothingEnabled = true;
ctx.drawImage(rec.img, 0, row * skin.frameH, skin.frameW, skin.frameH, x + (size - dw) / 2, y, dw, dh);
return true;
}
function drawIcon(ctx, visual, rect, opts) {
opts = opts || {};
visual = visual && visual.appearance ? visual : resolve(visual, opts);
if (!ctx || !rect || !ensureCanvasReady(visual, opts.onReady)) return false;
var boxW = rect.w || rect.size || 32;
var boxH = rect.h || rect.size || 32;
var natural = Math.min(boxW, boxH);
var legend = visual.context === 'legend' || opts.context === 'legend';
var scale = opts.scale || (legend ? 0.78 : 1);
var size = opts.size || Math.max(1, Math.round(natural * scale));
var offsetX = opts.offsetX || 0;
var offsetY = opts.offsetY != null ? opts.offsetY : (legend ? Math.round(natural * 0.08) : 0);
var x = rect.x + Math.max(0, (boxW - size) / 2) + offsetX;
var y = rect.y + Math.max(0, (boxH - size) / 2) + offsetY;
ctx.clearRect(rect.x, rect.y, boxW, boxH);
if (visual.kind === 'char') return drawCharIcon(ctx, visual, x, y, size);
if (visual.kind === 'skin') return drawSkinIcon(ctx, visual, x, y, size);
return false;
}
function drawTopdownChar(ctx, visual, entity, viewport, opts) {
opts = opts || {};
var ch = RK.CHARS && RK.CHARS[visual.appearance.avatar];
if (!ch || !RK.charFrame || !RK.drawCharTileCanvas) return false;
var cell = viewport.cell || 32;
var e = {
id: entity.id || 'avatar',
x: entity.x || 0,
y: entity.y || 0,
facing: entity.facing || 'down'
};
var frame = RK.charFrame(ch, e, opts.now || Date.now());
var dw = cell * (opts.scale || 1.8);
var dh = dw * frame.squash;
var cx = viewport.screenX * cell + cell / 2;
var dy = (viewport.screenY * cell + cell) - dh + frame.bob;
var ap = RK.charAppearance({ avatar: visual.appearance.avatar, appearance: visual.appearance });
ctx.imageSmoothingEnabled = false;
if (entity.you) {
ctx.strokeStyle = 'rgba(255,255,255,0.85)';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.ellipse(cx, viewport.screenY * cell + cell - 2, dw * 0.3, cell * 0.16, 0, 0, Math.PI * 2);
ctx.stroke();
}
function drawComposite(dx, dy2) {
RK.drawCharTileCanvas(ctx, ch.frame, ap.tint, dx, dy2, dw, dh, ap.colors, 'base');
RK.charOverlayParts(ap).forEach(function (part) {
RK.drawCharTileCanvas(ctx, part.frame, part.tint, dx, dy2, dw, dh, part.colorable ? ap.colors : null, part.slot);
});
}
if (frame.flip) {
ctx.save();
ctx.translate(cx + dw / 2, dy);
ctx.scale(-1, 1);
drawComposite(0, 0);
ctx.restore();
} else {
drawComposite(cx - dw / 2, dy);
}
if (entity.label) {
ctx.fillStyle = '#d7dbe0';
ctx.font = '11px monospace';
ctx.textAlign = 'center';
ctx.fillText(entity.label, cx, dy - 2);
}
return true;
}
function drawTopdownSkin(ctx, visual, entity, viewport, opts) {
opts = opts || {};
var rec = RK.skinSheet && RK.skinSheet(visual.appearance.avatar);
var skin = RK.SKINS && RK.SKINS[visual.appearance.avatar];
if (!rec || !skin || !RK.skinFrame) return false;
var cell = viewport.cell || 32;
var e = {
id: entity.id || 'avatar-skin',
x: entity.x || 0,
y: entity.y || 0,
facing: entity.facing || 'down'
};
var frame = RK.skinFrame(skin, e, opts.now || Date.now());
var dh = cell * (skin.scale || 1.7);
var dw = dh * (skin.frameW / skin.frameH);
var cx = viewport.screenX * cell + cell / 2;
var dx = cx - dw / 2;
var dy = (viewport.screenY * cell + cell) - dh;
ctx.imageSmoothingEnabled = true;
var midY = dy + dh * 0.45;
var halo = ctx.createRadialGradient(cx, midY, 0, cx, midY, dw * 0.8);
halo.addColorStop(0, 'rgba(255,226,180,0.30)');
halo.addColorStop(1, 'rgba(255,226,180,0)');
ctx.fillStyle = halo;
ctx.beginPath();
ctx.arc(cx, midY, dw * 0.8, 0, Math.PI * 2);
ctx.fill();
if (entity.you) {
ctx.strokeStyle = 'rgba(255,255,255,0.85)';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.ellipse(cx, viewport.screenY * cell + cell - 2, dw * 0.3, cell * 0.16, 0, 0, Math.PI * 2);
ctx.stroke();
}
ctx.drawImage(rec.img, frame.col * skin.frameW, frame.row * skin.frameH, skin.frameW, skin.frameH, dx, dy, dw, dh);
if (entity.label) {
ctx.fillStyle = '#d7dbe0';
ctx.font = '11px monospace';
ctx.textAlign = 'center';
ctx.fillText(entity.label, cx, dy - 2);
}
return true;
}
function drawTopdownWorld(ctx, visual, entity, viewport, opts) {
opts = opts || {};
visual = visual && visual.appearance ? visual : resolve(visual, opts);
if (!ctx || !entity || !viewport || !visual.allowed || !ensureCanvasReady(visual, opts.onReady)) return false;
if (visual.kind === 'char') return drawTopdownChar(ctx, visual, entity, viewport, opts);
if (visual.kind === 'skin') return drawTopdownSkin(ctx, visual, entity, viewport, opts);
return false;
}
RK.avatarVisuals = {
DEFAULT_APPEARANCE: DEFAULT_APPEARANCE,
normalize: normalize,
kindFor: kindFor,
resolve: resolve,
tintColorFor: tintColorFor,
ensureCanvasReady: ensureCanvasReady,
drawIcon: drawIcon,
drawTopdownWorld: drawTopdownWorld
};
RK.resolveAvatarVisual = resolve;
})(window);
+46
View File
@@ -0,0 +1,46 @@
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
// Pet Cats Pack (CC-0). Each idle strip is 10 frames of 50x50 laid out horizontally.
var FRAMES = 10, FW = 50, FH = 50, FRAME_MS = 150;
var CATS = ['cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6'];
var images = {};
function imgFor(id) {
if (!CATS.includes(id)) id = 'cat3';
if (!images[id]) {
var im = new Image();
im.src = 'assets/cats/' + id + '-idle.png';
images[id] = im;
}
return images[id];
}
RK.catIds = function () { return CATS.slice(); };
RK.randomCatId = function () { return CATS[Math.floor(Math.random() * CATS.length)]; };
RK.isCat = function (id) { return CATS.indexOf(id) !== -1; };
// Draw an animated cat centered in its cell, feet near the bottom of the tile. Flips to face left.
RK.drawCatCanvas = function (ctx, e, cell, now) {
var im = imgFor(e.catSprite || 'cat3');
if (!im.complete || !im.naturalWidth) return false;
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.
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
ctx.save();
ctx.imageSmoothingEnabled = false;
if (e.facing === 'left') {
ctx.translate(dx + size, dy); ctx.scale(-1, 1);
ctx.drawImage(im, sx, 0, FW, FH, 0, 0, size, size);
} else {
ctx.drawImage(im, sx, 0, FW, FH, dx, dy, size, size);
}
ctx.restore();
return true;
};
})(window);
+214
View File
@@ -0,0 +1,214 @@
// ChainAmbience: the live chain, drifting around the edges of a stage.
//
// 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.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
var STYLE_ID = 'rk-chain-ambience-style';
var CSS = [
'.rk-chain-amb{position:absolute;inset:0;pointer-events:none;overflow:hidden;z-index:9;',
' font-family:ui-monospace,SFMono-Regular,Menlo,monospace;}',
'.rk-chain-amb .rk-cm{position:absolute;white-space:nowrap;font-size:11px;letter-spacing:.09em;',
' color:#7fe3c0;opacity:0;text-shadow:0 0 8px rgba(80,220,180,.45);will-change:transform,opacity;}',
'.rk-chain-amb .rk-cm.rk-drift{animation:rk-cm-drift var(--rk-cm-life,9s) linear forwards;}',
'@keyframes rk-cm-drift{',
' 0%{opacity:0;transform:translate3d(0,0,0) scale(.94);}',
' 16%{opacity:var(--rk-cm-peak,.42);}',
' 76%{opacity:var(--rk-cm-peak,.42);}',
' 100%{opacity:0;transform:translate3d(var(--rk-cm-dx,0px),var(--rk-cm-dy,-26px),0) scale(1);}}',
'.rk-chain-amb .rk-chain-readout{position:absolute;left:10px;bottom:8px;font-size:10px;',
' line-height:1.5;color:#5f7f96;letter-spacing:.1em;opacity:.72;transition:color .5s ease;}',
'.rk-chain-amb .rk-chain-readout b{display:block;color:#8fd8b6;font-weight:400;font-size:11px;}',
'.rk-chain-amb .rk-chain-readout .rk-chain-hash{display:block;color:#4d6a80;word-break:break-all;max-width:34ch;}',
'.rk-chain-amb .rk-chain-readout.rk-fresh b{color:#b6f7d6;text-shadow:0 0 10px rgba(120,240,190,.55);}',
'.rk-chain-amb .rk-chain-ripple{position:absolute;inset:0;border:1px solid rgba(127,227,192,0);',
' border-radius:inherit;}',
'.rk-chain-amb .rk-chain-ripple.rk-go{animation:rk-chain-ripple 1.5s ease-out forwards;}',
'@keyframes rk-chain-ripple{',
' 0%{border-color:rgba(127,227,192,.55);box-shadow:inset 0 0 0 rgba(127,227,192,.4);}',
' 100%{border-color:rgba(127,227,192,0);box-shadow:inset 0 0 46px rgba(127,227,192,0);}}',
'@media (prefers-reduced-motion:reduce){',
' .rk-chain-amb .rk-cm{display:none}',
' .rk-chain-amb .rk-chain-ripple.rk-go{animation:none}}'
].join('\n');
function ensureStyle(doc) {
if (doc.getElementById(STYLE_ID)) return;
var el = doc.createElement('style');
el.id = STYLE_ID;
el.textContent = CSS;
doc.head.appendChild(el);
}
function reducedMotion() {
try { return root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches; }
catch (_) { return false; }
}
function ChainAmbience(host, opts) {
opts = opts || {};
var doc = root.document;
ensureStyle(doc);
this.host = host;
this.doc = doc;
this.tip = { height: null, hash: null, difficulty: null, txPoolSize: null };
this.motes = 0;
this.maxMotes = opts.maxMotes || 9;
this.spawnMs = opts.spawnMs || 1200;
this.el = doc.createElement('div');
this.el.className = 'rk-chain-amb';
this.el.setAttribute('aria-hidden', 'true'); // decoration; the readout below is the a11y copy
this.ripple = doc.createElement('div');
this.ripple.className = 'rk-chain-ripple';
this.el.appendChild(this.ripple);
this.readout = doc.createElement('div');
this.readout.className = 'rk-chain-readout';
this.heightEl = doc.createElement('b');
this.hashEl = doc.createElement('span');
this.hashEl.className = 'rk-chain-hash';
this.readout.appendChild(this.heightEl);
this.readout.appendChild(this.hashEl);
this.el.appendChild(this.readout);
host.appendChild(this.el);
var self = this;
this.timer = root.setInterval(function () { self._spawn(); }, this.spawnMs);
// 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();
};
doc.addEventListener('visibilitychange', this._onVisibility);
}
ChainAmbience.prototype._clearMotes = function () {
if (!this.el) return;
var existing = this.el.querySelectorAll('.rk-cm');
for (var i = 0; i < existing.length; i++) existing[i].remove();
this.motes = 0;
};
// Fragments of the real top-block hash, plus the occasional height/difficulty token, so the
// drifting text is actual chain data rather than decorative gibberish.
ChainAmbience.prototype._fragment = function () {
var t = this.tip;
var roll = Math.random();
if (t.hash && roll < 0.68) {
var start = Math.floor(Math.random() * (t.hash.length - 8));
return t.hash.substr(start, 4 + Math.floor(Math.random() * 5));
}
if (t.height != null && roll < 0.86) return '#' + t.height;
if (t.difficulty != null && roll < 0.94) return 'diff ' + Math.round(t.difficulty / 1e6) + 'M';
if (t.txPoolSize != null) return 'mempool ' + t.txPoolSize;
return t.height != null ? '#' + t.height : '';
};
ChainAmbience.prototype._spawn = function (burst) {
if (!this.el || reducedMotion()) return;
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;
var doc = this.doc;
var m = doc.createElement('span');
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 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;
if (edge === 0) { m.style.left = along + '%'; m.style.top = '3%'; dy = -18; }
else if (edge === 1) { m.style.left = along + '%'; m.style.bottom = '4%'; dy = 20; }
else if (edge === 2) { m.style.left = '2%'; m.style.top = along + '%'; dx = -22; }
else { m.style.right = '2%'; m.style.top = along + '%'; dx = 22; }
dx += (Math.random() - 0.5) * 14;
dy += (Math.random() - 0.5) * 10;
m.style.setProperty('--rk-cm-dx', dx.toFixed(1) + 'px');
m.style.setProperty('--rk-cm-dy', dy.toFixed(1) + 'px');
m.style.setProperty('--rk-cm-life', (7 + Math.random() * 5).toFixed(1) + 's');
m.style.setProperty('--rk-cm-peak', (burst ? 0.62 : 0.30 + Math.random() * 0.22).toFixed(2));
if (burst) m.style.color = '#b6f7d6';
var self = this;
m.addEventListener('animationend', function () {
if (m.parentNode) m.parentNode.removeChild(m);
self.motes--;
});
this.motes++;
this.el.appendChild(m);
};
// Feed it the `blockheight` payload. A height increase is treated as "a block landed" and gets
// the ripple + a burst of fragments; a repeat of the same height just refreshes the readout.
ChainAmbience.prototype.setTip = function (data) {
if (!this.el || !data) return;
var height = Number(data.blockHeight);
if (!isFinite(height)) return;
var advanced = this.tip.height != null && height > this.tip.height;
this.tip.height = height;
if (typeof data.hash === 'string') this.tip.hash = data.hash;
if (data.difficulty != null) this.tip.difficulty = Number(data.difficulty);
if (data.txPoolSize != null) this.tip.txPoolSize = Number(data.txPoolSize);
this.heightEl.textContent = 'BLOCK ' + height;
this.hashEl.textContent = this.tip.hash
? this.tip.hash.slice(0, 16) + '…' + this.tip.hash.slice(-8)
: '';
if (!advanced) return;
var self = this;
this.readout.classList.add('rk-fresh');
this.ripple.classList.remove('rk-go');
// Force a reflow so the animation restarts on consecutive blocks.
void this.ripple.offsetWidth;
this.ripple.classList.add('rk-go');
for (var i = 0; i < 5; i++) {
(function (n) { root.setTimeout(function () { self._spawn(true); }, n * 110); })(i);
}
if (this._freshTimer) root.clearTimeout(this._freshTimer);
this._freshTimer = root.setTimeout(function () {
if (self.readout) self.readout.classList.remove('rk-fresh');
}, 2600);
};
ChainAmbience.prototype.destroy = function () {
if (this.timer) root.clearInterval(this.timer);
this.timer = null;
if (this._onVisibility) this.doc.removeEventListener('visibilitychange', this._onVisibility);
this._onVisibility = null;
if (this._freshTimer) root.clearTimeout(this._freshTimer);
this._freshTimer = null;
if (this.el && this.el.parentNode) this.el.parentNode.removeChild(this.el);
this.el = null;
this.readout = null;
this.ripple = null;
};
RK.ChainAmbience = ChainAmbience;
RK.mountChainAmbience = function (host, opts) {
if (!host || !root.document) return null;
try { return new ChainAmbience(host, opts); }
catch (e) {
if (root.console) console.warn('chain ambience unavailable:', e && e.message);
return null;
}
};
})(typeof window !== 'undefined' ? window : this);
+899
View File
@@ -0,0 +1,899 @@
// Character customization -- a persistent "appearance identity" the player picks once and carries
// across the tavern (and, next, single-player / PvP / dead-kernel). The saved shape is structured
// so premium character packs can add their own tint/equipment catalogs without changing join flow.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
var DEFAULT_EQUIPMENT = { body: 'none', head: 'none', shield: 'none', weapon: 'none' };
var DEFAULT_COLORS = { base: 'none', skin: 'natural', hair: 'copper', body: 'none', head: 'none', shield: 'none', weapon: 'none' };
var thumbImages = {};
var thumbBounds = {};
function cloneEquipment(eq) {
eq = eq || {};
var out = {};
var slots = (RK.CHAR_EQUIPMENT_SLOTS || ['body', 'head', 'shield', 'weapon']);
slots.forEach(function (slot) { out[slot] = eq[slot] || 'none'; });
return out;
}
function cloneColors(colors, legacyTint) {
if (RK.normalizeCharColors) return RK.normalizeCharColors(colors, legacyTint);
colors = colors || {};
var out = {};
for (var k in DEFAULT_COLORS) out[k] = colors[k] || (k === 'base' ? (legacyTint || DEFAULT_COLORS[k]) : DEFAULT_COLORS[k]);
return out;
}
function baseAppearances() {
var list = [
{ id: 'default', label: 'Adventurer', kind: 'color', color: '#9aa4b2' },
{ id: 'green', label: 'Verdant', kind: 'color', color: '#3fb950' },
{ id: 'amber', label: 'Amber', kind: 'color', color: '#d29922' },
{ id: 'red', label: 'Crimson', kind: 'color', color: '#f85149' }
];
for (var cid in (RK.CHARS || {})) {
var c = RK.CHARS[cid];
list.push({ id: cid, label: c.label || cid, kind: 'char' });
}
for (var id in (RK.SKINS || {})) {
var s = RK.SKINS[id];
list.push({ id: id, label: s.label || id, kind: 'skin', premium: !!s.premium, pack: s.pack || 'generated-skins' });
}
if (RK.packAppearances) {
RK.packAppearances().forEach(function (a) { list.push(a); });
}
return list;
}
function baseAppearance(id) {
var all = baseAppearances();
for (var i = 0; i < all.length; i++) if (all[i].id === id) return all[i];
return all[0];
}
// The base appearance catalog. Kept for existing callers that expect a flat list.
RK.appearances = baseAppearances;
RK.normalizeAppearance = function (input) {
if (input && input.appearance && !input.avatar) input = input.appearance;
if (typeof input === 'string') input = { avatar: input };
input = input || {};
var avatar = input.avatar || input.id || 'default';
if (!baseAppearance(avatar) || baseAppearance(avatar).id !== avatar) avatar = 'default';
var base = baseAppearance(avatar);
var isChar = !!(RK.isChar && RK.isChar(avatar));
var isModel = base && base.kind === 'model3d';
var tint = 'none';
var equipment = cloneEquipment(DEFAULT_EQUIPMENT);
var colors = null;
if (isChar || isModel) {
colors = cloneColors(input.colors, input.tint);
tint = colors.base;
}
if (isChar) {
equipment = RK.normalizeCharEquipment ? RK.normalizeCharEquipment(input.equipment) : cloneEquipment(input.equipment);
}
var out = { avatar: avatar, tint: tint, equipment: equipment };
if (isChar || isModel) out.colors = colors;
return out;
};
RK.appearance = function (input) {
var ap = RK.normalizeAppearance(input);
var base = baseAppearance(ap.avatar);
var label = base.label || base.id;
if (base.kind === 'char' && ap.colors && ap.colors.base && ap.colors.base !== 'none' && RK.CHAR_TINTS && RK.CHAR_TINTS[ap.colors.base]) {
label += ' / ' + RK.CHAR_TINTS[ap.colors.base].label;
}
return {
id: ap.avatar,
label: label,
kind: base.kind,
color: base.color,
premium: !!base.premium,
appearance: ap
};
};
// Identity persistence (client-side for now; server/DB persistence is the next step so it
// follows the player across modes and survives device changes).
RK.saveIdentity = function (appearance) {
try { localStorage.setItem('rk_identity', JSON.stringify({ appearance: RK.normalizeAppearance(appearance) })); } catch (_) { /* ignore */ }
};
RK.loadIdentity = function () {
try {
var raw = JSON.parse(localStorage.getItem('rk_identity') || 'null');
if (!raw) return null;
return { appearance: RK.normalizeAppearance(raw.appearance || raw) };
} catch (_) { return null; }
};
function projectionToMode(projection) {
if (projection === 'iso') return 'iso';
if (projection === '3d') return '3d';
if (projection === 'ascii') return 'ascii';
return 'tiles';
}
function projectionForMode(mode) {
if (mode === 'iso' || mode === '3d' || mode === 'ascii') return mode;
return 'topdown';
}
function isoAvatarId() {
return (RK.isoAssets && RK.isoAssets.avatar) || 'char-villager';
}
function hasIsoCharacter(a) {
return !!(a && a.kind === 'char' && a.id === isoAvatarId());
}
function appearanceVisibleInProjection(a, projection) {
if (!a) return false;
if (projection === 'topdown') return a.kind === 'color' || a.kind === 'char' || a.kind === 'skin';
if (projection === 'iso') return hasIsoCharacter(a);
if (projection === '3d') return a.kind === 'model3d';
if (projection === 'ascii') return a.kind === 'color';
return a.kind === 'color';
}
function loadThumbImage(url, onReady) {
if (!url) return null;
if (thumbImages[url]) return thumbImages[url];
var rec = thumbImages[url] = { ready: false, error: false, img: new Image() };
rec.img.onload = function () { rec.ready = true; if (onReady) onReady(); };
rec.img.onerror = function () { rec.error = true; };
rec.img.src = url;
return rec;
}
function tintColorForThumb(a, draft, projection) {
if (projection === 'iso') return null;
var source = {};
var d = draft || {};
for (var dk in d) source[dk] = d[dk];
source.avatar = a.id;
if (a.kind === 'color') return a.color;
if (RK.avatarVisuals && RK.avatarVisuals.tintColorFor) return RK.avatarVisuals.tintColorFor(source, '#9aa4b2');
return '#9aa4b2';
}
function isoCharacterForThumb(a, draft) {
var source = {};
var d = draft || {};
for (var dk in d) source[dk] = d[dk];
source.avatar = a.id;
if (RK.avatarVisuals && RK.avatarVisuals.resolve) {
var visual = RK.avatarVisuals.resolve(source, { projection: 'iso', context: 'customizer' });
if (visual && visual.character) return visual.character;
}
var chars = RK.isoAssets && RK.isoAssets.characters;
return (chars && (chars[a.id] || chars.fallback)) || (RK.isoAssets && RK.isoAssets.character) || null;
}
function isoSkinTintForDraft(draft) {
var colors = cloneColors(draft && draft.colors, draft && draft.tint);
if (!colors.skin || colors.skin === 'natural') return null;
var tone = RK.CHAR_SKIN_TONES && RK.CHAR_SKIN_TONES[colors.skin];
return (tone && tone.color) || null;
}
function imageBounds(img) {
var key = img && img.src;
if (!img || !key) return null;
if (thumbBounds[key]) return thumbBounds[key];
var w = img.naturalWidth || img.width;
var h = img.naturalHeight || img.height;
var cv = document.createElement('canvas');
cv.width = w;
cv.height = h;
var ctx = cv.getContext('2d');
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, w, h).data;
var minX = w, minY = h, maxX = -1, maxY = -1;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
if (data[(y * w + x) * 4 + 3] < 8) continue;
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
}
thumbBounds[key] = maxX < minX ? { x: 0, y: 0, w: w, h: h } : { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
return thumbBounds[key];
}
function drawTintedImage(ctx, img, bounds, x, y, w, h, tint) {
bounds = bounds || { x: 0, y: 0, w: img.naturalWidth || img.width, h: img.naturalHeight || img.height };
if (!tint) {
ctx.drawImage(img, bounds.x, bounds.y, bounds.w, bounds.h, x, y, w, h);
return;
}
var cv = document.createElement('canvas');
cv.width = bounds.w;
cv.height = bounds.h;
var tctx = cv.getContext('2d');
tctx.drawImage(img, bounds.x, bounds.y, bounds.w, bounds.h, 0, 0, bounds.w, bounds.h);
tctx.globalCompositeOperation = 'source-atop';
tctx.globalAlpha = 0.42;
tctx.fillStyle = tint;
tctx.fillRect(0, 0, cv.width, cv.height);
tctx.globalAlpha = 1;
tctx.globalCompositeOperation = 'source-over';
ctx.drawImage(cv, x, y, w, h);
}
function drawProjectionThumb(ctx, a, draft, projection, onReady) {
var color = tintColorForThumb(a, draft, projection);
ctx.clearRect(0, 0, 72, 80);
if (projection === 'ascii') {
ctx.fillStyle = color || '#9aa4b2';
ctx.font = '42px monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('@', 36, 43);
return;
}
if (projection === 'iso') {
ctx.imageSmoothingEnabled = true;
ctx.fillStyle = '#705842';
ctx.beginPath();
ctx.moveTo(36, 54);
ctx.lineTo(62, 42);
ctx.lineTo(36, 30);
ctx.lineTo(10, 42);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = 'rgba(255,255,255,0.22)';
ctx.stroke();
var ch = isoCharacterForThumb(a, draft);
var rec = loadThumbImage(ch && ch.idle, onReady);
if (rec && rec.ready) {
var b = imageBounds(rec.img);
var dh = 52;
var dw = dh * (b.w / b.h);
drawTintedImage(ctx, rec.img, b, 36 - dw / 2, 74 - dh, dw, dh, isoSkinTintForDraft(draft));
} else {
ctx.fillStyle = color || '#9aa4b2';
ctx.beginPath();
ctx.ellipse(36, 37, 8, 16, 0, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#0a0c0f';
ctx.fillRect(32, 34, 8, 3);
}
return;
}
if (projection === '3d') {
ctx.imageSmoothingEnabled = true;
ctx.fillStyle = color || '#64748b';
ctx.beginPath();
ctx.ellipse(36, 45, 17, 24, 0, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.28)';
ctx.beginPath();
ctx.ellipse(29, 34, 6, 9, -0.5, 0, Math.PI * 2);
ctx.fill();
if (a.kind === 'model3d') {
ctx.fillStyle = '#d7dbe0';
ctx.font = '15px monospace';
ctx.textAlign = 'center';
ctx.fillText('3D', 36, 49);
}
return;
}
}
function drawBaseThumb(ctx, a, draft, projection, onReady) {
ctx.clearRect(0, 0, 72, 80);
if (projection && projection !== 'topdown') {
drawProjectionThumb(ctx, a, draft, projection, onReady);
return;
}
if (a.kind === 'color') {
ctx.beginPath(); ctx.arc(36, 44, 21, 0, Math.PI * 2);
ctx.fillStyle = a.color; ctx.fill();
ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(255,255,255,0.3)'; ctx.stroke();
return;
}
if (a.kind === 'char') {
var at = RK.charAtlas && RK.charAtlas();
if (!at) {
RK.loadCharAtlas(onReady);
ctx.fillStyle = '#666'; ctx.font = '11px monospace'; ctx.textAlign = 'center'; ctx.fillText('...', 36, 44);
return;
}
var source = {};
var d = draft || {};
for (var dk in d) source[dk] = d[dk];
source.avatar = a.id;
var ap = RK.normalizeAppearance(source);
if (!RK.drawCharCompositeCanvas(ctx, ap, 1, 8, 70)) {
RK.loadCharAtlas(onReady);
ctx.fillStyle = '#666'; ctx.fillText('...', 36, 44);
}
return;
}
if (a.kind === 'model3d') {
ctx.beginPath(); ctx.arc(36, 43, 21, 0, Math.PI * 2);
ctx.fillStyle = '#64748b'; ctx.fill();
ctx.fillStyle = '#d7dbe0'; ctx.font = '18px monospace'; ctx.textAlign = 'center'; ctx.fillText('3D', 36, 49);
return;
}
var rec = RK.skinSheet(a.id);
if (!rec) {
var r = RK.loadSkin(a.id);
if (r && r.cbs && onReady) r.cbs.push(onReady);
ctx.fillStyle = '#666'; ctx.font = '11px monospace'; ctx.textAlign = 'center';
ctx.fillText('...', 36, 44);
return;
}
var s = RK.SKINS[a.id];
var row = (s.dirRows && s.dirRows.down) || 0;
var dh = 72, dw = dh * (s.frameW / s.frameH);
ctx.imageSmoothingEnabled = true;
ctx.drawImage(rec.img, 0, row * s.frameH, s.frameW, s.frameH, 36 - dw / 2, 80 - dh, dw, dh);
}
function thumbCanvas(a, getDraft, redraw) {
var cv = document.createElement('canvas');
cv.width = 72; cv.height = 80;
cv.style.cssText = 'display:block;margin:0 auto;image-rendering:pixelated;';
var ctx = cv.getContext('2d');
function draw() {
var d = getDraft && getDraft();
var projection = (d && d.__projection) || 'topdown';
drawBaseThumb(ctx, a, d, projection, draw);
}
draw();
if (redraw) redraw.push(draw);
return cv;
}
function optionTileCanvas(slot, item, draft, redraw) {
var cv = document.createElement('canvas');
cv.width = 52; cv.height = 52;
cv.style.cssText = 'display:block;margin:0 auto 4px;image-rendering:pixelated;';
var ctx = cv.getContext('2d');
function draw() {
ctx.clearRect(0, 0, 52, 52);
if (!item || item.frame == null) {
ctx.strokeStyle = 'rgba(255,255,255,0.35)';
ctx.beginPath(); ctx.moveTo(17, 26); ctx.lineTo(35, 26); ctx.stroke();
return;
}
var colorable = item.colorable === true;
var tint = colorable ? ((draft.colors && draft.colors[slot]) || draft.tint) : 'none';
var colors = colorable ? draft.colors : null;
if (!RK.drawCharTileCanvas || !RK.drawCharTileCanvas(ctx, item.frame, tint, 2, 2, 48, 48, colors, slot)) {
RK.loadCharAtlas(draw);
ctx.fillStyle = '#666'; ctx.font = '11px monospace'; ctx.textAlign = 'center'; ctx.fillText('...', 26, 30);
}
}
draw();
if (redraw) redraw.push(draw);
return cv;
}
function ensureCustomizeStyle() {
if (document.getElementById('rk-customize-style')) return;
var style = document.createElement('style');
style.id = 'rk-customize-style';
style.textContent = [
'.rk-customize{position:fixed;inset:0;z-index:9999;background:rgba(4,6,8,.94);color:#d7dbe0;font-family:ui-monospace,monospace;overflow:hidden;}',
'.rk-customize *{box-sizing:border-box;letter-spacing:0;}',
'.rk-customize-shell{height:100%;max-width:1080px;margin:0 auto;padding:12px;display:grid;grid-template-rows:auto minmax(0,1fr);gap:10px;}',
'.rk-customize-top{display:flex;align-items:center;justify-content:space-between;gap:10px;border-bottom:1px solid #202832;padding-bottom:10px;}',
'.rk-customize-title{font-size:15px;font-weight:700;color:#f0f3f6;overflow-wrap:anywhere;}',
'.rk-customize-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;justify-content:flex-end;}',
'.rk-customize-body{min-height:0;display:grid;grid-template-columns:168px minmax(0,1fr);gap:12px;}',
'.rk-customize-preview{align-self:start;position:sticky;top:0;border:1px solid #26303b;background:#0b0f14;border-radius:6px;padding:10px;}',
'.rk-customize-preview canvas{display:block;width:100%;height:auto;image-rendering:pixelated;background:#090c10;border:1px solid #2a313a;border-radius:6px;}',
'.rk-customize-name{font-size:12px;font-weight:700;color:#f0f3f6;margin-top:8px;overflow-wrap:anywhere;}',
'.rk-customize-meta{font-size:11px;color:#8b949e;margin-top:4px;overflow-wrap:anywhere;}',
'.rk-customize-content{min-width:0;overflow:auto;padding-right:4px;scrollbar-gutter:stable;}',
'.rk-customize-section{margin-bottom:12px;}',
'.rk-customize-section h3{margin:0 0 8px;font-size:12px;line-height:1.2;color:#9aa4b2;font-weight:700;text-transform:uppercase;}',
'.rk-mode-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(96px,1fr));gap:6px;}',
'.rk-mode-card{min-width:0;border:2px solid #2a313a;border-radius:6px;background:#11161c;color:#c7ccd4;cursor:pointer;padding:7px 8px;font:inherit;text-align:left;display:grid;gap:2px;}',
'.rk-mode-card:hover{border-color:#566274;background:#151b22;}',
'.rk-mode-card.is-selected{border-color:#3fb950;box-shadow:0 0 0 1px rgba(63,185,80,.3) inset;}',
'.rk-mode-card.is-locked{opacity:.5;cursor:not-allowed;}',
'.rk-mode-label{font-size:12px;font-weight:700;color:#dce2ea;overflow-wrap:anywhere;}',
'.rk-mode-status{font-size:10px;color:#8b949e;overflow-wrap:anywhere;}',
'.rk-avatar-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(78px,1fr));gap:6px;}',
'.rk-option-card{min-width:0;min-height:92px;border:2px solid #2a313a;border-radius:6px;background:#11161c;color:#c7ccd4;cursor:pointer;padding:6px;font:inherit;font-size:10px;text-align:center;}',
'.rk-option-card:hover{border-color:#566274;background:#151b22;}',
'.rk-option-card.is-selected{border-color:#3fb950;box-shadow:0 0 0 1px rgba(63,185,80,.3) inset;}',
'.rk-option-card.is-locked{opacity:.48;cursor:not-allowed;}',
'.rk-option-card canvas{max-width:60px;width:100%;height:auto;}',
'.rk-option-label{margin-top:5px;line-height:1.2;overflow-wrap:anywhere;color:#d0d6de;}',
'.rk-customize-row{display:grid;grid-template-columns:72px minmax(0,1fr);gap:8px;align-items:start;margin-bottom:8px;}',
'.rk-row-label{font-size:11px;color:#9aa4b2;padding-top:8px;overflow-wrap:anywhere;}',
'.rk-row-options{display:flex;gap:6px;flex-wrap:wrap;min-width:0;}',
'.rk-swatch,.rk-equip-option{border:2px solid #2a313a;border-radius:6px;background:#11161c;color:#c7ccd4;cursor:pointer;font:inherit;font-size:10px;}',
'.rk-swatch{width:58px;min-height:50px;padding:5px;}',
'.rk-equip-option{width:64px;min-height:68px;padding:4px;}',
'.rk-swatch:hover,.rk-equip-option:hover{border-color:#566274;background:#151b22;}',
'.rk-swatch.is-selected,.rk-equip-option.is-selected{border-color:#3fb950;box-shadow:0 0 0 1px rgba(63,185,80,.3) inset;}',
'.rk-swatch-dot{display:block;width:20px;height:20px;margin:0 auto 4px;border-radius:50%;border:1px solid rgba(255,255,255,.35);}',
'.rk-none-dot{background:linear-gradient(135deg,#171c22 0,#171c22 45%,#9aa4b2 47%,#9aa4b2 53%,#171c22 55%,#171c22 100%);}',
'.rk-button{font:inherit;border-radius:6px;padding:7px 12px;cursor:pointer;font-weight:700;}',
'.rk-save{border:0;background:#3fb950;color:#071109;}',
'.rk-cancel{border:1px solid #2a313a;background:#10151b;color:#d7dbe0;}',
'@media (max-width:760px){.rk-customize-shell{padding:10px;}.rk-customize-top{align-items:flex-start;}.rk-customize-body{grid-template-columns:1fr;overflow:auto;}.rk-customize-content{overflow:visible;padding-right:0;}.rk-customize-preview{position:relative;display:grid;grid-template-columns:88px minmax(0,1fr);gap:10px;align-items:center;}.rk-customize-preview canvas{width:88px;}.rk-customize-row{grid-template-columns:1fr;gap:5px;}.rk-row-label{padding-top:0;}.rk-avatar-grid{grid-template-columns:repeat(auto-fill,minmax(76px,1fr));}.rk-option-card{min-height:90px;}.rk-customize-actions{width:100%;justify-content:flex-start;}}'
].join('');
document.head.appendChild(style);
}
RK.openCustomize = function (current, onSave, opts) {
opts = opts || {};
ensureCustomizeStyle();
var draft = RK.normalizeAppearance(current);
var redrawers = []; // avatar thumbnail draws (reset in buildAvatarGrid)
var equipRedrawers = []; // equipment option tile draws (reset in renderEditor)
var cards = {};
function isCharDraft() {
return !!(RK.isChar && RK.isChar(draft.avatar));
}
function draftKind() {
return (baseAppearance(draft.avatar) || {}).kind;
}
function supportsColorDraft() {
var kind = draftKind();
return isCharDraft() || kind === 'model3d';
}
function activeProjection() {
return projectionForMode(selectedMode);
}
function ensureColorDraft() {
if (!draft.colors) draft.colors = cloneColors(null, draft.tint);
draft.tint = draft.colors.base;
}
function ensureCharDraft() {
ensureColorDraft();
if (!draft.equipment) draft.equipment = cloneEquipment(DEFAULT_EQUIPMENT);
}
var wrap = document.createElement('div');
wrap.className = 'rk-customize';
var shell = document.createElement('div');
shell.className = 'rk-customize-shell';
wrap.appendChild(shell);
var top = document.createElement('div');
top.className = 'rk-customize-top';
shell.appendChild(top);
var title = document.createElement('div');
title.className = 'rk-customize-title';
title.textContent = 'Customize your character';
top.appendChild(title);
var actions = document.createElement('div');
actions.className = 'rk-customize-actions';
top.appendChild(actions);
var save = document.createElement('button');
save.type = 'button';
save.className = 'rk-button rk-save';
save.textContent = 'Save';
actions.appendChild(save);
var cancel = document.createElement('button');
cancel.type = 'button';
cancel.className = 'rk-button rk-cancel';
cancel.textContent = 'Cancel';
actions.appendChild(cancel);
var body = document.createElement('div');
body.className = 'rk-customize-body';
shell.appendChild(body);
var previewPane = document.createElement('div');
previewPane.className = 'rk-customize-preview';
body.appendChild(previewPane);
var preview = document.createElement('canvas');
preview.width = 150;
preview.height = 164;
var pctx = preview.getContext('2d');
previewPane.appendChild(preview);
var previewText = document.createElement('div');
previewPane.appendChild(previewText);
var previewName = document.createElement('div');
previewName.className = 'rk-customize-name';
previewText.appendChild(previewName);
var previewMeta = document.createElement('div');
previewMeta.className = 'rk-customize-meta';
previewText.appendChild(previewMeta);
var content = document.createElement('div');
content.className = 'rk-customize-content';
body.appendChild(content);
// The main game page only uses top-down rendering, so the customizer there should
// default to top-down and not offer the tavern's render-mode picker. The tavern passes
// no opts, so it gets the full picker and the user's saved mode.
var selectedMode = opts.projection ? projectionToMode(opts.projection) : (RK.loadMode ? RK.loadMode('tiles') : 'tiles');
var showRenderModes = !opts.projection && RK.RENDER_MODES && RK.RENDER_MODES.length;
var modeCards = {};
var renderModeGrid = null;
if (showRenderModes) {
var renderSection = document.createElement('section');
renderSection.className = 'rk-customize-section';
content.appendChild(renderSection);
var renderTitle = document.createElement('h3');
renderTitle.textContent = 'Render';
renderSection.appendChild(renderTitle);
renderModeGrid = document.createElement('div');
renderModeGrid.className = 'rk-mode-grid';
renderSection.appendChild(renderModeGrid);
}
var avatarSection = document.createElement('section');
avatarSection.className = 'rk-customize-section';
content.appendChild(avatarSection);
var avatarTitle = document.createElement('h3');
avatarTitle.textContent = 'Avatar';
avatarSection.appendChild(avatarTitle);
var grid = document.createElement('div');
grid.className = 'rk-avatar-grid';
avatarSection.appendChild(grid);
var editSection = document.createElement('section');
editSection.className = 'rk-customize-section';
content.appendChild(editSection);
function colorCatalog(kind) {
if (kind === 'skin') return RK.CHAR_SKIN_TONES || {};
if (kind === 'hair') return RK.CHAR_HAIR_COLORS || {};
return RK.CHAR_TINTS || {};
}
function sectionTitle(text, parent) {
var h = document.createElement('h3');
h.textContent = text;
parent.appendChild(h);
return h;
}
function row(labelText, parent) {
var r = document.createElement('div');
r.className = 'rk-customize-row';
var label = document.createElement('div');
label.className = 'rk-row-label';
label.textContent = labelText;
r.appendChild(label);
var opts = document.createElement('div');
opts.className = 'rk-row-options';
r.appendChild(opts);
parent.appendChild(r);
return opts;
}
function optionButton(label, selected, onclick, canvas) {
var b = document.createElement('button');
b.type = 'button';
b.className = 'rk-equip-option' + (selected ? ' is-selected' : '');
if (canvas) b.appendChild(canvas);
var t = document.createElement('div');
t.className = 'rk-option-label';
t.textContent = label;
b.appendChild(t);
b.onclick = onclick;
return b;
}
function swatchButton(item, selected, onclick) {
var b = document.createElement('button');
b.type = 'button';
b.className = 'rk-swatch' + (selected ? ' is-selected' : '');
var dot = document.createElement('span');
dot.className = 'rk-swatch-dot' + (!item.color ? ' rk-none-dot' : '');
if (item.color) dot.style.background = item.color;
b.appendChild(dot);
var text = document.createElement('div');
text.className = 'rk-option-label';
text.textContent = item.label || item.id;
b.appendChild(text);
b.onclick = onclick;
return b;
}
function packLabel(id) {
var pack = RK.pack && RK.pack(id);
return (pack && pack.label) || 'premium pack';
}
function modeLockedTitle(mode) {
var label = mode && mode.label ? mode.label : 'Mode';
if (mode && RK.isModeRuntimeAvailable && !RK.isModeRuntimeAvailable(mode.id)) {
return label + ' is unavailable on this server because its optional renderer dependency is disabled.';
}
if (mode && mode.pack) return label + ' is locked. Buy any credits or unlock ' + packLabel(mode.pack) + '.';
return label + ' is locked. Buy any credits to unlock premium modes.';
}
function modeStatus(mode, unlocked) {
if (!mode || !mode.premium) return 'Included';
if (RK.isModeRuntimeAvailable && !RK.isModeRuntimeAvailable(mode.id)) return 'Unavailable';
if (unlocked && RK.renderModeTestUnlocks && RK.renderModeTestUnlocks()) return 'Test';
return unlocked ? 'Unlocked' : 'Locked';
}
function markRenderMode() {
for (var id in modeCards) {
if (id === selectedMode) modeCards[id].classList.add('is-selected');
else modeCards[id].classList.remove('is-selected');
}
}
function selectRenderMode(mode) {
if (RK.canUseMode && !RK.canUseMode(mode.id)) return;
selectedMode = mode.id;
if (RK.saveMode) RK.saveMode(mode.id);
markRenderMode();
buildAvatarGrid();
renderEditor();
redrawAll();
}
function buildRenderModes() {
if (!renderModeGrid || !RK.RENDER_MODES) return;
renderModeGrid.innerHTML = '';
modeCards = {};
RK.RENDER_MODES.forEach(function (mode) {
var unlocked = !RK.canUseMode || RK.canUseMode(mode.id);
var b = document.createElement('button');
b.type = 'button';
b.className = 'rk-mode-card' + (unlocked ? '' : ' is-locked');
b.setAttribute('aria-disabled', unlocked ? 'false' : 'true');
b.title = unlocked ? ('Use ' + mode.label) : modeLockedTitle(mode);
var label = document.createElement('span');
label.className = 'rk-mode-label';
label.textContent = mode.label + (mode.premium ? ' *' : '');
b.appendChild(label);
var status = document.createElement('span');
status.className = 'rk-mode-status';
status.textContent = modeStatus(mode, unlocked);
b.appendChild(status);
b.onclick = function () { selectRenderMode(mode); };
renderModeGrid.appendChild(b);
modeCards[mode.id] = b;
});
markRenderMode();
}
function setColor(slot, id) {
ensureCharDraft();
draft.colors[slot] = id;
if (slot === 'base') draft.tint = id;
renderEditor();
redrawAll();
}
function renderColorRow(label, slot, catalogKind, parent) {
var opts = row(label, parent);
var catalog = colorCatalog(catalogKind);
for (var id in catalog) {
(function (item) {
opts.appendChild(swatchButton(item, draft.colors && draft.colors[slot] === item.id, function () {
setColor(slot, item.id);
}));
})(catalog[id]);
}
}
function equipmentColorable(item) {
return !!(item && item.frame != null && item.colorable === true);
}
function renderEditor() {
editSection.innerHTML = '';
equipRedrawers = [];
if (!supportsColorDraft()) return;
if (isCharDraft()) ensureCharDraft();
else ensureColorDraft();
var projection = activeProjection();
if (projection === 'iso' && isCharDraft()) {
sectionTitle('Color', editSection);
renderColorRow('Skin', 'skin', 'skin', editSection);
return;
}
if (projection !== 'topdown' || !isCharDraft()) {
sectionTitle('Color', editSection);
renderColorRow('Color', 'base', 'tint', editSection);
return;
}
// 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
// remains here; the '@' colour for ASCII mode is still pickable in the ascii/colour
// branch above.
sectionTitle('Equipment', editSection);
(RK.CHAR_EQUIPMENT_SLOTS || []).forEach(function (slot) {
var catalog = RK.CHAR_EQUIPMENT[slot] || {};
var opts = row(slot.charAt(0).toUpperCase() + slot.slice(1), editSection);
for (var id in catalog) {
(function (item) {
opts.appendChild(optionButton(item.label, draft.equipment[slot] === item.id, function () {
draft.equipment[slot] = item.id;
renderEditor();
redrawAll();
}, optionTileCanvas(slot, item, draft, equipRedrawers)));
})(catalog[id]);
}
});
}
function selectAvatar(a) {
if (RK.canUseAppearance && !RK.canUseAppearance(a)) return;
draft.avatar = a.id;
if (RK.isChar && RK.isChar(draft.avatar)) {
ensureCharDraft();
} else if (draftKind() === 'model3d') {
ensureColorDraft();
draft.equipment = cloneEquipment(DEFAULT_EQUIPMENT);
} else {
draft.tint = 'none';
draft.equipment = cloneEquipment(DEFAULT_EQUIPMENT);
delete draft.colors;
}
mark();
renderEditor();
redrawAll();
}
function visibleAppearances() {
var projection = activeProjection();
return RK.appearances().filter(function (a) {
return appearanceVisibleInProjection(a, projection);
});
}
function appearanceForId(list, id) {
for (var i = 0; i < list.length; i++) if (list[i].id === id) return list[i];
return null;
}
function ensureVisibleAvatar() {
var list = visibleAppearances();
if (appearanceForId(list, draft.avatar)) return;
if (!list.length) return;
draft.avatar = list[0].id;
if (RK.isChar && RK.isChar(draft.avatar)) ensureCharDraft();
else if (draftKind() === 'model3d') {
ensureColorDraft();
draft.equipment = cloneEquipment(DEFAULT_EQUIPMENT);
} else {
draft.tint = 'none';
draft.equipment = cloneEquipment(DEFAULT_EQUIPMENT);
delete draft.colors;
}
}
function buildAvatarGrid() {
// 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.
grid.innerHTML = '';
cards = {};
redrawers = [];
visibleAppearances().forEach(function (a) {
var card = document.createElement('button');
var locked = !!(RK.canUseAppearance && !RK.canUseAppearance(a));
card.type = 'button';
card.className = 'rk-option-card' + (locked ? ' is-locked' : '');
if (locked) card.title = 'Premium pack - buy credits to unlock';
card.appendChild(thumbCanvas(a, function () {
var d = {};
for (var dk in draft) d[dk] = draft[dk];
d.__projection = activeProjection();
return d;
}, redrawers));
var lab = document.createElement('div');
lab.className = 'rk-option-label';
lab.textContent = a.label + (a.premium ? ' *' : '');
card.appendChild(lab);
card.onclick = function () { selectAvatar(a); };
grid.appendChild(card);
cards[a.id] = card;
});
mark();
}
function drawPreview() {
pctx.clearRect(0, 0, preview.width, preview.height);
var base = baseAppearance(draft.avatar);
var projection = activeProjection();
if (projection !== 'topdown') {
var temp = document.createElement('canvas');
temp.width = 72;
temp.height = 80;
drawProjectionThumb(temp.getContext('2d'), base, draft, projection, redrawAll);
pctx.imageSmoothingEnabled = projection !== 'ascii';
pctx.drawImage(temp, 0, 0, 72, 80, 21, 12, 108, 120);
} else if (base.kind === 'color') {
pctx.beginPath(); pctx.arc(75, 86, 34, 0, Math.PI * 2);
pctx.fillStyle = base.color; pctx.fill();
pctx.lineWidth = 3; pctx.strokeStyle = 'rgba(255,255,255,0.35)'; pctx.stroke();
} else if (base.kind === 'char') {
if (!RK.drawCharCompositeCanvas || !RK.drawCharCompositeCanvas(pctx, draft, 15, 12, 120)) RK.loadCharAtlas(redrawAll);
} else if (base.kind === 'model3d') {
pctx.beginPath(); pctx.arc(75, 86, 34, 0, Math.PI * 2);
pctx.fillStyle = '#64748b'; pctx.fill();
pctx.fillStyle = '#d7dbe0'; pctx.font = '26px monospace'; pctx.textAlign = 'center'; pctx.fillText('3D', 75, 95);
} else if (base.kind === 'skin') {
var rec = RK.skinSheet(base.id);
if (!rec) {
var r = RK.loadSkin(base.id);
if (r && r.cbs) r.cbs.push(redrawAll);
pctx.fillStyle = '#666'; pctx.font = '13px monospace'; pctx.textAlign = 'center'; pctx.fillText('...', 75, 88);
} else {
var s = RK.SKINS[base.id];
var row = (s.dirRows && s.dirRows.down) || 0;
var dh = 142, dw = dh * (s.frameW / s.frameH);
pctx.imageSmoothingEnabled = true;
pctx.drawImage(rec.img, 0, row * s.frameH, s.frameW, s.frameH, 75 - dw / 2, 158 - dh, dw, dh);
}
} else {
drawBaseThumb(pctx, base, draft, 'topdown', redrawAll);
}
var visible = appearanceVisibleInProjection(base, projection);
previewName.textContent = base.label || base.id;
var metaParts = [];
if (projection !== 'topdown') metaParts.push(projection.toUpperCase() + ' view');
if (!visible && projection !== 'topdown') metaParts.push('fallback render');
if (base.premium) metaParts.push('Premium pack');
else if (base.kind === 'char') metaParts.push('Customizable');
else if (base.kind === 'color') metaParts.push('Free');
previewMeta.textContent = metaParts.join(' · ') || 'Free';
}
function redrawAll() {
drawPreview();
redrawers.forEach(function (fn) { try { fn(); } catch (_) { /* ignore */ } });
equipRedrawers.forEach(function (fn) { try { fn(); } catch (_) { /* ignore */ } });
}
function mark() {
for (var id in cards) {
if (id === draft.avatar) cards[id].classList.add('is-selected');
else cards[id].classList.remove('is-selected');
}
}
save.onclick = function () {
var saved = RK.normalizeAppearance(draft);
RK.saveIdentity(saved);
document.body.removeChild(wrap);
if (onSave) onSave(saved);
};
cancel.onclick = function () { document.body.removeChild(wrap); };
document.body.appendChild(wrap);
buildRenderModes();
buildAvatarGrid();
renderEditor();
redrawAll();
};
})(window);
+359
View File
@@ -0,0 +1,359 @@
// Roguelike top-down characters (free tier). Each character is a SINGLE sprite on Kenney's
// character sheet (adjacent columns are DIFFERENT characters, not walk frames). We animate
// entirely procedurally: a vertical bob + squash while moving, horizontal flip when facing left.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
var COLS = 54, TILE = 16, SHEET = 'assets/kenney/roguelikeChar.png';
var EQUIP_SLOTS = ['body', 'head', 'shield', 'weapon'];
// Kenney's sheet includes recolour-friendly purple/magenta pixels. We remap only those
// exact source pixels so skin, outlines, wood, and metal keep their authored colours.
var TINT_SOURCE = {
'160,132,196': 0, // dark purple
'181,159,206': 1,
'199,182,220': 2,
'213,201,228': 3,
'255,153,204': 2 // hot-pink accent used by a few weapon overlays
};
var SKIN_SOURCE = {
'156,118,80': 0,
'161,125,82': 0,
'170,143,111': 1,
'176,128,82': 1,
'200,164,128': 2,
'229,196,157': 3
};
var HAIR_SOURCE = {
'114,88,57': 0,
'149,92,24': 1,
'163,84,34': 1,
'177,92,35': 2,
'192,117,28': 2,
'198,101,39': 3
};
RK.CHAR_TINTS = {
none: { id: 'none', label: 'Natural', color: null, ramp: null },
rose: { id: 'rose', label: 'Rose', color: '#d85c78', ramp: ['#8f3d54', '#b84f6b', '#d96f8c', '#f4aac0'] },
teal: { id: 'teal', label: 'Teal', color: '#37aaa5', ramp: ['#1f6360', '#287d79', '#37aaa5', '#99dee3'] },
moss: { id: 'moss', label: 'Moss', color: '#7bad2c', ramp: ['#4f721d', '#639535', '#7bad2c', '#95ce3e'] },
gold: { id: 'gold', label: 'Gold', color: '#d29922', ramp: ['#8d6640', '#b08052', '#d29922', '#eee3b3'] },
violet: { id: 'violet', label: 'Violet', color: '#a084c4', ramp: ['#74558f', '#8f6eb0', '#a084c4', '#d5c9e4'] },
ash: { id: 'ash', label: 'Ash', color: '#878787', ramp: ['#4f4f4f', '#646464', '#878787', '#cacaca'] }
};
RK.CHAR_SKIN_TONES = {
natural: { id: 'natural', label: 'Natural', color: '#e5c49d', ramp: ['#9c7650', '#aa8f6f', '#c8a480', '#e5c49d'] },
fair: { id: 'fair', label: 'Fair', color: '#f2d6b3', ramp: ['#b38361', '#c9a07a', '#e2be94', '#f2d6b3'] },
warm: { id: 'warm', label: 'Warm', color: '#c78355', ramp: ['#704226', '#9a5d37', '#c78355', '#e0a777'] },
umber: { id: 'umber', label: 'Umber', color: '#8b5a3c', ramp: ['#3e291d', '#5b3a28', '#8b5a3c', '#b7825c'] },
olive: { id: 'olive', label: 'Olive', color: '#9f9a64', ramp: ['#5b5a38', '#777246', '#9f9a64', '#c2bb83'] },
ash: { id: 'ash', label: 'Ash', color: '#a7a7a7', ramp: ['#585858', '#767676', '#a7a7a7', '#d1d1d1'] }
};
RK.CHAR_HAIR_COLORS = {
copper: { id: 'copper', label: 'Copper', color: '#c66527', ramp: ['#724627', '#a35424', '#c66527', '#d8893d'] },
brown: { id: 'brown', label: 'Brown', color: '#7b5437', ramp: ['#34261b', '#573a28', '#7b5437', '#a47a53'] },
black: { id: 'black', label: 'Black', color: '#333333', ramp: ['#111111', '#202020', '#333333', '#555555'] },
blond: { id: 'blond', label: 'Blond', color: '#d7b45a', ramp: ['#80662d', '#a9863a', '#d7b45a', '#f0d98a'] },
silver: { id: 'silver', label: 'Silver', color: '#c8c8c8', ramp: ['#686868', '#929292', '#c8c8c8', '#ececec'] },
violet: { id: 'violet', label: 'Violet', color: '#9f7aea', ramp: ['#46315f', '#694c93', '#9f7aea', '#d8c4ff'] }
};
var DEFAULT_COLORS = {
base: 'none',
skin: 'natural',
hair: 'copper',
body: 'none',
head: 'none',
shield: 'none',
weapon: 'none'
};
RK.CHAR_DEFAULT_COLORS = DEFAULT_COLORS;
RK.CHAR_EQUIPMENT = {
body: {
none: { id: 'none', label: 'None', frame: null },
robe: { id: 'robe', label: 'Robe', frame: 14 },
jerkin: { id: 'jerkin', label: 'Jerkin', frame: 122 },
mail: { id: 'mail', label: 'Mail', frame: 230 },
sash: { id: 'sash', label: 'Sash', frame: 440 }
},
head: {
none: { id: 'none', label: 'None', frame: null },
hood: { id: 'hood', label: 'Hood', frame: 24 },
helm: { id: 'helm', label: 'Helm', frame: 454 },
horns: { id: 'horns', label: 'Horns', frame: 354 },
cap: { id: 'cap', label: 'Cap', frame: 462 }
},
shield: {
none: { id: 'none', label: 'None', frame: null },
round: { id: 'round', label: 'Round', frame: 254 },
kite: { id: 'kite', label: 'Kite', frame: 304 },
tower: { id: 'tower', label: 'Tower', frame: 202 },
buckler:{ id: 'buckler', label: 'Buckler', frame: 411 }
},
weapon: {
none: { id: 'none', label: 'None', frame: null },
staff: { id: 'staff', label: 'Staff', frame: 154 },
sword: { id: 'sword', label: 'Sword', frame: 369 },
axe: { id: 'axe', label: 'Axe', frame: 375 },
bow: { id: 'bow', label: 'Bow', frame: 107 }
}
};
RK.CHAR_EQUIPMENT_SLOTS = EQUIP_SLOTS.slice();
// Curated humanoid characters (verified non-empty, by sight), one tile index each.
RK.CHARS = {
'char-villager': { id: 'char-villager', label: 'Villager', frame: 270 },
'char-elder': { id: 'char-elder', label: 'Elder', frame: 271 },
'char-barbarian': { id: 'char-barbarian', label: 'Barbarian', frame: 324 },
'char-monk': { id: 'char-monk', label: 'Monk', frame: 379 },
'char-ranger': { id: 'char-ranger', label: 'Ranger', frame: 432 },
'char-bard': { id: 'char-bard', label: 'Bard', frame: 486 },
'char-rogue': { id: 'char-rogue', label: 'Rogue', frame: 540 },
'char-merchant': { id: 'char-merchant', label: 'Merchant', frame: 541 },
'char-wizard': { id: 'char-wizard', label: 'Wizard', frame: 595 },
'char-goblin': { id: 'char-goblin', label: 'Goblin', frame: 162 }
};
RK.isChar = function (id) { return !!(id && RK.CHARS[id]); };
function validTint(id) {
return (id && RK.CHAR_TINTS[id]) ? id : 'none';
}
function validSkin(id) {
return (id && RK.CHAR_SKIN_TONES[id]) ? id : 'natural';
}
function validHair(id) {
return (id && RK.CHAR_HAIR_COLORS[id]) ? id : 'copper';
}
RK.normalizeCharColors = function (colors, legacyTint) {
var input = colors || {};
function tintFor(slot) {
return validTint(Object.prototype.hasOwnProperty.call(input, slot) ? input[slot] : legacyTint);
}
return {
base: tintFor('base'),
skin: validSkin(input.skin),
hair: validHair(input.hair),
body: tintFor('body'),
head: tintFor('head'),
shield: tintFor('shield'),
weapon: tintFor('weapon')
};
};
function validEquipment(slot, id) {
var catalog = RK.CHAR_EQUIPMENT[slot] || {};
return (id && catalog[id]) ? id : 'none';
}
RK.normalizeCharEquipment = function (equipment) {
equipment = equipment || {};
var out = {};
EQUIP_SLOTS.forEach(function (slot) {
out[slot] = validEquipment(slot, equipment[slot]);
});
return out;
};
RK.charAppearance = function (e) {
e = e || {};
var ap = e.appearance || {};
var avatar = e.avatar || ap.avatar || 'char-villager';
var colors = RK.normalizeCharColors(ap.colors, ap.tint);
return {
avatar: avatar,
tint: colors.base,
equipment: RK.normalizeCharEquipment(ap.equipment),
colors: colors
};
};
RK.charRenderKey = function (e) {
var ap = RK.charAppearance(e);
return [
ap.avatar, ap.tint,
ap.colors.base, ap.colors.skin, ap.colors.hair,
ap.colors.body, ap.colors.head, ap.colors.shield, ap.colors.weapon,
ap.equipment.body, ap.equipment.head, ap.equipment.shield, ap.equipment.weapon
].join('|');
};
var atlas = null;
var tintedTiles = {};
var tintedTextures = {};
RK.loadCharAtlas = function (cb) {
if (!atlas) atlas = new RK.TilesetAtlas(SHEET, { tile: TILE, spacing: 1 });
atlas.onReady(function () { if (cb) cb(atlas); });
return atlas;
};
RK.charAtlas = function () { return (atlas && atlas.ready) ? atlas : null; };
var last = {}; // procedural animation state per entity
RK.charFrame = function (ch, e, nowMs) {
var st = last[e.id] || (last[e.id] = { x: e.x, y: e.y, t: 0 });
if (e.x !== st.x || e.y !== st.y) { st.x = e.x; st.y = e.y; st.t = nowMs; }
var moving = (nowMs - st.t) < 300;
return {
idx: ch.frame,
bob: moving ? -Math.abs(Math.sin(nowMs / 100)) * 2.5 : Math.sin(nowMs / 480) * 0.6,
squash: moving ? 1 + Math.sin(nowMs / 100) * 0.07 : 1,
flip: e.facing === 'left',
moving: moving
};
};
RK.charTexture = function (idx) {
var a = RK.charAtlas();
if (!a) return null;
return a.texture(idx % a.cols, Math.floor(idx / a.cols));
};
function hexToRgb(hex) {
var n = parseInt(String(hex).replace('#', ''), 16);
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };
}
function applyRamp(img, source, ramp) {
if (!ramp) return;
for (var i = 0; i < img.data.length; i += 4) {
if (img.data[i + 3] === 0) continue;
var k = img.data[i] + ',' + img.data[i + 1] + ',' + img.data[i + 2];
var ri = source[k];
if (ri == null) continue;
var rgb = ramp[Math.min(ri, ramp.length - 1)];
img.data[i] = rgb.r; img.data[i + 1] = rgb.g; img.data[i + 2] = rgb.b;
}
}
function tintedTileCanvas(idx, tintId, colors, slot) {
// 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,
// a separate path. To restore tinting, delete this early return.
return null;
var a = RK.charAtlas();
tintId = validTint(tintId);
colors = RK.normalizeCharColors(colors, tintId);
slot = slot || 'base';
var skin = RK.CHAR_SKIN_TONES[colors.skin];
var hair = RK.CHAR_HAIR_COLORS[colors.hair];
var slotTint = RK.CHAR_TINTS[slot === 'base' ? colors.base : (colors[slot] || tintId)];
var slotRamp = slotTint && slotTint.ramp ? slotTint.ramp.map(hexToRgb) : null;
var needsSlotTint = !!slotRamp && (slot !== 'base' || colors.base !== 'none');
var needsBodyPalette = slot === 'base' && ((skin && colors.skin !== 'natural') || (hair && colors.hair !== 'copper') || needsSlotTint);
if (!a || (!needsBodyPalette && !needsSlotTint)) return null;
var key = idx + '|' + slot + '|' + JSON.stringify(colors);
if (tintedTiles[key]) return tintedTiles[key];
var cv = document.createElement('canvas');
cv.width = cv.height = TILE;
var ctx = cv.getContext('2d');
var src = a.px(idx % a.cols, Math.floor(idx / a.cols));
ctx.drawImage(a.img, src.x, src.y, TILE, TILE, 0, 0, TILE, TILE);
var img = ctx.getImageData(0, 0, TILE, TILE);
if (slot === 'base') {
applyRamp(img, SKIN_SOURCE, skin && colors.skin !== 'natural' ? skin.ramp.map(hexToRgb) : null);
applyRamp(img, HAIR_SOURCE, hair && colors.hair !== 'copper' ? hair.ramp.map(hexToRgb) : null);
}
applyRamp(img, TINT_SOURCE, slotRamp);
ctx.putImageData(img, 0, 0);
tintedTiles[key] = cv;
return cv;
}
RK.charTileTexture = function (idx, tintId, colors, slot) {
tintId = validTint(tintId);
if (typeof PIXI === 'undefined') return null;
colors = RK.normalizeCharColors(colors, tintId);
slot = slot || 'base';
var key = idx + '|' + slot + '|' + JSON.stringify(colors);
if (tintedTextures[key]) return tintedTextures[key];
var cv = tintedTileCanvas(idx, tintId, colors, slot);
if (!cv) return RK.charTexture(idx);
var tx = PIXI.Texture.from(cv);
if (tx.baseTexture) tx.baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST;
tintedTextures[key] = tx;
return tx;
};
RK.drawCharTileCanvas = function (ctx, idx, tintId, dx, dy, dw, dh, colors, slot) {
var a = RK.charAtlas();
if (!a) return false;
var tinted = tintedTileCanvas(idx, tintId, colors, slot);
ctx.imageSmoothingEnabled = false;
if (tinted) {
ctx.drawImage(tinted, 0, 0, TILE, TILE, dx, dy, dw, dh);
return true;
}
var src = a.px(idx % a.cols, Math.floor(idx / a.cols));
ctx.drawImage(a.img, src.x, src.y, TILE, TILE, dx, dy, dw, dh);
return true;
};
RK.charOverlayParts = function (appearance) {
appearance = appearance || {};
var colors = RK.normalizeCharColors(appearance.colors, appearance.tint);
var tint = colors.base;
var eq = RK.normalizeCharEquipment(appearance.equipment);
var out = [];
EQUIP_SLOTS.forEach(function (slot) {
var item = RK.CHAR_EQUIPMENT[slot][eq[slot]];
if (!item || item.frame == null) return;
var colorable = item.colorable === true;
out.push({ slot: slot, id: item.id, frame: item.frame, tint: colorable ? tint : 'none', colorable: colorable });
});
return out;
};
// Canvas draw (TileRenderer + thumbnails). Returns false (and lazy-loads) if not ready.
RK.drawCharCanvas = function (ctx, e, cell, nowMs) {
var a = RK.charAtlas();
if (!a) { RK.loadCharAtlas(); return false; }
var appearance = RK.charAppearance(e);
var ch = RK.CHARS[appearance.avatar];
if (!ch) return false;
var f = RK.charFrame(ch, e, nowMs);
var dw = cell * 1.8, dh = dw * f.squash;
var cx = e.x * cell + cell / 2;
var dy = (e.y * cell + cell) - dh + f.bob; // feet at tile bottom, squashed upward
ctx.imageSmoothingEnabled = false;
if (e.you) {
ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.ellipse(cx, e.y * cell + cell - 2, dw * 0.3, cell * 0.16, 0, 0, Math.PI * 2); ctx.stroke();
}
function drawComposite(dx, dy2) {
RK.drawCharTileCanvas(ctx, f.idx, appearance.tint, dx, dy2, dw, dh, appearance.colors, 'base');
RK.charOverlayParts(appearance).forEach(function (part) {
RK.drawCharTileCanvas(ctx, part.frame, part.tint, dx, dy2, dw, dh, part.colorable ? appearance.colors : null, part.slot);
});
}
if (f.flip) {
ctx.save();
ctx.translate(cx + dw / 2, dy); ctx.scale(-1, 1);
drawComposite(0, 0);
ctx.restore();
} else {
drawComposite(cx - dw / 2, dy);
}
if (e.label) {
ctx.fillStyle = '#d7dbe0'; ctx.font = '11px monospace'; ctx.textAlign = 'center';
ctx.fillText(e.label, cx, dy - 2);
}
return true;
};
RK.drawCharCompositeCanvas = function (ctx, appearance, dx, dy, size) {
var a = RK.charAtlas();
if (!a) { RK.loadCharAtlas(); return false; }
var ap = RK.charAppearance({ avatar: appearance && appearance.avatar, appearance: appearance });
var ch = RK.CHARS[ap.avatar];
if (!ch) return false;
RK.drawCharTileCanvas(ctx, ch.frame, ap.tint, dx, dy, size, size, ap.colors, 'base');
RK.charOverlayParts(ap).forEach(function (part) {
RK.drawCharTileCanvas(ctx, part.frame, part.tint, dx, dy, size, size, part.colorable ? ap.colors : null, part.slot);
});
return true;
};
})(window);
+42
View File
@@ -0,0 +1,42 @@
// 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) {
'use strict';
var RK = root.RK = root.RK || {};
RK.activeRoom = null;
RK.loadRoom = function (url, cb) {
if (!url) { if (cb) cb(null); return; }
fetch(url).then(function (r) { return r.json(); }).then(function (desc) {
var atlas = new RK.TilesetAtlas(desc.tileset, { tile: desc.tile, spacing: desc.spacing });
atlas.onReady(function () {
RK.activeRoom = { desc: desc, atlas: atlas };
if (cb) cb(RK.activeRoom);
});
}).catch(function (e) {
if (root.console) console.warn('room load failed:', e.message);
if (cb) cb(null);
});
};
RK.roomReady = function () {
return !!(RK.activeRoom && RK.activeRoom.atlas && RK.activeRoom.atlas.ready);
};
// Draw the room's layers (back-to-front) onto a 2D canvas at the given cell size.
RK.drawRoomCanvas = function (ctx, cell) {
if (!RK.roomReady()) return;
var d = RK.activeRoom.desc, a = RK.activeRoom.atlas;
ctx.imageSmoothingEnabled = false;
for (var li = 0; li < d.layerOrder.length; li++) {
var grid = d.layers[d.layerOrder[li]];
for (var y = 0; y < d.rows; y++) {
var row = grid[y];
for (var x = 0; x < d.cols; x++) {
if (row[x] >= 0) a.drawIndex(ctx, row[x], x * cell, y * cell, cell);
}
}
}
};
})(window);
+393
View File
@@ -0,0 +1,393 @@
// 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) {
'use strict';
function colorNum(hex) { return parseInt(String(hex).replace('#', ''), 16) || 0; }
function facingDelta(f) {
if (f === 'up') return { x: 0, y: -1 };
if (f === 'left') return { x: -1, y: 0 };
if (f === 'right') return { x: 1, y: 0 };
return { x: 0, y: 1 };
}
// A soft radial-gradient texture (used for lights, motes, and the vignette).
function radialTexture(size, stops) {
var c = document.createElement('canvas');
c.width = c.height = size;
var ctx = c.getContext('2d');
var g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
stops.forEach(function (s) { g.addColorStop(s[0], s[1]); });
ctx.fillStyle = g;
ctx.fillRect(0, 0, size, size);
return PIXI.Texture.from(c);
}
function FancyRenderer(host, opts) {
if (typeof PIXI === 'undefined') throw new Error('PIXI not loaded');
opts = opts || {};
this.name = 'fancy';
this.host = host;
this.cell = opts.cell || 26;
this.app = new PIXI.Application({ backgroundColor: 0x0a0c0f, antialias: true });
this.app.view.className = 'rk-canvas';
this.canvas = this.app.view;
host.appendChild(this.app.view);
this.tileLayer = new PIXI.Container();
this.lightLayer = new PIXI.Container();
this.entityLayer = new PIXI.Container();
this.particleLayer = new PIXI.Container();
this.app.stage.addChild(this.tileLayer, this.lightLayer, this.entityLayer, this.particleLayer);
this.vignette = null;
this.texLight = radialTexture(128, [[0, 'rgba(255,190,110,0.95)'], [1, 'rgba(255,190,110,0)']]);
this.texMote = radialTexture(64, [[0, 'rgba(255,240,210,0.9)'], [1, 'rgba(255,240,210,0)']]);
this.texVig = radialTexture(256, [[0, 'rgba(0,0,0,0)'], [0.6, 'rgba(0,0,0,0)'], [1, 'rgba(0,0,0,0.62)']]);
this.sprites = {};
this.lights = [];
this.particles = [];
this._sizeKey = null;
this._t = 0;
var self = this;
this._tick = function (dt) { self._animate(dt); };
this.app.ticker.add(this._tick);
}
FancyRenderer.prototype.render = function (scene) {
if (!scene || !this.app) return;
var cell = this.cell, w = scene.cols * cell, h = scene.rows * cell;
this.app.renderer.resize(w, h);
var key = scene.cols + 'x' + scene.rows;
var hasRoom = !!(window.RK && RK.roomReady && RK.roomReady());
if (key !== this._sizeKey || hasRoom !== this._hadRoom) {
this._buildTiles(scene);
this._buildLights(scene);
this._buildVignette(w, h);
this._seedParticles(w, h);
this._sizeKey = key;
this._hadRoom = hasRoom;
}
this._syncEntities(scene);
};
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.
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++) {
var grid = d.layers[d.layerOrder[li]];
for (var ry = 0; ry < d.rows; ry++) {
for (var rx = 0; rx < d.cols; rx++) {
var idx = grid[ry][rx];
if (idx < 0) continue;
var tex = a.texture(idx % a.cols, Math.floor(idx / a.cols));
if (!tex) continue;
var sp = new PIXI.Sprite(tex);
sp.x = rx * cell; sp.y = ry * cell; sp.width = cell; sp.height = cell;
this.tileLayer.addChild(sp);
}
}
}
return;
}
for (var y = 0; y < scene.rows; y++) {
for (var x = 0; x < scene.cols; x++) {
var def = scene.legend[scene.grid[y][x]] || { color: '#333' };
var g = new PIXI.Graphics();
g.beginFill(colorNum(def.color));
g.drawRoundedRect(0, 0, cell - 1, cell - 1, 4);
g.endFill();
if (def.solid) {
g.beginFill(0xffffff, 0.09);
g.drawRoundedRect(0, 0, cell - 1, Math.max(2, cell * 0.2), 4);
g.endFill();
g.beginFill(0x000000, 0.22);
g.drawRect(0, cell - 3, cell - 1, 3);
g.endFill();
}
g.x = x * cell;
g.y = y * cell;
this.tileLayer.addChild(g);
}
}
};
FancyRenderer.prototype._buildLights = function (scene) {
this.lightLayer.removeChildren();
this.lights = [];
var cell = this.cell;
for (var y = 0; y < scene.rows; y++) {
for (var x = 0; x < scene.cols; x++) {
if (scene.grid[y][x] !== 'bar' || (x % 3) !== 0) continue; // sample the bar
var s = new PIXI.Sprite(this.texLight);
s.anchor.set(0.5);
s.blendMode = PIXI.BLEND_MODES.ADD;
s.x = x * cell + cell / 2;
s.y = y * cell + cell / 2;
s.scale.set(cell * 2.4 / 128);
s.alpha = 0.5;
this.lightLayer.addChild(s);
this.lights.push({ s: s, base: 0.5, phase: Math.random() * 6.28 });
}
}
};
FancyRenderer.prototype._buildVignette = function (w, h) {
if (this.vignette) { this.app.stage.removeChild(this.vignette); this.vignette.destroy(); }
this.vignette = new PIXI.Sprite(this.texVig);
this.vignette.anchor.set(0.5);
this.vignette.x = w / 2;
this.vignette.y = h / 2;
this.vignette.width = w * 1.25;
this.vignette.height = h * 1.35;
this.app.stage.addChild(this.vignette); // drawn on top of everything
};
FancyRenderer.prototype._seedParticles = function (w, h) {
this.particleLayer.removeChildren();
this.particles = [];
var n = Math.min(60, Math.max(12, Math.round(w * h / 9000)));
for (var i = 0; i < n; i++) {
var p = new PIXI.Sprite(this.texMote);
p.anchor.set(0.5);
p.blendMode = PIXI.BLEND_MODES.ADD;
p.x = Math.random() * w;
p.y = Math.random() * h;
p.scale.set(0.12 + Math.random() * 0.18);
p.alpha = 0.15 + Math.random() * 0.2;
this.particleLayer.addChild(p);
this.particles.push({
s: p, w: w, h: h, ph: Math.random() * 6.28,
vx: (Math.random() - 0.5) * 0.25, vy: -(0.05 + Math.random() * 0.15)
});
}
};
FancyRenderer.prototype._makeSprite = function (e) {
var cell = this.cell, r = cell * 0.34, col = colorNum(e.color);
var c = new PIXI.Container();
var glow = new PIXI.Graphics();
glow.beginFill(col, 0.6);
glow.drawCircle(0, 0, r * 1.4);
glow.endFill();
try {
if (!PIXI.BlurFilter) throw new Error('no blur');
glow.filters = [new PIXI.BlurFilter(8)]; // real soft bloom
} catch (_) {
// No blur available: fake it with layered alpha rings.
glow.clear();
[[1.9, 0.05], [1.5, 0.10], [1.15, 0.18]].forEach(function (ring) {
glow.beginFill(col, ring[1]);
glow.drawCircle(0, 0, r * ring[0]);
glow.endFill();
});
}
glow.blendMode = PIXI.BLEND_MODES.ADD;
c.addChild(glow);
c._glow = glow;
var body = new PIXI.Graphics();
body.beginFill(col);
body.drawCircle(0, 0, r);
body.endFill();
var d = facingDelta(e.facing);
body.beginFill(0x0a0c0f);
body.drawCircle(d.x * r * 0.55, d.y * r * 0.55, cell * 0.08);
body.endFill();
c.addChild(body);
if (e.you) {
var ring = new PIXI.Graphics();
ring.lineStyle(2, 0xffffff, 0.9);
ring.drawCircle(0, 0, r + 2);
c.addChild(ring);
}
if (e.label) {
var label = new PIXI.Text(e.label, { fontFamily: 'monospace', fontSize: 11, fill: 0xd7dbe0 });
label.anchor.set(0.5, 1);
label.y = -cell * 0.5;
c.addChild(label);
}
return c;
};
// A premium animated-skin sprite (Pixi). Frames are swapped each tick in _animate.
FancyRenderer.prototype._makeSkinSprite = function (e) {
var s = window.RK.SKINS[e.avatar];
var c = new PIXI.Container();
var h = this.cell * (s.scale || 1.8);
// Warm backlight so a dark character reads against the dark room.
var glow = new PIXI.Graphics();
[[h * 0.55, 0.05], [h * 0.4, 0.10], [h * 0.28, 0.16]].forEach(function (rr) {
glow.beginFill(0xffe2b4, rr[1]); glow.drawCircle(0, 0, rr[0]); glow.endFill();
});
glow.blendMode = PIXI.BLEND_MODES.ADD;
glow.y = this.cell * 0.5 - h * 0.42;
c.addChild(glow);
var spr = new PIXI.Sprite(window.RK.skinTexture(e.avatar, 0, 0));
spr.anchor.set(0.5, 0.9);
spr.height = h; spr.width = h * (s.frameW / s.frameH);
spr.y = this.cell * 0.5; // feet at the tile's bottom
c.addChild(spr);
c._skinSpr = spr; c._skinId = e.avatar;
if (e.you) {
var ring = new PIXI.Graphics();
ring.lineStyle(2, 0xffffff, 0.85);
ring.drawEllipse(0, this.cell * 0.5, this.cell * 0.3, this.cell * 0.16);
c.addChild(ring);
}
if (e.label) {
var label = new PIXI.Text(e.label, { fontFamily: 'monospace', fontSize: 11, fill: 0xd7dbe0 });
label.anchor.set(0.5, 1); label.y = this.cell * 0.5 - h - 2;
c.addChild(label);
}
return c;
};
function configureCharPart(spr, h) {
spr.anchor.set(0.5, 0.9);
spr.height = h;
spr.width = h;
return spr;
}
// A roguelike character sprite (procedural walk + composited equipment), animated in _animate.
FancyRenderer.prototype._makeCharSprite = function (e) {
var appearance = window.RK.charAppearance(e);
var ch = window.RK.CHARS[appearance.avatar];
var c = new PIXI.Container();
var h = this.cell * 1.8;
var body = new PIXI.Container();
body.y = this.cell * 0.5;
var baseTex = window.RK.charTileTexture(ch.frame, appearance.tint, appearance.colors, 'base');
if (baseTex) body.addChild(configureCharPart(new PIXI.Sprite(baseTex), h));
window.RK.charOverlayParts(appearance).forEach(function (part) {
var tex = window.RK.charTileTexture(part.frame, part.tint, part.colorable ? appearance.colors : null, part.slot);
if (tex) body.addChild(configureCharPart(new PIXI.Sprite(tex), h));
});
c.addChild(body);
c._charBody = body; c._charId = appearance.avatar; c._charKey = window.RK.charRenderKey(e);
if (e.you) {
var ring = new PIXI.Graphics();
ring.lineStyle(2, 0xffffff, 0.85);
ring.drawEllipse(0, this.cell * 0.5, this.cell * 0.3, this.cell * 0.16);
c.addChild(ring);
}
if (e.label) {
var label = new PIXI.Text(e.label, { fontFamily: 'monospace', fontSize: 11, fill: 0xd7dbe0 });
label.anchor.set(0.5, 1); label.y = this.cell * 0.5 - h - 2;
c.addChild(label);
}
return c;
};
FancyRenderer.prototype._syncEntities = function (scene) {
var cell = this.cell, seen = {}, RKr = window.RK, focusFallback = null;
for (var i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i];
seen[e.id] = true;
var wantSkin = !!(RKr && RKr.isSkin && RKr.isSkin(e.avatar));
var wantChar = !!(RKr && RKr.isChar && RKr.isChar(e.avatar));
if (wantSkin && !RKr.skinSheet(e.avatar)) RKr.loadSkin(e.avatar); // lazy fetch
if (wantChar && !RKr.charAtlas()) RKr.loadCharAtlas();
var kind = (wantSkin && RKr.skinSheet(e.avatar)) ? 'skin'
: (wantChar && RKr.charAtlas()) ? 'char'
: 'circle';
var renderKey = (kind === 'char' && RKr.charRenderKey) ? RKr.charRenderKey(e) : e.avatar;
var s = this.sprites[e.id];
if (s && (s.kind !== kind || s.renderKey !== renderKey)) { // sheet loaded or appearance changed -> rebuild
this.entityLayer.removeChild(s.c); s.c.destroy({ children: true });
s = null; delete this.sprites[e.id];
}
if (!s) {
var c = (kind === 'skin') ? this._makeSkinSprite(e)
: (kind === 'char') ? this._makeCharSprite(e)
: this._makeSprite(e);
c.x = e.x * cell + cell / 2;
c.y = e.y * cell + cell / 2;
this.entityLayer.addChild(c);
s = this.sprites[e.id] = { c: c, kind: kind, renderKey: renderKey };
}
s.tx = e.x; s.ty = e.y; s.e = e;
if (e.kind === 'player' && !focusFallback) focusFallback = e;
if (e.you || e.cameraTarget) {
this.focusPoint = { x: e.x * cell + cell / 2, y: e.y * cell + cell / 2 };
focusFallback = null;
}
}
if (!this.focusPoint && focusFallback) {
this.focusPoint = { x: focusFallback.x * cell + cell / 2, y: focusFallback.y * cell + cell / 2 };
}
for (var id in this.sprites) {
if (!seen[id]) {
this.entityLayer.removeChild(this.sprites[id].c);
this.sprites[id].c.destroy({ children: true });
delete this.sprites[id];
}
}
};
FancyRenderer.prototype._animate = function (dt) {
this._t += dt;
var t = this._t, cell = this.cell, k = Math.min(1, 0.22 * dt), i, nowMs = Date.now();
for (var id in this.sprites) {
var s = this.sprites[id];
var tx = s.tx * cell + cell / 2, ty = s.ty * cell + cell / 2;
s.c.x += (tx - s.c.x) * k;
s.c.y += (ty - s.c.y) * k;
if (s.c._charBody && s.e) {
var cf = window.RK.charFrame(window.RK.CHARS[s.c._charId], s.e, nowMs);
s.c._charBody.scale.x = cf.flip ? -1 : 1;
s.c._charBody.scale.y = cf.squash;
s.c._charBody.y = this.cell * 0.5 + cf.bob;
} else if (s.c._skinSpr && s.e) {
var sk = window.RK.SKINS[s.c._skinId];
var fr = window.RK.skinFrame(sk, s.e, nowMs);
var tex = window.RK.skinTexture(s.c._skinId, fr.row, fr.col);
if (tex) s.c._skinSpr.texture = tex;
} else if (s.c._glow) {
s.c._glow.scale.set(1 + Math.sin(t * 0.09 + s.tx) * 0.16);
s.c._glow.alpha = 0.65 + Math.sin(t * 0.11) * 0.25;
}
}
for (i = 0; i < this.lights.length; i++) {
var L = this.lights[i];
L.s.alpha = L.base + Math.sin(t * 0.25 + L.phase) * 0.14 + Math.sin(t * 0.9 + L.phase * 1.7) * 0.06;
}
for (i = 0; i < this.particles.length; i++) {
var p = this.particles[i];
p.s.x += p.vx * dt;
p.s.y += p.vy * dt;
if (p.s.y < -8) { p.s.y = p.h + 8; p.s.x = Math.random() * p.w; }
if (p.s.x < -8) p.s.x = p.w + 8; else if (p.s.x > p.w + 8) p.s.x = -8;
p.s.alpha = 0.12 + (Math.sin(t * 0.15 + p.ph) + 1) * 0.12;
}
};
FancyRenderer.prototype.destroy = function () {
try {
if (this.app) {
this.app.ticker.remove(this._tick);
this.app.destroy(true, { children: true });
}
} catch (_) { /* ignore */ }
[this.texLight, this.texMote, this.texVig].forEach(function (tx) {
try { if (tx) tx.destroy(true); } catch (_) { /* ignore */ }
});
this.app = null;
this.sprites = {};
this.lights = [];
this.particles = [];
};
root.RK = root.RK || {};
root.RK.FancyRenderer = FancyRenderer;
})(window);
+118
View File
@@ -0,0 +1,118 @@
// 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.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
var fx = RK.fx = RK.fx || {};
// Fire flicker → 0..1. Layered sines at incommensurate rates so it reads as a living flame
// rather than an obvious pulse. `seed` decorrelates neighbouring torches.
fx.flicker = function (now, seed) {
seed = seed || 0;
var t = now / 1000;
var v = 0.62
+ 0.20 * Math.sin(t * 11.3 + seed * 1.7)
+ 0.11 * Math.sin(t * 24.1 + seed * 4.3)
+ 0.07 * Math.sin(t * 3.7 + seed * 0.9);
return v < 0 ? 0 : (v > 1 ? 1 : v);
};
// Smooth 0..1 pulse for hazards (slower, sinusoidal breathing).
fx.pulse = function (now, period, seed) {
period = period || 1400;
return 0.5 + 0.5 * Math.sin((now / period) * Math.PI * 2 + (seed || 0));
};
// Additive warm/tinted glow disc centred on (cx, cy).
fx.glow = function (ctx, cx, cy, radius, opts) {
opts = opts || {};
if (radius <= 0) return;
var rgb = opts.rgb || '255,180,90';
var a = opts.intensity == null ? 0.5 : opts.intensity;
var g = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius);
g.addColorStop(0, 'rgba(' + rgb + ',' + a + ')');
g.addColorStop(0.45, 'rgba(' + rgb + ',' + (a * 0.35) + ')');
g.addColorStop(1, 'rgba(' + rgb + ',0)');
ctx.save();
ctx.globalCompositeOperation = 'lighter';
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
};
function flamePath(ctx, cx, cy, w, h, sway) {
ctx.beginPath();
ctx.moveTo(cx - w / 2, cy);
ctx.quadraticCurveTo(cx - w * 0.5 + sway, cy - h * 0.55, cx + sway, cy - h);
ctx.quadraticCurveTo(cx + w * 0.5 + sway, cy - h * 0.55, cx + w / 2, cy);
ctx.quadraticCurveTo(cx, cy + h * 0.14, cx - w / 2, cy);
ctx.closePath();
}
// A dancing flame whose BASE sits at (cx, cy) and licks upward. `scale` ≈ flame width.
fx.flame = function (ctx, cx, cy, scale, now, seed) {
seed = seed || 0;
var f = fx.flicker(now, seed);
var sway = Math.sin(now / 150 + seed) * scale * 0.16;
var h = scale * (1.5 + f * 0.7);
var w = scale * 0.95;
ctx.save();
ctx.globalCompositeOperation = 'lighter';
// Outer flame (orange envelope).
var og = ctx.createRadialGradient(cx, cy - h * 0.45, 0, cx, cy - h * 0.4, h);
og.addColorStop(0, 'rgba(255,225,150,0.95)');
og.addColorStop(0.4, 'rgba(255,140,40,0.72)');
og.addColorStop(1, 'rgba(190,40,10,0)');
ctx.fillStyle = og;
flamePath(ctx, cx, cy, w, h, sway);
ctx.fill();
// Inner core (white-hot).
var ig = ctx.createRadialGradient(cx + sway * 0.5, cy - h * 0.32, 0, cx + sway * 0.5, cy - h * 0.3, h * 0.55);
ig.addColorStop(0, 'rgba(255,255,238,0.95)');
ig.addColorStop(1, 'rgba(255,205,95,0)');
ctx.fillStyle = ig;
flamePath(ctx, cx, cy, w * 0.52, h * 0.62, sway * 0.6);
ctx.fill();
ctx.restore();
};
// A fire emitter = flame + a soft warm ground glow. Used for torches (small) and hearths
// (large) alike; `scale` drives both.
fx.fire = function (ctx, cx, cy, scale, now, seed) {
var f = fx.flicker(now, seed || 0);
fx.glow(ctx, cx, cy - scale * 0.2, scale * (3.4 + f * 0.6), { rgb: '255,170,80', intensity: 0.16 + f * 0.12 });
fx.flame(ctx, cx, cy, scale, now, seed || 0);
};
// Hazard palettes. `rgb` = the emissive heat colour; `base` = the flat tint painted into the
// tile footprint; `period` = pulse speed (ms).
var HAZARD = {
lava: { rgb: '255,110,30', base: 'rgba(70,15,5,0.55)', period: 1500 },
poison: { rgb: '90,230,90', base: 'rgba(15,50,20,0.50)', period: 2200 },
spikes: { rgb: '170,190,215', base: 'rgba(20,24,30,0.35)', period: 1000 }
};
fx.isHazard = function (kind) { return !!HAZARD[kind]; };
fx.hazardKinds = function () { return Object.keys(HAZARD); };
// Pulsing hazard overlay. The renderer passes a `drawFootprint(ctx)` callback that traces the
// tile shape (a square cell top-down, a diamond in iso) so the flat tint clips correctly; the
// heat glow rides on top additively.
fx.hazard = function (ctx, kind, cx, cy, radius, now, drawFootprint) {
var s = HAZARD[kind];
if (!s) return;
var p = fx.pulse(now, s.period, cx * 0.13 + cy * 0.07);
if (drawFootprint) {
ctx.save();
drawFootprint(ctx);
ctx.fillStyle = s.base;
ctx.fill();
ctx.restore();
}
fx.glow(ctx, cx, cy, radius * (1.0 + p * 0.25), { rgb: s.rgb, intensity: 0.16 + p * 0.4 });
};
})(typeof window !== 'undefined' ? window : this);
+657
View File
@@ -0,0 +1,657 @@
// 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';
function IsoRenderer(host, opts) {
opts = opts || {};
this.name = 'iso';
this.host = host;
this.assets = (root.RK && ((RK.activeIsoAssets && RK.activeIsoAssets()) || RK.isoAssets)) || {};
this.tileW = opts.tileW || (this.assets.tile && this.assets.tile.w) || 84;
this.tileH = opts.tileH || (this.assets.tile && this.assets.tile.h) || 42;
this.imageW = opts.imageW || (this.assets.tile && this.assets.tile.imageW) || 92;
this.imageH = opts.imageH || (this.assets.tile && this.assets.tile.imageH) || 184;
this.canvas = document.createElement('canvas');
this.canvas.className = 'rk-canvas';
this.ctx = this.canvas.getContext('2d');
this.cache = {};
this.tintCache = {};
this.shadeCache = {};
this.boundsCache = {};
this.last = {};
this.lastScene = null;
this.enabled = !(root.RK && RK.canUsePack && this.assets.pack && !RK.canUsePack(this.assets.pack));
this._raf = null;
this._animating = false;
host.appendChild(this.canvas);
if (this.enabled) this._preload();
}
IsoRenderer.prototype._load = function (url) {
if (!url) return null;
if (this.cache[url]) return this.cache[url];
var rec = this.cache[url] = { ready: false, img: new Image() };
var self = this;
rec.img.onload = function () { rec.ready = true; self._invalidate(); };
rec.img.onerror = function () { rec.error = true; };
rec.img.src = url;
return rec;
};
IsoRenderer.prototype._invalidate = function () {
if (this._raf || !this.lastScene) return;
var self = this;
this._raf = requestAnimationFrame(function () {
self._raf = null;
if (self.lastScene) self.render(self.lastScene);
});
};
IsoRenderer.prototype._preload = function () {
var tiles = this.assets.tiles || {};
for (var k in tiles) this._load(tiles[k]);
var self = this;
function loadCharacter(ch) {
if (!ch) return;
self._load(ch.idle);
(ch.run || []).forEach(self._load.bind(self));
}
var ch = this.assets.character || {};
loadCharacter(ch);
var dirs = this.assets.directions || {};
for (var d in dirs) loadCharacter(dirs[d]);
};
IsoRenderer.prototype._project = function (x, y, originX, originY) {
return {
x: originX + (x - y) * this.tileW / 2,
y: originY + (x + y) * this.tileH / 2
};
};
IsoRenderer.prototype._drawImage = function (img, cx, baseY, w, h) {
this.ctx.drawImage(img, cx - w / 2, baseY - h, w, h);
};
// 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, which falls
// back to a glyph.
IsoRenderer.prototype._featureTileUrl = function (e) {
var tiles = this.assets.tiles || {};
var c = e.char;
if (c === '<' || c === '>') return tiles.stairs || null;
if (c === '$' || c === '$W' || c === '$M') return tiles.chestClosed || tiles.chest || null;
return null;
};
// 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();
ctx.beginPath();
ctx.moveTo(cx, cy - hh); ctx.lineTo(cx + hw, cy); ctx.lineTo(cx, cy + hh); ctx.lineTo(cx - hw, cy);
ctx.closePath();
ctx.lineWidth = 2.5;
ctx.strokeStyle = color;
ctx.stroke();
ctx.restore();
};
// Draw a text glyph centered at a projected cell (feature fallback when no pack tile fits).
IsoRenderer.prototype._glyph = function (cx, cy, ch, color) {
var ctx = this.ctx;
ctx.save();
ctx.font = 'bold ' + Math.round(this.tileH * 0.95) + "px monospace";
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = color || '#fff';
ctx.fillText(ch, cx, cy);
ctx.restore();
};
// 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();
ctx.moveTo(cx, cy - hh); ctx.lineTo(cx + hw, cy); ctx.lineTo(cx, cy + hh); ctx.lineTo(cx - hw, cy);
ctx.closePath();
ctx.fillStyle = color; ctx.fill();
ctx.strokeStyle = 'rgba(0,0,0,0.28)'; ctx.lineWidth = 1; ctx.stroke();
};
// Soft contact shadow grounds props/characters so they don't float on the floor.
IsoRenderer.prototype._contactShadow = function (cx, cy, rx, ry) {
var ctx = this.ctx;
ctx.save();
ctx.globalAlpha = 0.28;
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
};
// 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 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);
g.addColorStop(0.45, outer);
g.addColorStop(1, 'rgba(0,0,0,0)');
ctx.save();
ctx.globalCompositeOperation = 'lighter';
ctx.fillStyle = g;
// The pool is squashed to the iso ground plane so it reads as light ON the floor rather
// than a sphere floating in front of the camera.
ctx.translate(cx, cy);
ctx.scale(1, this.tileH / this.tileW);
ctx.translate(-cx, -cy);
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
};
// Embers rising off a flame. Deterministic per torch (seeded by cell) so they don't reshuffle
// every frame; only the phase advances.
IsoRenderer.prototype._embers = function (cx, cy, seed, now) {
var ctx = this.ctx;
ctx.save();
ctx.globalCompositeOperation = 'lighter';
for (var i = 0; i < 4; i++) {
var phase = ((now / 1400) + (seed + i * 37) / 97) % 1;
var driftX = Math.sin((seed + i * 11) * 1.7 + phase * 6.28) * 7;
var y = cy - phase * 34;
var a = (1 - phase) * 0.5;
ctx.fillStyle = 'rgba(255,' + (150 + Math.floor(phase * 70)) + ',90,' + a.toFixed(3) + ')';
ctx.beginPath();
ctx.arc(cx + driftX, y, 1.5 * (1 - phase * 0.5), 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
};
// 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) {
var ctx = this.ctx, hw = this.tileW / 2, hh = this.tileH / 2;
var g = ctx.createRadialGradient(cx, cy, hw * 0.15, cx, cy, hw);
g.addColorStop(0, 'rgba(0,0,0,0)');
g.addColorStop(1, 'rgba(0,0,0,' + strength.toFixed(3) + ')');
ctx.save();
ctx.beginPath();
ctx.moveTo(cx, cy - hh); ctx.lineTo(cx + hw, cy); ctx.lineTo(cx, cy + hh); ctx.lineTo(cx - hw, cy);
ctx.closePath();
ctx.clip();
ctx.fillStyle = g;
ctx.fillRect(cx - hw, cy - hh, this.tileW, this.tileH);
ctx.restore();
};
// 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,
w / 2, h * 0.46, Math.max(w, h) * 0.62);
g.addColorStop(0, 'rgba(255, 214, 150, 0.06)');
g.addColorStop(0.5, 'rgba(0, 0, 0, 0)');
g.addColorStop(1, 'rgba(0, 0, 0, 0.58)');
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = g;
ctx.fillRect(0, 0, w, h);
ctx.restore();
};
IsoRenderer.prototype._imageBounds = function (img) {
if (!img) return null;
var key = img.src || img._rkBoundsKey || null;
if (key && this.boundsCache[key]) return this.boundsCache[key];
var w = img.naturalWidth || img.width;
var h = img.naturalHeight || img.height;
var cv = document.createElement('canvas');
cv.width = w;
cv.height = h;
var ctx = cv.getContext('2d');
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, w, h).data;
var minX = w, minY = h, maxX = -1, maxY = -1;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
if (data[(y * w + x) * 4 + 3] < 8) continue;
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
}
var bounds = maxX < minX ? { x: 0, y: 0, w: w, h: h } : { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
if (key) this.boundsCache[key] = bounds;
return bounds;
};
IsoRenderer.prototype._drawSpriteImage = function (img, cx, baseY, h) {
var b = this._imageBounds(img);
if (!b) return;
var w = h * (b.w / b.h);
this.ctx.drawImage(img, b.x, b.y, b.w, b.h, cx - w / 2, baseY - h, w, h);
};
IsoRenderer.prototype._tintedImage = function (img, tint) {
if (!img || !tint) return img;
var key = img.src + '|' + tint;
if (this.tintCache[key]) return this.tintCache[key];
var cv = document.createElement('canvas');
cv.width = img.naturalWidth || img.width;
cv.height = img.naturalHeight || img.height;
var ctx = cv.getContext('2d');
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = 'source-atop';
ctx.globalAlpha = 0.42;
ctx.fillStyle = tint;
ctx.fillRect(0, 0, cv.width, cv.height);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
cv._rkBoundsKey = key;
this.tintCache[key] = cv;
return cv;
};
// 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)));
if (step >= 5) return img;
var key = (img.src || img._rkBoundsKey || '') + '|s' + step;
if (this.shadeCache[key]) return this.shadeCache[key];
var cv = document.createElement('canvas');
cv.width = img.naturalWidth || img.width;
cv.height = img.naturalHeight || img.height;
if (!cv.width || !cv.height) return img;
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, 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';
cv._rkBoundsKey = key;
this.shadeCache[key] = cv;
return cv;
};
IsoRenderer.prototype._skinTintFor = function (visual) {
var ap = visual && visual.appearance;
var skin = ap && ap.colors && ap.colors.skin;
if (!skin || skin === 'natural') return null;
var tones = root.RK && RK.CHAR_SKIN_TONES;
var tone = tones && tones[skin];
return (tone && tone.color) || null;
};
IsoRenderer.prototype._tileUrl = function (kind) {
var tiles = this.assets.tiles || {};
return tiles[kind] || tiles.fallback || tiles.floor;
};
// 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;
return h / 4294967295;
}
// Wall-family kinds share edge-run detection so a window/door in a wall counts as wall.
var WALLISH = { wall: 1, window: 1, door: 1, archway: 1 };
IsoRenderer.prototype._isWall = function (scene, x, y) {
if (x < 0 || y < 0 || y >= scene.rows || x >= scene.cols) return false;
return !!WALLISH[scene.grid[y][x]];
};
// 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. 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);
var yRun = this._isWall(scene, x, y - 1) || this._isWall(scene, x, y + 1);
if (xRun && yRun && kind === 'wall' && tiles.wallCorner) return 'wallCorner';
if (yRun && !xRun && tiles[kind + 'Y']) return kind + 'Y';
return kind;
};
// Sprinkle floor variants deterministically so the ground isn't a flat identical sea.
IsoRenderer.prototype._floorVariant = function (kind, x, y) {
var tiles = this.assets.tiles || {};
var r = cellHash(x, y);
if (kind === 'floor' && tiles.floorAlt && r > 0.86) return 'floorAlt';
if (kind === 'floor2' && tiles.stoneTile && r > 0.6) return 'stoneTile';
if (kind === 'floor2' && tiles.floor2Alt && r > 0.82) return 'floor2Alt';
return kind;
};
IsoRenderer.prototype._visualFor = function (e) {
var appearance = (e && e.appearance) || { avatar: (e && e.avatar) || 'default' };
if (root.RK && RK.avatarVisuals && RK.avatarVisuals.resolve) {
return RK.avatarVisuals.resolve(appearance, { projection: 'iso', context: 'tavern', entity: e });
}
if (root.RK && RK.resolveAppearance) return RK.resolveAppearance(e, 'iso');
return null;
};
IsoRenderer.prototype._charFrame = function (e, now) {
var visual = this._visualFor(e);
if (visual && visual.allowed === false) return null;
var dirs = this.assets.directions || {};
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) {
// 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';
st.x = e.x; st.y = e.y; st.t = now;
}
var facing = (e && e.facing) || st.facing || 'down';
var moving = (now - st.t) < 360;
var ch = dirs[facing] || (visual && visual.character) || (this.assets.character || {});
if (!moving || !ch.run || ch.run.length === 0) return { url: ch.idle, character: ch, visual: visual };
this._animating = true;
return { url: ch.run[Math.floor(now / 80) % ch.run.length], character: ch, visual: visual };
};
IsoRenderer.prototype.render = function (scene) {
if (!scene) return;
this.lastScene = scene;
this._animating = false;
var margin = 28;
var originX = margin + scene.rows * this.tileW / 2 + this.tileW;
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);
// 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 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;
}
var ctx = this.ctx;
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.fillStyle = scene.background || '#0a0c0f';
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
ctx.imageSmoothingEnabled = true;
// Furniture kinds draw a floor tile as the base + the prop sprite on top (same idea as the
// tiled renderer's `over` compositing). Everything else is a plain ground/wall tile.
var PROP = { bar: 1, table: 1, chair: 1, keg: 1, shelf: 1, barrel: 1, crate: 1, chest: 1 };
var legend = scene.legend || {};
var items = [], x, y, kind, p, def;
for (y = 0; y < scene.rows; y++) {
for (x = 0; x < scene.cols; x++) {
kind = scene.grid[y][x];
def = legend[kind];
p = this._project(x, y, originX, originY);
items.push({ type: 'tile', kind: kind, x: x, y: y, sx: p.x, sy: p.y, depth: x + y });
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) 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 });
}
}
}
for (var i = 0; i < scene.entities.length; i++) {
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: 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.
var lights = [];
for (i = 0; i < items.length; i++) {
var it = items[i];
if (it.type === 'tile') {
// 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);
else tileKind = this._floorVariant(tileKind, it.x, it.y);
var rec = this._load(this._tileUrl(tileKind));
// Cutaway: fade the walls sitting between the camera and the player (higher x+y, toward
// the SE camera, within a few cells) so they don't hide the player or the openings right
// in front of them. Iso occlusion otherwise makes near hallways impossible to read.
var cut = WALLISH[it.kind] && this._plx != null &&
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, 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 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));
this._drawImage(img, it.sx, it.sy + this.tileH, this.imageW, this.imageH);
} else {
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: 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
// 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);
if (adj) {
ctx.globalAlpha = Math.max(0.14, lb);
this._wallAO(it.sx, it.sy + this.tileH * 0.5, Math.min(0.42, 0.14 * adj));
}
ctx.globalAlpha = Math.max(0.14, lb) * 0.5;
ctx.fillStyle = 'rgba(150,215,255,1)';
ctx.beginPath();
ctx.arc(it.sx, it.sy + this.tileH * 0.5, 2.4, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = 1;
} else if (it.type === 'prop') {
this._contactShadow(it.sx, it.sy + this.tileH * 1.4, 22, 9);
rec = this._load(this._tileUrl(it.kind));
if (rec && rec.ready) this._drawImage(rec.img, it.sx, it.sy + this.tileH, this.imageW, this.imageH);
} else if (it.type === 'fx' && root.RK && RK.fx) {
this._animating = true; // keep the RAF alive so the flame/pulse animates
var fcx = it.sx, fgy = it.sy + this.tileH * 1.15;
if (it.def.hazard) {
var hw = this.tileW / 2, hh = this.tileH / 2, hy = it.sy + this.tileH;
RK.fx.hazard(ctx, it.def.hazard, fcx, hy, this.tileW * 0.5, now, function (c) {
c.beginPath();
c.moveTo(fcx, hy - hh); c.lineTo(fcx + hw, hy);
c.lineTo(fcx, hy + hh); c.lineTo(fcx - hw, hy); c.closePath();
});
} else {
var fscale = this.tileW * (it.def.fxScale || 0.34) * 0.7;
RK.fx.fire(ctx, fcx, fgy, fscale, now, (it.x * 7 + it.y * 13) % 97);
var seed = (it.x * 7 + it.y * 13) % 97;
this._embers(fcx, fgy - this.tileH * 0.2, seed, now);
// Torch flames flicker, so the pool they cast has to flicker with them.
var flick = 0.82 + Math.sin(now / 95 + seed) * 0.12 + Math.sin(now / 41 + seed * 2) * 0.06;
lights.push({
x: fcx, y: it.sy + this.tileH, r: this.tileW * 1.75 * flick,
inner: 'rgba(255,168,74,' + (0.15 * flick).toFixed(3) + ')',
outer: 'rgba(196,96,26,' + (0.045 * flick).toFixed(3) + ')'
});
}
} else if (it.type === 'entity') {
// 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);
if (frec && frec.ready) this._drawImage(frec.img, it.sx, it.sy + this.tileH, this.imageW, this.imageH);
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.
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;
// 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),
inner: 'rgba(' + beaconRGB + ',' + (0.10 + breathe * 0.12).toFixed(3) + ')',
outer: 'rgba(' + beaconRGB + ',' + (0.03 + breathe * 0.04).toFixed(3) + ')'
});
}
continue;
}
this._contactShadow(it.sx, it.sy + this.tileH * 1.15, 18, 7);
var frame = this._charFrame(it.e, now);
rec = this._load(frame && frame.url);
if (rec && rec.ready) {
var ch = frame.character || this.assets.character || {};
// 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 {
ctx.beginPath();
ctx.arc(it.sx, it.sy, 8, 0, Math.PI * 2);
ctx.fillStyle = it.e.color || '#d7dbe0';
ctx.fill();
}
if (it.e.you) {
ctx.strokeStyle = 'rgba(255,255,255,0.85)';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.ellipse(it.sx, it.sy + this.tileH * 0.7, 20, 8, 0, 0, Math.PI * 2);
ctx.stroke();
}
if (it.e.label) {
ctx.fillStyle = '#d7dbe0';
ctx.font = '11px monospace';
ctx.textAlign = 'center';
ctx.fillText(it.e.label, it.sx, it.sy - 62);
}
}
}
// Walkability affordance: the iso wall tiles leave ambiguous gaps that read as doorways, so
// 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]];
for (var ni = 0; ni < nbrs.length; ni++) {
var nx = this._plx + nbrs[ni][0], ny = this._ply + nbrs[ni][1];
if (ny < 0 || nx < 0 || !scene.grid[ny] || nx >= scene.cols) continue;
var nk = scene.grid[ny][nx];
if (nk === 'wall' || nk === 'dark' || nk === 'torch' || nk === undefined) continue;
var np = this._project(nx, ny, originX, originY);
this._diamondOutline(np.x, np.y + this.tileH * 0.5, 'rgba(130,220,255,' + pulse + ')');
}
this._animating = true; // keep the pulse animating between game updates
}
// The player carries a lantern. Its pool is drawn last of the emitters so it always wins in
// the cell you actually occupy, and it breathes slightly so a still player isn't a static image.
if (this.focusPoint) {
var lantern = 0.9 + Math.sin(now / 170) * 0.07 + Math.sin(now / 73) * 0.03;
lights.push({
x: this.focusPoint.x, y: this.focusPoint.y, r: this.tileW * 2.7 * lantern,
inner: 'rgba(255,214,158,' + (0.115 * lantern).toFixed(3) + ')',
outer: 'rgba(210,140,70,' + (0.04 * lantern).toFixed(3) + ')'
});
this._animating = true;
}
for (var lg = 0; lg < lights.length; lg++) {
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,
// 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();
if (this._animating) this._invalidate();
};
// Cold blue overlay on explored-but-not-currently-visible cells.
IsoRenderer.prototype._memoryWash = function (scene, originX, originY) {
var light = scene.lightGrid;
if (!light) return;
var ctx = this.ctx, hw = this.tileW / 2, hh = this.tileH / 2;
ctx.save();
ctx.globalCompositeOperation = 'source-atop';
// 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, 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();
ctx.moveTo(p.x, cy - hh); ctx.lineTo(p.x + hw, cy);
ctx.lineTo(p.x, cy + hh); ctx.lineTo(p.x - hw, cy);
ctx.closePath();
ctx.fill();
}
}
ctx.restore();
};
IsoRenderer.prototype.destroy = function () {
if (this._raf) cancelAnimationFrame(this._raf);
if (this.canvas && this.canvas.parentNode) this.canvas.parentNode.removeChild(this.canvas);
this.canvas = null;
this.ctx = null;
this.cache = {};
this.tintCache = {};
this.shadeCache = {};
this.boundsCache = {};
this.last = {};
this.lastScene = null;
};
root.RK = root.RK || {};
root.RK.IsoRenderer = IsoRenderer;
})(window);
+75
View File
@@ -0,0 +1,75 @@
// 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
// 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
// selection per projection. Renderers ask for the active pack's assets; a picker lets an unlocked
// user switch. Adding a pack then = register(def) + drop assets + a catalog row.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
// id -> { id, label, projection: 'topdown'|'iso'|'3d', kind, assets }
// `assets` is the render-kit payload for that projection (theme tiles / iso set / 3d models).
RK.PACK_REGISTRY = RK.PACK_REGISTRY || {};
// Storage: localStorage in the browser, an in-memory map under Node/tests.
var mem = {};
function store() {
try { if (root.localStorage) return root.localStorage; } catch (_) {}
return { getItem: function (k) { return k in mem ? mem[k] : null; }, setItem: function (k, v) { mem[k] = String(v); } };
}
function key(projection) { return 'rk_pack_' + projection; }
RK.registerPack = function (def) {
if (!def || !def.id || !def.projection) return null;
RK.PACK_REGISTRY[def.id] = def;
return def;
};
RK.getPackDef = function (id) { return (id && RK.PACK_REGISTRY[id]) || null; };
RK.packsForProjection = function (projection) {
var out = [];
for (var id in RK.PACK_REGISTRY) {
if (RK.PACK_REGISTRY[id].projection === projection) out.push(RK.PACK_REGISTRY[id]);
}
return out;
};
// Packs the user can actually use for a projection (free ones + entitlement-unlocked ones).
RK.unlockedPacks = function (projection) {
return RK.packsForProjection(projection).filter(function (p) {
return !RK.canUsePack || RK.canUsePack(p.id);
});
};
// The user's chosen pack if it's registered for this projection AND unlocked; otherwise the
// first unlocked pack; otherwise null.
RK.activePackId = function (projection) {
var saved = store().getItem(key(projection));
var def = saved && RK.PACK_REGISTRY[saved];
if (def && def.projection === projection && (!RK.canUsePack || RK.canUsePack(saved))) return saved;
var unlocked = RK.unlockedPacks(projection);
return unlocked.length ? unlocked[0].id : null;
};
RK.activePack = function (projection) { return RK.getPackDef(RK.activePackId(projection)); };
RK.activePackAssets = function (projection) {
var def = RK.activePack(projection);
return def ? def.assets : null;
};
// Select a pack (persisted per projection). Refused if unregistered or locked. Returns success.
RK.setActivePack = function (id) {
var def = RK.getPackDef(id);
if (!def) return false;
if (RK.canUsePack && !RK.canUsePack(id)) return false;
store().setItem(key(def.projection), id);
return true;
};
if (typeof module !== 'undefined' && module.exports) module.exports = RK;
})(typeof window !== 'undefined' ? window : this);
+212
View File
@@ -0,0 +1,212 @@
// Render mode registry, factory, and entitlements for the render kit (RK).
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
RK.localRenderersEnabled = function () {
return !!(root.WOWNGEON_RUNTIME && root.WOWNGEON_RUNTIME.rendererLocalEnabled === true);
};
RK.externalRenderersEnabled = function () {
return !!(root.WOWNGEON_RUNTIME && root.WOWNGEON_RUNTIME.rendererCdnEnabled === true);
};
RK.isModeRuntimeAvailable = function (id) {
if (!RK.modeMeta || !RK.modeMeta(id)) return false;
if (id === '3d') {
return !!(RK.THREE && RK.THREE.THREE)
|| RK.localRenderersEnabled()
|| RK.externalRenderersEnabled();
}
return true;
};
// 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
// premium mode unlocks once the user has ANY unlocked pack for its projection.
RK.RENDER_MODES = [
{ id: 'tiles', label: 'Tiled', premium: false, projection: 'topdown' },
{ id: 'ascii', label: 'ASCII', premium: false, projection: 'topdown' },
{ id: 'iso', label: 'Iso', premium: true, projection: 'iso' },
{ id: '3d', label: '3D', premium: true, projection: '3d' }
];
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:
// ?unlock=1 -> on (sticky) ?unlock=0 -> off
RK.RENDER_MODE_TEST_UNLOCKS = false;
try {
var q = (root.location && root.location.search) || '';
var m = /[?&]unlock=([01])/.exec(q);
if (m) { try { root.localStorage.setItem('rk_unlock_all', m[1]); } catch (_) {} }
RK.RENDER_MODE_TEST_UNLOCKS = (root.localStorage && root.localStorage.getItem('rk_unlock_all') === '1');
} catch (_) { /* no location/localStorage */ }
RK.renderModeTestUnlocks = function () { return RK.RENDER_MODE_TEST_UNLOCKS === true; };
RK.modeMeta = function (id) {
for (var i = 0; i < RK.RENDER_MODES.length; i++) {
if (RK.RENDER_MODES[i].id === id) return RK.RENDER_MODES[i];
}
return null;
};
RK.canUseMode = function (id) {
var m = RK.modeMeta(id);
if (!m) return false;
if (!RK.isModeRuntimeAvailable(id)) return false;
if (RK.renderModeTestUnlocks && RK.renderModeTestUnlocks()) return true;
if (!m.premium) return true;
// A premium mode is available once the user has ANY unlocked pack for its projection.
if (m.projection && RK.unlockedPacks) return RK.unlockedPacks(m.projection).length > 0;
if (m.pack && RK.canUsePack) return RK.canUsePack(m.pack);
return !!RK.entitlements.premium;
};
RK.modeAvailability = function (id) {
var runtimeAvailable = RK.isModeRuntimeAvailable(id);
var usable = runtimeAvailable && RK.canUseMode(id);
return {
usable: usable,
runtimeAvailable: runtimeAvailable,
reason: !runtimeAvailable ? 'runtime_unavailable' : (usable ? null : 'entitlement_locked')
};
};
RK.createRenderer = function (mode, host, opts) {
if (!RK.canUseMode(mode)) return new RK.TileRenderer(host, opts);
if (mode === 'ascii' && RK.AsciiRenderer) return new RK.AsciiRenderer(host, opts);
if (mode === 'iso' && RK.IsoRenderer) return new RK.IsoRenderer(host, opts);
if (mode === '3d' && RK.ThreeRenderer && RK.THREE) {
try { return new RK.ThreeRenderer(host, opts); }
catch (e) {
if (root.console) console.warn('3D renderer failed; using tiled:', e && e.message);
return new RK.TileRenderer(host, opts);
}
}
if (mode === 'fancy') {
try {
if (!RK.FancyRenderer) throw new Error('fancy renderer not loaded');
return new RK.FancyRenderer(host, opts);
} catch (e) {
if (root.console) console.warn('Fancy renderer unavailable; using tiled:', e.message);
return new RK.TileRenderer(host, opts);
}
}
return new RK.TileRenderer(host, opts); // default / fallback
};
// Lazy-load PixiJS (+ @pixi/unsafe-eval for the strict CSP) only when Fancy is first needed,
// so ASCII/Tiled users never download the WebGL library.
var pixiLoading = false, pixiCbs = [];
RK.pixiReady = function () { return typeof PIXI !== 'undefined'; };
RK.ensurePixi = function (cb) {
if (RK.pixiReady()) { cb(true); return; }
if (!RK.externalRenderersEnabled()) { cb(false); return; }
pixiCbs.push(cb);
if (pixiLoading) return;
pixiLoading = true;
var inject = function (src, onload, onerror) {
var el = document.createElement('script');
el.src = src; el.onload = onload; el.onerror = onerror;
document.head.appendChild(el);
};
var done = function (ok) { var cbs = pixiCbs; pixiCbs = []; cbs.forEach(function (f) { f(ok); }); };
inject('https://cdn.jsdelivr.net/npm/pixi.js@7.4.2/dist/pixi.min.js', function () {
// @pixi/unsafe-eval patches the shader compiler on load (needed under the CSP).
inject('https://cdn.jsdelivr.net/npm/@pixi/unsafe-eval@7.4.2/dist/unsafe-eval.min.js',
function () { done(true); }, function () { done(false); });
}, function () { done(false); });
};
var threeLoading = false, threeCbs = [];
RK.threeReady = function () { return !!(RK.THREE && RK.THREE.THREE); };
RK.threeModuleSources = function () {
if (RK.localRenderersEnabled()) {
var version = String(root.WOWNGEON_RUNTIME.rendererLocalVersion || '');
if (!/^\d+\.\d+\.\d+$/.test(version)) return null;
var base = '/vendor/three/' + version;
return {
library: base + '/three.module.min.js',
loader: base + '/addons/loaders/GLTFLoader.js',
skeleton: base + '/addons/utils/SkeletonUtils.js'
};
}
if (!RK.externalRenderersEnabled()) return null;
return {
library: 'https://cdn.jsdelivr.net/npm/three@0.160.0/+esm',
loader: 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/loaders/GLTFLoader.js/+esm',
skeleton: 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/utils/SkeletonUtils.js/+esm'
};
};
RK.ensureThree = function (cb) {
if (RK.threeReady()) { cb(true); return; }
var sources = RK.threeModuleSources();
if (!sources) { cb(false); return; }
threeCbs.push(cb);
if (threeLoading) return;
threeLoading = true;
Promise.all([
import(sources.library),
import(sources.loader),
import(sources.skeleton)
]).then(function (mods) {
threeLoading = false;
RK.THREE = {
THREE: mods[0],
GLTFLoader: mods[1].GLTFLoader,
SkeletonUtils: mods[2]
};
var cbs = threeCbs; threeCbs = [];
cbs.forEach(function (f) { f(true); });
}).catch(function (e) {
threeLoading = false;
if (root.console) console.warn('Three renderer unavailable:', e && e.message);
var cbs = threeCbs; threeCbs = [];
cbs.forEach(function (f) { f(false); });
});
};
// Create a renderer, loading Pixi on demand for Fancy; falls back to Tiled if Pixi fails.
RK.createRendererAsync = function (mode, host, opts, cb) {
if (!RK.canUseMode(mode)) {
cb(new RK.TileRenderer(host, opts));
return;
}
if (mode === 'fancy') {
RK.ensurePixi(function (ok) {
if (!ok) { cb(new RK.TileRenderer(host, opts)); return; }
try { cb(new RK.FancyRenderer(host, opts)); }
catch (e) {
if (root.console) console.warn('Fancy renderer failed; using tiled:', e.message);
cb(new RK.TileRenderer(host, opts));
}
});
return;
}
if (mode === '3d') {
RK.ensureThree(function (ok) {
if (!ok) { cb(new RK.TileRenderer(host, opts)); return; }
try { cb(new RK.ThreeRenderer(host, opts)); }
catch (e) {
if (root.console) console.warn('3D renderer failed; using tiled:', e.message);
cb(new RK.TileRenderer(host, opts));
}
});
return;
}
cb(RK.createRenderer(mode, host, opts));
};
RK.loadMode = function (def) {
try {
var m = localStorage.getItem('rk_mode');
if (RK.modeMeta(m) && RK.canUseMode(m)) return m;
} catch (_) { /* ignore */ }
return def || 'tiles';
};
RK.saveMode = function (mode) {
try { localStorage.setItem('rk_mode', mode); } catch (_) { /* ignore */ }
};
})(window);
+378
View File
@@ -0,0 +1,378 @@
// Shared scene model + adapters for the render kit (RK).
//
// A Scene is a renderer-agnostic description of a grid world + entities. Any renderer
// (ASCII / tiled / fancy) draws the same Scene, and any surface (tavern / main game) can
// produce one via an adapter. This file is DOM-free so the adapters stay unit-testable.
(function (root) {
'use strict';
// 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.
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
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"
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.
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 }
};
// Layout character -> tile kind.
var TAVERN_TILE_OF = {
'#': 'wall', 'W': 'window', '.': 'floor', '@': 'floor', 'r': 'rug',
'=': 'bar', 'k': 'keg', 'h': 'shelf', 'T': 'table', 'c': 'chair',
'B': 'barrel', 'C': 'crate', 'D': 'door', 'i': 'torch', 'F': 'hearth'
};
var AVATAR_COLORS = { 'default': '#9aa4b2', green: '#3fb950', amber: '#d29922', red: '#f85149' };
// Build a Scene from a tavern room state ({ layout, cols, rows, occupants }).
function sceneFromTavern(state, youId) {
state = state || {};
var layout = state.layout || [];
var walkable = state.walkable || null;
var rows = state.rows || layout.length;
var cols = state.cols || (layout[0] ? layout[0].length : 0);
var grid = [];
for (var y = 0; y < rows; y++) {
var srcRow = layout[y] || '';
var row = [];
for (var x = 0; x < cols; x++) {
if (layout[y]) row.push(TAVERN_TILE_OF[srcRow[x]] || 'wall');
else if (walkable && walkable[y]) row.push(walkable[y][x] ? 'floor' : 'wall');
else row.push('wall');
}
grid.push(row);
}
var occ = state.occupants || [];
var entities = occ.map(function (o) {
var appearance = o.appearance || (o.avatar ? { avatar: o.avatar } : null);
var avatar = (appearance && appearance.avatar) || o.avatar;
return {
id: o.id,
x: o.x,
y: o.y,
kind: 'avatar',
avatar: avatar, // preserved so renderers can detect premium skins
appearance: appearance,
color: AVATAR_COLORS[avatar] || AVATAR_COLORS.default,
char: '@',
facing: o.facing || 'down',
label: o.name || null,
you: !!youId && o.id === youId
};
});
return {
cols: cols,
rows: rows,
grid: grid,
legend: TAVERN_LEGEND,
entities: entities,
background: '#0a0c0f'
};
}
var api = {
sceneFromTavern: sceneFromTavern,
TAVERN_LEGEND: TAVERN_LEGEND,
AVATAR_COLORS: AVATAR_COLORS
};
// ---- 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.
// Used by both the main game and the tavern spectator view.
var DUNGEON_LEGEND = {
wall: { char: '#', color: '#2a2f38', solid: true },
floor: { char: '·', color: '#15191f', solid: false },
floor2: { char: '·', color: '#181c22', solid: false },
entrance: { char: '<', color: '#3fb950', solid: false },
exit: { char: '>', color: '#d29922', solid: false },
treasure: { char: '$', color: '#fbbf24', solid: false },
// 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.
// 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' },
dark: { char: ' ', color: '#0a0c0f', solid: true }
};
// Map dungeon tile characters to scene tile kinds.
function dungeonTileKind(ch) {
if (ch === '#') return 'wall';
if (ch === 'torch' || ch === 'i') return 'torch';
if (ch === 'L') return 'lava';
if (ch === 'P') return 'poison';
if (ch === '^') return 'spikes';
if (ch === "'1" || ch === 0) return 'floor';
if (ch === "'2") return 'floor2';
if (ch === '<') return 'entrance';
if (ch === '>') return 'exit';
if (ch === '$' || ch === '$W' || ch === '$M') return 'treasure';
return 'floor';
}
// 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;
for (var i = 0; i < maps.length; i++) {
var m = maps[i];
if (!m || typeof m !== 'object') continue;
for (var yk in m) {
if (!Object.prototype.hasOwnProperty.call(m, yk)) continue;
var yi = parseInt(yk, 10);
if (!isFinite(yi)) continue;
if (yi + 1 > rows) rows = yi + 1;
var r = m[yk];
if (r && typeof r === 'object') {
for (var xk in r) {
if (!Object.prototype.hasOwnProperty.call(r, xk)) continue;
var xi = parseInt(xk, 10);
if (isFinite(xi) && xi + 1 > cols) cols = xi + 1;
}
}
}
}
return { rows: rows, cols: cols };
}
function normalizeGameStateOpts(opts) {
// 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 : {};
}
function pickCameraPlayer(players, state, opts) {
if (!players || !players.length) return null;
var viewerId = opts.viewerId || opts.socketId || null;
var focusId = opts.focusPlayerId || null;
var i, p;
// Match ticks are broadcast once, so the client socket id is the authoritative local marker
// when the server cannot include a recipient-specific `you` flag.
if (viewerId) {
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && p.id === viewerId) return p;
}
}
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && p.you === true) return p;
}
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && focusId && p.id === focusId) return p;
}
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && state.winnerId && p.id === state.winnerId) return p;
}
// 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;
}
return players[0] || null;
}
function pointOf(value) {
if (!value) return null;
if (Array.isArray(value)) return { x: value[0], y: value[1] };
if (typeof value.x === 'number' && typeof value.y === 'number') return { x: value.x, y: value.y };
return null;
}
function racerColor(player, index, isYou) {
if (isYou) return '#67e8f9';
if (player && player.alive === false) return '#6b7280';
if (player && (player.finished || player.escaped)) return '#fbbf24';
var palette = ['#9aa4b2', '#a78bfa', '#4ade80', '#fb7185', '#60a5fa', '#f97316'];
var raw = String((player && player.id) || index), hash = 0;
for (var i = 0; i < raw.length; i++) hash = ((hash * 31) + raw.charCodeAt(i)) >>> 0;
return palette[hash % palette.length];
}
function sceneFromGameState(state, opts) {
state = state || {};
opts = normalizeGameStateOpts(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, 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;
var cols = state.dungeonCols || dims.cols;
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. 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);
var grid = [];
var lightGrid = [];
for (var y = 0; y < rows; y++) {
var row = [];
var lrow = [];
for (var x = 0; x < cols; x++) {
var ch = null;
var isVisible = visible[y] && visible[y][x] !== undefined;
if (isVisible) {
ch = visible[y][x];
} else if (explored[y] && explored[y][x] !== undefined) {
ch = explored[y][x];
}
if (ch === null || ch === undefined || ch === ' ') {
row.push('dark');
lrow.push(0);
} else if (isVisible) {
row.push(dungeonTileKind(ch));
// Lighting: 0 = fully lit, higher = darker. Convert to brightness (1 = lit).
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, 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));
}
}
grid.push(row);
lightGrid.push(lrow);
}
var entities = [];
// 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, 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.
// 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);
var treasure = pointOf(state.treasure);
if (entrance && seen(entrance.x, entrance.y)) {
entities.push({ id: 'entrance', x: entrance.x, y: entrance.y, kind: 'feature', char: '<', color: '#3fb950', label: null });
}
if (exit && seen(exit.x, exit.y)) {
entities.push({ id: 'exit', x: exit.x, y: exit.y, kind: 'feature', char: '>', color: '#d29922', label: null });
}
if (treasure && seen(treasure.x, treasure.y) && !(state.treasure && state.treasure.carrierId)) {
var tChar = opts.cryptoType === 'XMR' ? '$M' : '$W';
entities.push({ id: 'treasure', x: treasure.x, y: treasure.y, kind: 'feature', char: tChar, color: '#fbbf24', label: null });
}
// Items, only once explored.
if (state.items) {
for (var key in state.items) {
if (state.items.hasOwnProperty(key)) {
var item = state.items[key];
if (item && typeof item.x === 'number' && seen(item.x, item.y)) {
entities.push({ id: 'item:' + key, x: item.x, y: item.y, kind: 'item', char: '$', color: '#fbbf24', label: null });
}
}
}
}
// 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,
kind: 'monster', char: '~', color: '#f85149', label: null
});
}
// Multiplayer racers. Preserve public status fields useful to HUD/render extensions while
// keeping the shared entity contract identical to solo (`kind: player`, appearance, facing).
if (matchPlayers.length) {
var viewerId = opts.viewerId || opts.socketId || null;
for (var pi = 0; pi < matchPlayers.length; pi++) {
var rp = matchPlayers[pi];
if (!rp || typeof rp.x !== 'number' || typeof rp.y !== 'number') continue;
var isYou = viewerId ? rp.id === viewerId : rp.you === true;
var appearance = rp.appearance || (rp.avatar ? { avatar: rp.avatar } : null) || { avatar: 'default' };
entities.push({
id: rp.id || ('player:' + pi), x: rp.x, y: rp.y,
kind: 'player', char: '@', color: racerColor(rp, pi, isYou),
facing: rp.facing || null, label: rp.name || null,
avatar: appearance.avatar || rp.avatar || 'default', appearance: appearance,
you: isYou, cameraTarget: rp === cameraPlayer,
alive: rp.alive !== false, finished: !!rp.finished, escaped: !!rp.escaped,
hasTreasure: !!rp.hasTreasure, placement: rp.placement == null ? null : rp.placement
});
}
// Single-player protocol.
} else if (state.player) {
var playerEntity = {
id: 'player', x: state.player.x, y: state.player.y,
kind: 'player', char: '@', color: '#9aa4b2',
// 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
};
// Attach the player's appearance if available (for render-kit character rendering).
if (opts.playerAppearance) {
playerEntity.avatar = opts.playerAppearance.avatar || 'default';
playerEntity.appearance = opts.playerAppearance;
} else {
playerEntity.avatar = 'default';
playerEntity.appearance = { avatar: 'default', tint: 'none', equipment: { body: 'none', head: 'none', shield: 'none', weapon: 'none' } };
}
entities.push(playerEntity);
}
return {
cols: cols,
rows: rows,
grid: grid,
legend: DUNGEON_LEGEND,
entities: entities,
lightGrid: lightGrid,
background: '#0a0c0f',
isDungeon: true
};
}
api.sceneFromGameState = sceneFromGameState;
api.DUNGEON_LEGEND = DUNGEON_LEGEND;
root.RK = root.RK || {};
root.RK.scene = api;
// 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;
})(typeof window !== 'undefined' ? window : this);
+117
View File
@@ -0,0 +1,117 @@
// 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.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
// Skin registry. `sheet` is hosted under assets/generated (gitignored / CDN-delivered).
RK.SKINS = {
'monero-knight': {
id: 'monero-knight', label: 'Monero Knight', premium: true, pack: 'generated-skins',
sheet: 'assets/generated/monero_knight_walk.webp',
frameW: 190, frameH: 233, cols: 8, rows: 4, fps: 10,
dirRows: { down: 0, left: 1, right: 2, up: 3 },
scale: 2.0, // sprite height ≈ scale × tile cell
moveWindowMs: 350 // consider "moving" (animate) if position changed this recently
},
'wownero-rogue': {
id: 'wownero-rogue', label: 'Wownero Rogue', premium: true, pack: 'generated-skins',
sheet: 'assets/generated/wownero_walk.webp',
frameW: 169, frameH: 223, cols: 8, rows: 4, fps: 10,
dirRows: { down: 0, left: 1, right: 2, up: 3 },
scale: 2.0, moveWindowMs: 350
},
'cypher-operative': {
id: 'cypher-operative', label: 'Cypher Operative', premium: true, pack: 'generated-skins',
sheet: 'assets/generated/operative_walk.webp',
frameW: 160, frameH: 225, cols: 8, rows: 4, fps: 10,
dirRows: { down: 0, left: 1, right: 2, up: 3 },
scale: 2.0, moveWindowMs: 350
}
};
RK.isSkin = function (id) { return !!(id && RK.SKINS[id]); };
// --- Lazy sheet loading ------------------------------------------------------------------
var sheets = {}; // id -> { ready, img, base, texCache, cbs }
RK.loadSkin = function (id) {
var s = RK.SKINS[id];
if (!s) return null;
if (sheets[id]) return sheets[id];
var rec = sheets[id] = { ready: false, cbs: [] };
var img = new Image();
img.onload = function () {
rec.ready = true; rec.img = img;
rec.cbs.forEach(function (cb) { try { cb(rec); } catch (_) {} });
rec.cbs = [];
};
img.onerror = function () { if (root.console) console.warn('skin sheet failed:', s.sheet); };
img.src = s.sheet;
return rec;
};
RK.skinSheet = function (id) { return (sheets[id] && sheets[id].ready) ? sheets[id] : null; };
// --- Movement-aware frame selection ------------------------------------------------------
var last = {}; // entity id -> { x, y, t }
RK.skinFrame = function (skin, e, nowMs) {
var st = last[e.id] || (last[e.id] = { x: e.x, y: e.y, t: 0 });
if (e.x !== st.x || e.y !== st.y) { st.x = e.x; st.y = e.y; st.t = nowMs; }
var moving = (nowMs - st.t) < (skin.moveWindowMs || 350);
var row = (skin.dirRows && skin.dirRows[e.facing] != null) ? skin.dirRows[e.facing] : 0;
var col = moving ? Math.floor(nowMs / 1000 * skin.fps) % skin.cols : 0; // idle -> frame 0
return { row: row, col: col };
};
// --- Canvas draw (TileRenderer). Returns false (and kicks a lazy load) if not ready. ------
RK.drawSkinCanvas = function (ctx, e, cell, nowMs) {
var rec = RK.skinSheet(e.avatar);
if (!rec) { RK.loadSkin(e.avatar); return false; }
var s = RK.SKINS[e.avatar];
var fr = RK.skinFrame(s, e, nowMs);
var dh = cell * (s.scale || 1.7);
var dw = dh * (s.frameW / s.frameH);
var cx = e.x * cell + cell / 2;
var dx = cx - dw / 2;
var dy = (e.y * cell + cell) - dh; // feet at tile bottom
ctx.imageSmoothingEnabled = true;
// Warm backlight so a dark character separates from the dark background.
var midY = dy + dh * 0.45;
var halo = ctx.createRadialGradient(cx, midY, 0, cx, midY, dw * 0.8);
halo.addColorStop(0, 'rgba(255,226,180,0.30)');
halo.addColorStop(1, 'rgba(255,226,180,0)');
ctx.fillStyle = halo;
ctx.beginPath(); ctx.arc(cx, midY, dw * 0.8, 0, Math.PI * 2); ctx.fill();
if (e.you) {
ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.lineWidth = 2;
ctx.beginPath();
ctx.ellipse(cx, e.y * cell + cell - 2, dw * 0.3, cell * 0.16, 0, 0, Math.PI * 2);
ctx.stroke();
}
ctx.drawImage(rec.img, fr.col * s.frameW, fr.row * s.frameH, s.frameW, s.frameH, dx, dy, dw, dh);
if (e.label) {
ctx.fillStyle = '#d7dbe0'; ctx.font = '11px monospace'; ctx.textAlign = 'center';
ctx.fillText(e.label, cx, dy - 2);
}
return true;
};
// --- Pixi texture for a skin frame (FancyRenderer), cached. ------------------------------
RK.skinTexture = function (id, row, col) {
var rec = RK.skinSheet(id);
if (!rec || typeof PIXI === 'undefined') return null;
var s = RK.SKINS[id];
if (!rec.base) {
rec.base = PIXI.BaseTexture.from(rec.img);
rec.base.scaleMode = PIXI.SCALE_MODES.LINEAR;
rec.texCache = {};
}
var key = row + ',' + col;
if (!rec.texCache[key]) {
rec.texCache[key] = new PIXI.Texture(rec.base, new PIXI.Rectangle(col * s.frameW, row * s.frameH, s.frameW, s.frameH));
}
return rec.texCache[key];
};
})(window);
+320
View File
@@ -0,0 +1,320 @@
// 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. 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 || {};
var SP = RK.SPGame = RK.SPGame || {};
SP._renderer = null;
SP._mode = null;
SP._live = false;
function doc() { return root.document; }
function gameDisplay() { return doc() && doc().getElementById('game-display'); }
// Keyboard movement is intentionally scoped to #game-display so typing in chat and controls
// can never move the player. UI controls that affect the live renderer call this immediately
// after activation to restore that explicit gameplay focus.
SP.focusGameplay = function () {
var gd = gameDisplay();
if (!gd || !gd.focus) return false;
gd.setAttribute('tabindex', '-1');
try { gd.focus({ preventScroll: true }); }
catch (_) { gd.focus(); }
if (root.UI && UI.updateFocusIndicator) UI.updateFocusIndicator();
return doc().activeElement === gd;
};
// 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;
var host = doc().getElementById('rk-game-host');
if (!host) {
host = doc().createElement('div');
host.id = 'rk-game-host';
// 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);
}
return host;
}
SP.available = function () {
return !!(RK.createRenderer && RK.sceneFromGameState && gameDisplay());
};
SP.mode = function () {
if (!SP._mode) {
var m = (RK.loadMode && RK.loadMode('tiles')) || 'tiles';
SP._mode = (RK.canUseMode && !RK.canUseMode(m)) ? 'tiles' : m;
}
return SP._mode;
};
SP.setMode = function (mode) {
if (RK.canUseMode && !RK.canUseMode(mode)) return false;
if (SP._mode !== mode) SP._zoom = null; // let the new projection use its legible default
SP._mode = mode;
if (RK.saveMode) RK.saveMode(mode);
SP._destroyRenderer();
if (SP._live && SP._lastState) SP.render(SP._lastState, SP._lastOpts);
return true;
};
// Re-mount after a pack switch (same mode, new active pack/assets).
SP.refreshPack = function () {
SP._destroyRenderer();
if (SP._live && SP._lastState) SP.render(SP._lastState, SP._lastOpts);
};
SP._destroyRenderer = function () {
if (SP._renderer && SP._renderer.destroy) { try { SP._renderer.destroy(); } catch (_) {} }
SP._renderer = null;
};
SP._setZoom = function (next) {
SP._zoom = Math.max(0.4, Math.min(4, Number(next) || SP._defaultZoom()));
var readout = doc() && doc().getElementById('rk-sp-camera-zoom');
if (readout) readout.textContent = Math.round(SP._zoom * 100) + '%';
SP._applyCamera();
};
SP._mountCameraControls = function (host) {
if (!host || host._rkCameraControls || !doc()) return;
var controls = doc().createElement('div');
controls.id = 'rk-sp-camera-controls';
controls.className = 'rk-camera-controls';
controls.setAttribute('aria-label', 'Dungeon camera controls');
controls.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:20;display:flex;' +
'align-items:center;gap:4px;padding:4px;background:rgba(4,7,10,.82);border:1px solid rgba(255,255,255,.2);' +
'border-radius:7px;box-shadow:0 4px 18px rgba(0,0,0,.45);font:12px monospace;';
function addButton(label, title, action) {
var b = doc().createElement('button');
b.type = 'button'; b.textContent = label; b.title = title; b.setAttribute('aria-label', title);
b.style.cssText = 'min-width:30px;height:28px;padding:0 7px;background:#151b22;color:#e5e7eb;' +
'border:1px solid #3b4552;border-radius:4px;cursor:pointer;font:inherit;';
b.addEventListener('click', function (e) {
e.stopPropagation();
action();
SP.focusGameplay();
});
controls.appendChild(b);
}
addButton('−', 'Zoom out', function () { SP._setZoom(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) / 1.18); });
var readout = doc().createElement('span');
readout.id = 'rk-sp-camera-zoom';
readout.style.cssText = 'min-width:42px;text-align:center;color:#a7f3d0;';
controls.appendChild(readout);
addButton('+', 'Zoom in', function () { SP._setZoom(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) * 1.18); });
addButton('⌂', 'Reset camera', function () { SP._zoom = null; SP._camX = null; SP._setZoom(SP._defaultZoom()); });
host.appendChild(controls);
host._rkCameraControls = controls;
readout.textContent = Math.round(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) * 100) + '%';
};
SP._ensureRenderer = function () {
if (SP._renderer) return SP._renderer;
var host = rkHost();
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, 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;
RK.ensureThree(function (ok) {
SP._threePending = false;
if (ok && SP._live && SP.mode() === '3d') {
SP._destroyRenderer();
if (SP._lastState) SP.render(SP._lastState, SP._lastOpts);
}
});
}
}
SP._renderer = RK.createRenderer(mode, host, { cell: 24 });
// 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';
// 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');
c.style.setProperty('image-rendering', 'pixelated', 'important');
}
if (!host._rkZoomBound) {
host._rkZoomBound = true;
host.addEventListener('wheel', function (ev) {
ev.preventDefault();
// 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 });
host.addEventListener('dblclick', function (ev) {
if (ev.target && ev.target.closest && ev.target.closest('.rk-camera-controls')) return;
SP._zoom = null; SP._camX = null; SP._setZoom(SP._defaultZoom());
});
var points = {}, pinchDistance = null;
host.addEventListener('pointerdown', function (ev) {
if (ev.target && ev.target.closest && ev.target.closest('.rk-camera-controls')) return;
points[ev.pointerId] = { x: ev.clientX, y: ev.clientY };
try { host.setPointerCapture(ev.pointerId); } catch (_) {}
});
host.addEventListener('pointermove', function (ev) {
if (!points[ev.pointerId]) return;
points[ev.pointerId] = { x: ev.clientX, y: ev.clientY };
var ids = Object.keys(points);
if (ids.length < 2) return;
var a = points[ids[0]], b = points[ids[1]];
var distance = Math.hypot(a.x - b.x, a.y - b.y);
if (pinchDistance) SP._setZoom(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) * (distance / pinchDistance));
pinchDistance = distance;
});
function release(ev) { delete points[ev.pointerId]; pinchDistance = null; }
host.addEventListener('pointerup', release);
host.addEventListener('pointercancel', release);
}
SP._mountCameraControls(host);
return SP._renderer;
};
// Mode-aware default zoom: iso tiles are large (84px) so they want less magnification than the
// small tiled/ascii cells (~24px).
SP._defaultZoom = function () {
if (SP._renderer && SP._renderer.name === 'iso') return 1.0;
if (SP._renderer && SP._renderer.name === '3d') return 1.05;
return 1.7;
};
// 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 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';
r.canvas.style.left = '0';
r.canvas.style.top = '0';
return;
}
var scale = (SP._zoom != null) ? SP._zoom : SP._defaultZoom();
var fp = r.focusPoint;
// 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;
fp = { x: (SP._lastState.player.x + 0.5) * _c, y: (SP._lastState.player.y + 0.5) * _c };
}
r.canvas.style.transformOrigin = '0 0';
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, 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 {
SP._camX += (tx - SP._camX) * 0.3;
SP._camY += (ty - SP._camY) * 0.3;
}
r.canvas.style.transform = 'translate(' + SP._camX + 'px,' + SP._camY + 'px) scale(' + scale + ')';
};
function toggleLegacy(hide) {
var gd = gameDisplay();
if (!gd) return;
var kids = gd.children;
for (var i = 0; i < kids.length; i++) {
if (kids[i].id === 'rk-game-host') continue;
kids[i].style.display = hide ? 'none' : '';
}
}
// Show the render-kit view (hide the ROT splash canvases). Call on game start.
SP.show = function () {
if (!SP.available()) return false;
var host = rkHost();
if (!host) return false;
host.style.display = 'block';
toggleLegacy(true);
SP._live = true;
SP._camX = null; // snap-center on the first frame of a new game
SP._startCameraLoop();
return true;
};
// 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() {
if (!SP._live) { SP._camRaf = null; return; }
SP._applyCamera();
SP._camRaf = root.requestAnimationFrame(tick);
}
SP._camRaf = root.requestAnimationFrame(tick);
};
// Back to the ROT view (splash / win / lose). Call on game end.
SP.hide = function () {
SP._live = false;
SP._destroyRenderer();
var host = doc() && doc().getElementById('rk-game-host');
if (host) host.style.display = 'none';
toggleLegacy(false);
};
// Build the Scene from the SP client render-state and draw it. Returns true if it rendered
// (caller then skips the legacy renderer). Non-destructive on failure.
SP.render = function (clientState, opts) {
if (!SP._live || !SP.available()) return false;
var r = SP._ensureRenderer();
if (!r) return false;
opts = opts || {};
SP._lastState = clientState;
SP._lastOpts = opts;
try {
var scene = RK.sceneFromGameState(clientState, {
cryptoType: opts.cryptoType,
playerAppearance: opts.playerAppearance,
isSpectating: opts.isSpectating
});
r.render(scene);
SP._applyCamera();
return true;
} catch (e) {
if (root.console) console.warn('SPGame render failed; falling back to legacy:', e && e.message);
return false;
}
};
if (typeof module !== 'undefined' && module.exports) module.exports = SP;
})(typeof window !== 'undefined' ? window : this);
+488
View File
@@ -0,0 +1,488 @@
// 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
// come from the server snapshot. Speech bubbles pop above any occupant (NPC or real player)
// when they speak.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
// roundRect polyfill for older browsers.
if (!root.CanvasRenderingContext2D.prototype.roundRect) {
root.CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
if (w < 2 * r) r = w / 2;
if (h < 2 * r) r = h / 2;
this.beginPath();
this.moveTo(x + r, y);
this.arcTo(x + w, y, x + w, y + h, r);
this.arcTo(x + w, y + h, x, y + h, r);
this.arcTo(x, y + h, x, y, r);
this.arcTo(x, y, x + w, y, r);
this.closePath();
return this;
};
}
// ---- 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.",
"I've seen braver than you not return.", "House special: liquid courage.",
"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 = [
"Another round!", "I almost made it out...", "The dungeon claims another.",
"Heard someone found the bag!", "Cheers!", "This ale is questionable.",
"Anyone seen my shield?", "Last time I swear it was right there...",
"The monster was RIGHT behind me.", "Need more credits...", "One more run.",
"I used to be an adventurer too.", "Bloody hell, that was close.", "Pour me another.",
"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."];
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
// ---- NPC definitions --------------------------------------------------------
// NPCs are identified by a prefix so they don't collide with real socket ids.
var NPC_PREFIX = 'npc:';
function makeNPC(id, kind, avatar, x, y, opts) {
opts = opts || {};
return {
id: NPC_PREFIX + id,
kind: kind,
avatar: avatar,
appearance: { avatar: avatar, tint: 'none', equipment: { body: 'none', head: 'none', shield: 'none', weapon: 'none' } },
x: x, y: y, facing: 'down',
targetX: x, targetY: y,
moveCooldown: 0,
sitTimer: 0,
// Stagger the first lines so entering the room feels conversational instead of every
// patron opening a bubble on the same frame.
speechTimer: opts.speechTimer == null ? 1800 + Math.random() * 7000 : opts.speechTimer,
speech: null, speechUntil: 0,
color: opts.color || '#d7dbe0',
label: opts.label || null,
role: opts.role || 'patron',
roamArea: opts.roamArea || null
};
}
function bartendersArea(cols, rows) {
// Behind the bar: the row between the top wall and the counter (y=1). Sealed off by the
// counter, so the bartender stays back there and never wanders onto the customer floor.
return { minY: 1, maxY: 1, minX: 3, maxX: Math.max(5, cols - 5) };
}
function patronsArea(cols, rows) {
// Patrons roam the middle/lower floor.
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.
return { minY: 4, maxY: rows - 2, minX: 1, maxX: cols - 2 };
}
// ---- Speech bubbles ---------------------------------------------------------
var BUBBLE_FONT = '12px ui-monospace, Menlo, Consolas, monospace';
var BUBBLE_PADDING = 8;
var BUBBLE_RADIUS = 6;
var BUBBLE_TAIL = 7;
var BUBBLE_DURATION = 4200;
var BUBBLE_FADE = 500;
function measureBubble(ctx, text) {
ctx.font = BUBBLE_FONT;
var metrics = ctx.measureText(text);
var w = Math.ceil(metrics.width) + BUBBLE_PADDING * 2;
var h = 22 + BUBBLE_PADDING * 2;
return { w: w, h: h };
}
function drawBubble(ctx, x, y, text, alpha) {
if (alpha <= 0 || !text) return;
var dim = measureBubble(ctx, text);
var bw = dim.w, bh = dim.h;
// Clamp so the bubble stays on screen.
var bx = Math.max(4, Math.min(x - bw / 2, ctx.canvas.width - bw - 4));
var by = y - bh - BUBBLE_TAIL;
if (by < 4) by = y + BUBBLE_TAIL + 4; // flip below if no room above
ctx.save();
ctx.globalAlpha = alpha;
ctx.font = BUBBLE_FONT;
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
// Bubble body (rounded rect).
ctx.fillStyle = 'rgba(18,24,32,0.94)';
ctx.strokeStyle = 'rgba(120,140,165,0.55)';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.roundRect(bx, by, bw, bh, BUBBLE_RADIUS);
ctx.fill();
ctx.stroke();
// Tail pointer.
var tailX = Math.max(bx + 12, Math.min(x, bx + bw - 12));
ctx.fillStyle = 'rgba(18,24,32,0.94)';
ctx.beginPath();
ctx.moveTo(tailX - 5, by + bh);
ctx.lineTo(tailX + 5, by + bh);
ctx.lineTo(tailX, by + bh + (by < y ? BUBBLE_TAIL : -BUBBLE_TAIL));
ctx.closePath();
ctx.fill();
// Text.
ctx.fillStyle = '#e8edf3';
ctx.fillText(text, bx + bw / 2, by + bh / 2);
ctx.restore();
}
// ---- The TavernLife controller ----------------------------------------------
function TavernLife(host, getScene, getCell) {
this.host = host;
this.getScene = getScene;
this.getCell = getCell || function () { return 24; };
this.npcs = [];
this.bubbles = {}; // occupantId -> { text, until, born }
this._overlay = null;
this._octx = null;
this._raf = null;
this._lastTick = 0;
this._spawned = false;
this._realBubbles = {}; // socketId -> { text, until } from real chat
}
TavernLife.prototype._ensureOverlay = function () {
if (this._overlay && this._overlay.parentNode) return this._octx;
var cv = root.document.createElement('canvas');
cv.className = 'tavern-life-overlay';
cv.style.cssText = 'position:absolute;inset:0;pointer-events:none;z-index:10;';
this.host.style.position = this.host.style.position || 'relative';
this.host.appendChild(cv);
this._overlay = cv;
this._octx = cv.getContext('2d');
return this._octx;
};
TavernLife.prototype._syncOverlaySize = function (w, h) {
var ctx = this._ensureOverlay();
if (!ctx) return;
if (this._overlay.width !== w) this._overlay.width = w;
if (this._overlay.height !== h) this._overlay.height = h;
return ctx;
};
TavernLife.prototype.spawn = function () {
if (this._spawned) return;
this._spawned = true;
var scene = this.getScene();
if (!scene) return;
var cols = scene.cols, rows = scene.rows;
var grid = scene.grid;
// Find walkable tiles for spawning.
function isFloor(x, y) {
return y >= 0 && y < rows && x >= 0 && x < cols && grid[y] && grid[y][x] === 'floor';
}
function findFloor(cx, cy) {
for (var r = 1; r < 8; r++) {
for (var dy = -r; dy <= r; dy++) {
for (var dx = -r; dx <= r; dx++) {
var x = cx + dx, y = cy + dy;
if (isFloor(x, y)) return { x: x, y: y };
}
}
}
return { x: 1, y: 1 };
}
// Bartender BEHIND the bar (row 1, between the top wall and the counter).
var barSpot = findFloor(Math.floor(cols / 2), 1);
var bartender = makeNPC('bartender', 'bartender', 'char-merchant', barSpot.x, barSpot.y, {
label: 'Bartender', color: '#c9a25e', role: 'bartender',
roamArea: bartendersArea(cols, rows)
});
this.npcs.push(bartender);
// 2-3 patrons near tables (middle area).
var patronAvatars = ['char-villager', 'char-elder', 'char-bard', 'char-wizard', 'char-ranger', 'char-rogue'];
var patronColors = ['#7eb6c9', '#c9a0d4', '#a0c97e', '#d4b0a0', '#8fa0d4'];
var numPatrons = 2 + Math.floor(Math.random() * 2);
for (var i = 0; i < numPatrons; i++) {
var px = 4 + Math.floor(Math.random() * (cols - 8));
var py = 5 + Math.floor(Math.random() * (rows - 8));
var spot = findFloor(px, py);
this.npcs.push(makeNPC('patron' + i, 'patron', patronAvatars[i % patronAvatars.length],
spot.x, spot.y, {
label: 'Patron', color: patronColors[i % patronColors.length],
roamArea: patronsArea(cols, rows),
sitTimer: 2000 + Math.random() * 4000
}));
}
// 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)
});
cat.catSprite = (RK.randomCatId ? RK.randomCatId() : 'cat3');
this.npcs.push(cat);
};
TavernLife.prototype._pickTarget = function (npc, scene) {
var area = npc.roamArea;
if (!area) return;
var grid = scene.grid;
var cols = scene.cols, rows = scene.rows;
for (var tries = 0; tries < 12; tries++) {
var tx = area.minX + Math.floor(Math.random() * (area.maxX - area.minX + 1));
var ty = area.minY + Math.floor(Math.random() * (area.maxY - area.minY + 1));
if (ty >= 0 && ty < rows && tx >= 0 && tx < cols && grid[ty] && grid[ty][tx] === 'floor') {
npc.targetX = tx;
npc.targetY = ty;
return;
}
}
};
TavernLife.prototype._moveNPC = function (npc, scene, dt) {
if (npc.sitTimer > 0) {
npc.sitTimer -= dt;
return;
}
npc.moveCooldown -= dt;
if (npc.moveCooldown > 0) return;
// Arrived at target?
if (npc.x === npc.targetX && npc.y === npc.targetY) {
var sitTime = npc.role === 'cat' ? 1000 + Math.random() * 2000 : 3000 + Math.random() * 5000;
npc.sitTimer = sitTime;
this._pickTarget(npc, scene);
return;
}
// Step toward target (one tile, cardinal only).
var dx = npc.targetX - npc.x;
var dy = npc.targetY - npc.y;
var stepX = 0, stepY = 0;
if (Math.abs(dx) >= Math.abs(dy) && dx !== 0) stepX = Math.sign(dx);
else if (dy !== 0) stepY = Math.sign(dy);
else if (dx !== 0) stepX = Math.sign(dx);
var nx = npc.x + stepX, ny = npc.y + stepY;
var grid = scene.grid;
if (ny >= 0 && ny < scene.rows && nx >= 0 && nx < scene.cols && grid[ny] && grid[ny][nx] === 'floor') {
npc.x = nx; npc.y = ny;
if (stepX < 0) npc.facing = 'left';
else if (stepX > 0) npc.facing = 'right';
else if (stepY < 0) npc.facing = 'up';
else if (stepY > 0) npc.facing = 'down';
} else {
// Blocked: pick a new target.
this._pickTarget(npc, scene);
}
// Cat moves faster; bartender slower.
npc.moveCooldown = npc.role === 'cat' ? 280 : npc.role === 'bartender' ? 500 : 380;
};
TavernLife.prototype._maybeSpeak = function (npc, now) {
if (npc.speech && now < npc.speechUntil) return;
npc.speechTimer -= 16;
if (npc.speechTimer > 0) return;
var lines;
if (npc.role === 'bartender') lines = BARTENDER_LINES;
else if (npc.role === 'cat') lines = CAT_LINES;
else lines = PATRON_LINES;
npc.speech = pick(lines);
npc.speechUntil = now + BUBBLE_DURATION;
npc.speechTimer = 8000 + Math.random() * 12000; // next speech gap
if (npc.role === 'cat') npc.speechTimer = 6000 + Math.random() * 10000;
};
// Inject NPC entities into a scene so the renderer draws them.
TavernLife.prototype.injectInto = function (scene) {
if (!scene || !this._spawned) return scene;
if (!scene._npcInjected) {
for (var i = 0; i < this.npcs.length; i++) {
var npc = this.npcs[i];
scene.entities.push({
id: npc.id,
x: npc.x, y: npc.y,
kind: npc.role === 'cat' ? 'cat' : 'avatar',
avatar: npc.avatar,
appearance: npc.appearance,
catSprite: npc.catSprite || null,
color: npc.color,
char: npc.role === 'cat' ? 'c' : '@',
facing: npc.facing,
label: npc.label,
you: false,
_npc: true
});
}
scene._npcInjected = true;
}
return scene;
};
// Show a speech bubble for a real player (called on chat_broadcast).
TavernLife.prototype.showPlayerBubble = function (socketId, text) {
this._realBubbles[socketId] = { text: text, until: Date.now() + BUBBLE_DURATION };
};
// Get the screen position of an entity for a given renderer/cell size.
// This is renderer-agnostic: top-down uses grid coords * cell; iso uses projection.
TavernLife.prototype._entityScreenPos = function (e, scene, cell, mode) {
var pos;
if (mode === 'iso') {
// Match IsoRenderer._project: originX = margin + rows * tileW/2 + tileW; originY = margin + imageH
var tileW = (RK.isoAssets && RK.isoAssets.tile && RK.isoAssets.tile.w) || 84;
var tileH = (RK.isoAssets && RK.isoAssets.tile && RK.isoAssets.tile.h) || 42;
var imageH = (RK.isoAssets && RK.isoAssets.tile && RK.isoAssets.tile.imageH) || 184;
var margin = 28;
var originX = margin + scene.rows * tileW / 2 + tileW;
var originY = margin + imageH;
pos = {
x: originX + (e.x - e.y) * tileW / 2,
y: originY + (e.x + e.y) * tileH / 2
};
} else if (mode === '3d') {
// 3D renderer uses Three.js; we can't easily get screen coords.
// Skip speech bubbles for 3D mode.
return null;
} else {
// top-down / ascii / fancy: grid coords * cell
pos = { x: e.x * cell + cell / 2, y: e.y * cell + cell / 2 };
}
var view = this._viewTransform;
if (view) return { x: view.left + pos.x * view.scaleX, y: view.top + pos.y * view.scaleY };
return pos;
};
TavernLife.prototype._drawBubbles = function (scene, cell, mode, now) {
var ctx = this._octx;
if (!ctx || !scene) return;
ctx.clearRect(0, 0, this._overlay.width, this._overlay.height);
// NPC bubbles.
for (var i = 0; i < this.npcs.length; i++) {
var npc = this.npcs[i];
if (!npc.speech || now >= npc.speechUntil) continue;
var alpha = 1;
var remaining = npc.speechUntil - now;
if (remaining < BUBBLE_FADE) alpha = remaining / BUBBLE_FADE;
var pos = this._entityScreenPos(npc, scene, cell, mode);
if (pos) drawBubble(ctx, pos.x, pos.y - cell * 0.3 * ((this._viewTransform && this._viewTransform.scaleY) || 1), npc.speech, alpha);
}
// Real player bubbles (from chat).
var occupants = scene.entities;
for (var j = 0; j < occupants.length; j++) {
var e = occupants[j];
if (e._npc) continue;
var bubble = this._realBubbles[e.id];
if (!bubble || now >= bubble.until) {
if (bubble) delete this._realBubbles[e.id];
continue;
}
var rAlpha = 1;
var rRemaining = bubble.until - now;
if (rRemaining < BUBBLE_FADE) rAlpha = rRemaining / BUBBLE_FADE;
var rPos = this._entityScreenPos(e, scene, cell, mode);
if (rPos) drawBubble(ctx, rPos.x, rPos.y - cell * 0.3 * ((this._viewTransform && this._viewTransform.scaleY) || 1), bubble.text, rAlpha);
}
};
// Main update: called every frame via rAF.
TavernLife.prototype.update = function (scene, cell, mode) {
if (!scene || !this._spawned) return;
var now = Date.now();
var dt = now - (this._lastTick || now);
this._lastTick = now;
// Update NPC movement and speech.
for (var i = 0; i < this.npcs.length; i++) {
this._moveNPC(this.npcs[i], scene, dt);
this._maybeSpeak(this.npcs[i], now);
}
// Update NPC entity positions in the scene.
for (var j = 0; j < this.npcs.length; j++) {
var npc = this.npcs[j];
for (var k = 0; k < scene.entities.length; k++) {
if (scene.entities[k].id === npc.id) {
scene.entities[k].x = npc.x;
scene.entities[k].y = npc.y;
scene.entities[k].facing = npc.facing;
break;
}
}
}
// Draw speech bubbles on the overlay.
var rendererCanvas = this.host.querySelector('.rk-canvas');
if (rendererCanvas) {
this._syncOverlaySize(this.host.clientWidth || rendererCanvas.width, this.host.clientHeight || rendererCanvas.height);
// Keep the overlay at viewport scale (so chat remains readable), but project each
// world-space head position through the camera-transformed canvas rectangle.
var hostRect = this.host.getBoundingClientRect ? this.host.getBoundingClientRect() : { left: 0, top: 0 };
var canvasRect = rendererCanvas.getBoundingClientRect ? rendererCanvas.getBoundingClientRect() : {
left: 0, top: 0, width: rendererCanvas.width, height: rendererCanvas.height
};
this._viewTransform = {
left: canvasRect.left - hostRect.left,
top: canvasRect.top - hostRect.top,
scaleX: canvasRect.width / (rendererCanvas.width || 1),
scaleY: canvasRect.height / (rendererCanvas.height || 1)
};
this._overlay.style.inset = '0';
this._overlay.style.left = '0';
this._overlay.style.top = '0';
this._overlay.style.maxWidth = 'none';
this._overlay.style.maxHeight = 'none';
this._overlay.style.transform = '';
this._overlay.style.transition = '';
}
this._drawBubbles(scene, cell, mode, now);
};
TavernLife.prototype.start = function () {
var self = this;
function loop() {
var scene = self.getScene();
if (scene) {
var cell = self.getCell();
// Re-inject NPCs if the scene was rebuilt.
if (!scene._npcInjected) self.injectInto(scene);
self.update(scene, cell, self._mode || 'tiles');
}
self._raf = root.requestAnimationFrame(loop);
}
this._raf = root.requestAnimationFrame(loop);
};
TavernLife.prototype.setMode = function (mode) { this._mode = mode; };
TavernLife.prototype.stop = function () {
if (this._raf) root.cancelAnimationFrame(this._raf);
this._raf = null;
if (this._overlay && this._overlay.parentNode) this._overlay.parentNode.removeChild(this._overlay);
this._overlay = null;
this._octx = null;
};
TavernLife.prototype.welcomeBubbles = function () {
// Make the bartender greet when the player joins.
if (this.npcs.length > 0 && this.npcs[0].role === 'bartender') {
var now = Date.now();
this.npcs[0].speech = pick(WELCOME_LINES);
this.npcs[0].speechUntil = now + BUBBLE_DURATION;
this.npcs[0].speechTimer = 5000;
}
};
RK.TavernLife = TavernLife;
})(window);
+954
View File
@@ -0,0 +1,954 @@
// 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
// fog-of-war brightness the 2D modes use. Textures are generated on a canvas at startup: no new
// asset downloads, nothing for the CSP to block, and the walls read as stone instead of flat boxes.
(function (root) {
'use strict';
function colorNum(hex) { return parseInt(String(hex || '#9aa4b2').replace('#', ''), 16) || 0x9aa4b2; }
function tintForVisual(visual, fallback) {
if (root.RK && RK.avatarVisuals && RK.avatarVisuals.tintColorFor) {
return RK.avatarVisuals.tintColorFor(visual && visual.appearance, fallback);
}
return fallback || null;
}
// 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; };
}
function makeCanvas(size, paint) {
var cv = root.document.createElement('canvas');
cv.width = size; cv.height = size;
paint(cv.getContext('2d'), size);
return cv;
}
// Coursed stone blocks: mortar gaps, per-block value variation, a lit top edge and a shaded
// bottom edge. The bevel is baked in so the walls have relief even at grazing light angles.
function stoneCanvas(size) {
return makeCanvas(size, function (c, s) {
var rnd = lcg(0x5713);
c.fillStyle = '#241f1a'; c.fillRect(0, 0, s, s);
var rows = 4, h = s / rows, bw = s / 2.5;
for (var r = 0; r < rows; r++) {
var offset = (r % 2) * (bw / 2);
for (var bx = -1; bx < 4; bx++) {
var x = bx * bw + offset, y = r * h;
var v = 116 + Math.floor(rnd() * 40);
c.fillStyle = 'rgb(' + v + ',' + (v - 7) + ',' + (v - 20) + ')';
c.fillRect(x + 2, y + 2, bw - 4, h - 4);
c.fillStyle = 'rgba(255,246,225,0.11)'; c.fillRect(x + 2, y + 2, bw - 4, 2);
c.fillStyle = 'rgba(0,0,0,0.26)'; c.fillRect(x + 2, y + h - 4, bw - 4, 2);
}
}
for (var i = 0; i < s * 10; i++) {
c.fillStyle = 'rgba(0,0,0,' + (rnd() * 0.18).toFixed(3) + ')';
c.fillRect(Math.floor(rnd() * s), Math.floor(rnd() * s), 1, 1);
}
});
}
// 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) {
var rnd = lcg(0x2f19);
c.fillStyle = '#1d1a16'; c.fillRect(0, 0, s, s);
var n = 4, cell = s / n;
for (var gy = 0; gy < n; gy++) {
for (var gx = 0; gx < n; gx++) {
var pad = 1.5 + rnd() * 1.5;
var v = 96 + Math.floor(rnd() * 34);
c.fillStyle = 'rgb(' + v + ',' + (v - 4) + ',' + (v - 14) + ')';
c.fillRect(gx * cell + pad, gy * cell + pad, cell - pad * 2, cell - pad * 2);
c.fillStyle = 'rgba(255,244,220,0.06)';
c.fillRect(gx * cell + pad, gy * cell + pad, cell - pad * 2, 1.5);
}
}
for (var i = 0; i < s * 14; i++) {
c.fillStyle = 'rgba(0,0,0,' + (rnd() * 0.2).toFixed(3) + ')';
c.fillRect(Math.floor(rnd() * s), Math.floor(rnd() * s), 1, 1);
}
});
}
// Vertical fade for the objective beacons: bright at the floor, gone by the top. Without it the
// beam cylinder renders as a flat uniform column that looks like a solid prop.
function beamCanvas(h) {
var cv = root.document.createElement('canvas');
cv.width = 4; cv.height = h;
var c = cv.getContext('2d');
var g = c.createLinearGradient(0, h, 0, 0);
g.addColorStop(0, 'rgba(255,255,255,0.85)');
g.addColorStop(0.35, 'rgba(255,255,255,0.30)');
g.addColorStop(1, 'rgba(255,255,255,0)');
c.fillStyle = g; c.fillRect(0, 0, 4, h);
return cv;
}
// Soft round sprite for the dust motes drifting in the torchlight.
function moteCanvas(size) {
return makeCanvas(size, function (c, s) {
var g = c.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2);
g.addColorStop(0, 'rgba(255,236,196,1)');
g.addColorStop(0.45, 'rgba(255,206,140,0.5)');
g.addColorStop(1, 'rgba(255,190,120,0)');
c.fillStyle = g; c.fillRect(0, 0, s, s);
});
}
// Wall-family kinds occupy the full cell height; ground kinds are a thin slab; everything else
// is a prop box sized per kind. `emissive` marks hazards/fire that glow on their own.
var WALLISH = { wall: 1, window: 1, door: 1, archway: 1, torch: 1 };
var GROUND = { floor: 1, floor2: 1, rug: 1, dirt: 1, entrance: 1, exit: 1, treasure: 1 };
var PROP_HEIGHT = {
bar: 0.52, table: 0.40, chair: 0.30, keg: 0.50, barrel: 0.50, shelf: 0.92,
crate: 0.44, chest: 0.38, hearth: 0.30, column: 1.30,
lava: 0.05, poison: 0.05, spikes: 0.09
};
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; everything else falls back to
// the legend.
var KIND_TINT = {
wall: '#a49a8b', window: '#7d94a8', door: '#9c7a4a', archway: '#a49a8b',
torch: '#a49a8b',
floor: '#7a6a53', floor2: '#6a5d4b', rug: '#8a4a45', dirt: '#645540',
entrance: '#4d7f57', exit: '#8a743c', treasure: '#7c7062',
lava: '#ff6a2a', poison: '#4fd07a', spikes: '#9aa3ad'
};
function ThreeRenderer(host, opts) {
opts = opts || {};
if (!root.RK || !RK.THREE || !RK.THREE.THREE) throw new Error('THREE not loaded');
this.name = '3d';
this.host = host;
this.THREE = RK.THREE.THREE;
this.GLTFLoader = RK.THREE.GLTFLoader;
this.SkeletonUtils = RK.THREE.SkeletonUtils;
this.models = {};
this.mixers = [];
this.entities = {};
this.last = {};
this.zoom = 1;
this.panX = 0;
this.panY = 0;
this.buckets = {};
this.torchCells = [];
this._destroyed = false;
this._init();
}
ThreeRenderer.prototype._init = function () {
var T = this.THREE;
this.scene = new T.Scene();
this.scene.background = new T.Color(0x000000);
// 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.
// 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);
this.camera.lookAt(0, 0, 0);
this.renderer = new T.WebGLRenderer({ antialias: true, alpha: false, preserveDrawingBuffer: true });
this.renderer.domElement.className = 'rk-canvas';
this.canvas = this.renderer.domElement;
this.renderer.setPixelRatio(Math.min(2, root.devicePixelRatio || 1));
if (T.SRGBColorSpace) this.renderer.outputColorSpace = T.SRGBColorSpace;
if (T.ACESFilmicToneMapping != null) {
this.renderer.toneMapping = T.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.22;
}
this.renderer.shadowMap.enabled = true;
if (T.PCFSoftShadowMap != null) this.renderer.shadowMap.type = T.PCFSoftShadowMap;
this.host.appendChild(this.renderer.domElement);
this._buildMaterials();
// A dim cool ambient keeps unlit corners from going pure black; the warm key light and the
// player's torch do the actual shaping.
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.castShadow = true;
this.keyLight.shadow.mapSize.set(1024, 1024);
this.keyLight.shadow.camera.near = 1;
this.keyLight.shadow.camera.far = 46;
this.keyLight.shadow.camera.left = -13;
this.keyLight.shadow.camera.right = 13;
this.keyLight.shadow.camera.top = 13;
this.keyLight.shadow.camera.bottom = -13;
this.keyLight.shadow.bias = -0.0015;
this.keyLight.shadow.normalBias = 0.04;
this.scene.add(this.keyLight);
this.scene.add(this.keyLight.target);
// A player-carried torch adds depth and keeps the followed avatar readable without washing
// out the dungeon's black fog-of-war background.
this.playerLight = new T.PointLight(0xffb35c, 4.4, 14, 2);
this.playerLight.position.set(0, 2.6, 0);
this.scene.add(this.playerLight);
// A small pool of lights reassigned to whichever torches are nearest the player each frame:
// a level can hold dozens of torches, but only a handful are ever on screen.
this.torchLights = [];
for (var i = 0; i < 6; i++) {
var pl = new T.PointLight(0xff9a3c, 0, 11, 2);
pl.visible = false;
this.scene.add(pl);
this.torchLights.push(pl);
}
this.world = new T.Group();
this.scene.add(this.world);
this.tileLayer = new T.Group();
this.fixtureLayer = new T.Group();
this.entityLayer = new T.Group();
this.world.add(this.tileLayer);
this.world.add(this.fixtureLayer);
this.world.add(this.entityLayer);
this._buildMotes();
this.clock = new T.Clock();
var self = this;
this._raf = requestAnimationFrame(function tick() {
if (self._destroyed || !self.renderer) { self._raf = null; return; }
if (self._animate() === false) { self._raf = null; return; }
self._raf = requestAnimationFrame(tick);
});
};
ThreeRenderer.prototype._buildMaterials = function () {
var T = this.THREE;
function tex(canvas, repeat) {
var t = new T.CanvasTexture(canvas);
t.wrapS = t.wrapT = T.RepeatWrapping;
t.repeat.set(repeat, repeat);
t.anisotropy = 4;
return t;
}
var stone = stoneCanvas(128), ground = groundCanvas(128);
this._textures = [];
var stoneMap = tex(stone, 1), groundMap = tex(ground, 1);
var stoneBump = tex(stone, 1), groundBump = tex(ground, 1);
if (T.SRGBColorSpace) { stoneMap.colorSpace = T.SRGBColorSpace; groundMap.colorSpace = T.SRGBColorSpace; }
this._textures.push(stoneMap, groundMap, stoneBump, groundBump);
this.wallMat = new T.MeshStandardMaterial({
map: stoneMap, bumpMap: stoneBump, bumpScale: 0.55, roughness: 0.94, metalness: 0.02
});
this.groundMat = new T.MeshStandardMaterial({
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.
this.glowMat = new T.MeshStandardMaterial({
roughness: 0.55, metalness: 0.0, emissive: new T.Color(0xffffff), emissiveIntensity: 0.9
});
};
// Dust motes drifting through the torchlight. Purely atmospheric, one draw call, and they are
// re-centred on the player so the same 160 particles cover the whole level.
ThreeRenderer.prototype._buildMotes = function () {
var T = this.THREE, n = 160;
var pos = new Float32Array(n * 3);
this._moteSeed = new Float32Array(n);
var rnd = lcg(0x9e37);
for (var i = 0; i < n; i++) {
pos[i * 3] = (rnd() - 0.5) * 26;
pos[i * 3 + 1] = rnd() * 5.5;
pos[i * 3 + 2] = (rnd() - 0.5) * 26;
this._moteSeed[i] = rnd() * 6.28;
}
var geom = new T.BufferGeometry();
geom.setAttribute('position', new T.BufferAttribute(pos, 3));
var map = new T.CanvasTexture(moteCanvas(32));
this._textures.push(map);
this._moteMat = new T.PointsMaterial({
size: 0.11, map: map, transparent: true, depthWrite: false,
blending: T.AdditiveBlending, opacity: 0.55, sizeAttenuation: true
});
this.motes = new T.Points(geom, this._moteMat);
this.motes.frustumCulled = false;
this.scene.add(this.motes);
};
// 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, 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 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;
this.camera.top = span;
this.camera.bottom = -span;
this.camera.updateProjectionMatrix();
};
ThreeRenderer.prototype.setZoom = function (zoom) {
var next = Math.max(0.55, Math.min(3.2, Number(zoom) || 1));
if (Math.abs(next - this.zoom) < 0.001) return;
this.zoom = next;
this._cw = null; // force projection update even when the host dimensions did not change
this._fitToHost();
};
// `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. 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;
this.panX = Math.max(-w, Math.min(w, Number(x) || 0));
this.panY = Math.max(-h, Math.min(h, Number(y) || 0));
};
ThreeRenderer.prototype._mat = function (hex) {
var T = this.THREE;
return new T.MeshStandardMaterial({ color: colorNum(hex), roughness: 0.82, metalness: 0.02 });
};
ThreeRenderer.prototype._disposeObject = function (object) {
if (!object || !object.traverse) return;
var keep = [this.wallMat, this.groundMat, this.propMat, this.glowMat];
object.traverse(function (obj) {
if (obj.geometry && obj.geometry.dispose) obj.geometry.dispose();
if (!obj.material) return;
var materials = Array.isArray(obj.material) ? obj.material : [obj.material];
materials.forEach(function (mat) {
if (mat && mat.dispose && keep.indexOf(mat) === -1) mat.dispose();
});
});
};
// 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];
if (!b || b.capacity < needed) {
if (b) { this.tileLayer.remove(b.mesh); b.mesh.dispose(); }
var capacity = Math.max(64, Math.ceil(needed * 1.35));
var mesh = new T.InstancedMesh(geom, mat, capacity);
mesh.instanceMatrix.setUsage(T.DynamicDrawUsage);
mesh.castShadow = name !== 'ground';
mesh.receiveShadow = true;
mesh.frustumCulled = false;
this.tileLayer.add(mesh);
b = this.buckets[name] = { mesh: mesh, capacity: capacity, geom: geom };
}
return b;
};
ThreeRenderer.prototype._buildTiles = function (scene) {
var T = this.THREE;
if (!this._geom) {
this._geom = {
wall: new T.BoxGeometry(1, 1, 1),
ground: new T.BoxGeometry(1, 0.12, 1),
prop: new T.BoxGeometry(1, 1, 1)
};
}
var legend = scene.legend || {};
var light = scene.lightGrid || null;
var cx = (scene.cols - 1) / 2, cz = (scene.rows - 1) / 2;
var walls = [], grounds = [], props = [];
this.torchCells = [];
var y, x, kind;
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 rendered (fog-of-war)
var def = legend[kind] || {};
var lb = (light && light[y] && light[y][x] != null) ? light[y][x] : 1;
// 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 };
if (WALLISH[kind]) walls.push(cell);
else if (GROUND[kind]) grounds.push(cell);
else props.push(cell);
// Wall-mounted torches: a brazier fixture + a light source candidate.
if (def.fx === 'fire') this.torchCells.push(cell);
if (def.hazard) cell.hazard = def.hazard;
}
}
this._wallCells = walls;
this._writeGround(grounds);
this._writeProps(props);
this._writeWalls();
this._syncFixtures();
};
ThreeRenderer.prototype._writeGround = function (cells) {
var T = this.THREE;
var b = this._bucket('ground', this._geom.ground, this.groundMat, cells.length);
var m = new T.Matrix4(), c = new T.Color();
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
m.makeTranslation(cell.x, 0, cell.z);
b.mesh.setMatrixAt(i, m);
c.set(colorNum(cell.tint)).multiplyScalar(cell.b);
b.mesh.setColorAt(i, c);
}
b.mesh.count = cells.length;
b.mesh.instanceMatrix.needsUpdate = true;
if (b.mesh.instanceColor) b.mesh.instanceColor.needsUpdate = true;
};
ThreeRenderer.prototype._writeProps = function (cells) {
var T = this.THREE;
var b = this._bucket('prop', this._geom.prop, this.propMat, cells.length);
var m = new T.Matrix4(), q = new T.Quaternion(), s = new T.Vector3(), p = new T.Vector3(), c = new T.Color();
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var h = PROP_HEIGHT[cell.kind] != null ? PROP_HEIGHT[cell.kind] : 0.3;
s.set(0.88, h, 0.88);
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
// difficulty curve.
var hb = cell.hazard ? Math.max(0.7, cell.b) : cell.b;
c.set(colorNum(cell.tint)).multiplyScalar(hb);
b.mesh.setColorAt(i, c);
}
b.mesh.count = cells.length;
b.mesh.instanceMatrix.needsUpdate = true;
if (b.mesh.instanceColor) b.mesh.instanceColor.needsUpdate = true;
};
// 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 () {
var cells = this._wallCells;
if (!cells) return;
var T = this.THREE;
var b = this._bucket('wall', this._geom.wall, this.wallMat, cells.length);
var m = new T.Matrix4(), q = new T.Quaternion(), s = new T.Vector3(), p = new T.Vector3(), c = new T.Color();
var px = this._plx, py = this._ply;
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var h = 1.45, dim = 1;
if (px != null && cell.gx >= px && cell.gy >= py) {
var d = (cell.gx - px) + (cell.gy - py);
if (d > 0 && d <= 3) { h = 0.40; dim = 0.62; }
}
s.set(1, h, 1);
p.set(cell.x, h / 2, cell.z);
m.compose(p, q, s);
b.mesh.setMatrixAt(i, m);
c.set(colorNum(cell.tint)).multiplyScalar(cell.b * dim);
b.mesh.setColorAt(i, c);
}
b.mesh.count = cells.length;
b.mesh.instanceMatrix.needsUpdate = true;
if (b.mesh.instanceColor) b.mesh.instanceColor.needsUpdate = true;
};
// 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 || {};
var want = {}, i, cell, k;
for (i = 0; i < this.torchCells.length; i++) {
cell = this.torchCells[i];
k = cell.gx + ',' + cell.gy;
want[k] = true;
if (this._flames[k]) { cell.flame = this._flames[k].flame; continue; }
var bowl = new T.Mesh(
new T.CylinderGeometry(0.17, 0.10, 0.16, 8),
new T.MeshStandardMaterial({ color: 0x2a2320, roughness: 0.9 })
);
bowl.position.set(cell.x, 1.30, cell.z);
this.fixtureLayer.add(bowl);
var flame = new T.Mesh(
new T.ConeGeometry(0.13, 0.34, 7),
new T.MeshBasicMaterial({ color: 0xffb14a, transparent: true, opacity: 0.92 })
);
flame.position.set(cell.x, 1.55, cell.z);
this.fixtureLayer.add(flame);
cell.flame = flame;
this._flames[k] = { bowl: bowl, flame: flame };
}
for (k in this._flames) {
if (want[k]) continue;
var rec = this._flames[k];
this.fixtureLayer.remove(rec.bowl);
this.fixtureLayer.remove(rec.flame);
this._disposeObject(rec.bowl);
this._disposeObject(rec.flame);
delete this._flames[k];
}
};
ThreeRenderer.prototype._fallbackAvatar = function (e, visual) {
var T = this.THREE;
var g = new T.Group();
var body = new T.Mesh(new T.CapsuleGeometry(0.40, 1.05, 4, 12), this._mat(tintForVisual(visual, e.color || '#9aa4b2')));
body.position.y = 0.95;
body.castShadow = true;
g.add(body);
var face = new T.Mesh(new T.BoxGeometry(0.22, 0.12, 0.06), this._mat('#0a0c0f'));
face.position.set(0, 1.30, 0.40);
g.add(face);
return g;
};
// Monsters share the dungeon with the player, so they must never read as a second hero: a
// hunched dark-red body with glowing eyes and its own red spill light.
ThreeRenderer.prototype._makeMonster = function (e) {
var T = this.THREE;
var g = new T.Group();
var body = new T.Mesh(
new T.CapsuleGeometry(0.42, 0.62, 4, 12),
new T.MeshStandardMaterial({ color: 0x7a1d1d, roughness: 0.65, emissive: 0x2a0505, emissiveIntensity: 0.7 })
);
body.position.y = 0.68;
body.castShadow = true;
g.add(body);
var eyeMat = new T.MeshBasicMaterial({ color: 0xff5b4a });
for (var s = -1; s <= 1; s += 2) {
var eye = new T.Mesh(new T.SphereGeometry(0.07, 8, 8), eyeMat);
eye.position.set(s * 0.15, 0.98, 0.34);
g.add(eye);
}
var horns = new T.MeshStandardMaterial({ color: 0x3d1414, roughness: 0.5 });
for (var h = -1; h <= 1; h += 2) {
var horn = new T.Mesh(new T.ConeGeometry(0.07, 0.28, 6), horns);
horn.position.set(h * 0.22, 1.16, 0);
horn.rotation.z = h * -0.3;
g.add(horn);
}
var light = new T.PointLight(0xff4a3a, 1.4, 4.5, 2);
light.position.set(0, 0.9, 0);
g.add(light);
g._menace = true;
return g;
};
// 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();
var ch = e.char || '?';
if (ch === '<' || ch === '>') {
var down = ch === '>';
var tone = down ? 0xd8a13f : 0x4fbf62;
var stepMat = new T.MeshStandardMaterial({ color: 0x5d564a, roughness: 0.9 });
for (var i = 0; i < 4; i++) {
var step = new T.Mesh(new T.BoxGeometry(0.82, 0.11, 0.82 - i * 0.17), stepMat);
step.position.set(0, down ? 0.05 - i * 0.09 : 0.05 + i * 0.09, i * 0.09);
step.receiveShadow = true;
g.add(step);
}
// A soft beacon column: from across a dark room you can see where the stairs are without
// the fog-of-war having to leak the whole layout.
if (!this._beamTex) {
this._beamTex = new T.CanvasTexture(beamCanvas(64));
this._textures.push(this._beamTex);
}
var beam = new T.Mesh(
new T.CylinderGeometry(0.30, 0.46, 3.2, 14, 1, true),
new T.MeshBasicMaterial({
color: tone, map: this._beamTex, transparent: true, opacity: 0.5,
side: T.DoubleSide, depthWrite: false, blending: T.AdditiveBlending, fog: false
})
);
beam.position.y = 1.6;
g.add(beam);
g._beam = beam;
var bl = new T.PointLight(tone, 1.1, 5, 2);
bl.position.set(0, 0.8, 0);
g.add(bl);
g._pulse = bl;
} else if (ch.charAt(0) === '$') {
var wood = new T.MeshStandardMaterial({ color: 0x6b4423, roughness: 0.8 });
var gold = new T.MeshStandardMaterial({
color: 0xf5c624, roughness: 0.28, metalness: 0.85,
emissive: 0x6b4c07, emissiveIntensity: 0.7
});
var body = new T.Mesh(new T.BoxGeometry(0.62, 0.34, 0.44), wood);
body.position.y = 0.24;
body.castShadow = true;
g.add(body);
var lid = new T.Mesh(new T.CylinderGeometry(0.22, 0.22, 0.62, 12, 1, false, 0, Math.PI), gold);
lid.rotation.z = Math.PI / 2;
lid.position.y = 0.41;
g.add(lid);
var glow = new T.PointLight(0xffc65c, 1.6, 4.5, 2);
glow.position.set(0, 0.7, 0);
g.add(glow);
g._pulse = glow;
g._bob = true;
} else {
var item = new T.Mesh(
new T.OctahedronGeometry(0.22, 0),
new T.MeshStandardMaterial({
color: colorNum(e.color || '#fbbf24'), roughness: 0.3, metalness: 0.6,
emissive: colorNum(e.color || '#fbbf24'), emissiveIntensity: 0.55
})
);
item.position.y = 0.5;
item.castShadow = true;
g.add(item);
g._spin = item;
g._bob = true;
}
g._static = true;
return g;
};
ThreeRenderer.prototype._applyModelTint = function (model, visual) {
var tint = tintForVisual(visual, null);
if (!model) return;
var T = this.THREE;
var color = tint ? new T.Color(colorNum(tint)) : null;
model.traverse(function (obj) {
if (!obj.isMesh || !obj.material) return;
obj.castShadow = true;
var materials = Array.isArray(obj.material) ? obj.material : [obj.material];
var next = materials.map(function (mat) {
if (!mat) return mat;
var copy = mat.clone();
if (color && copy.color) copy.color.copy(color);
return copy;
});
obj.material = Array.isArray(obj.material) ? next : next[0];
});
};
ThreeRenderer.prototype._fitModel = function (model) {
var T = this.THREE;
var wrapper = new T.Group();
model.updateMatrixWorld(true);
var box = new T.Box3();
var foundMesh = false;
model.traverse(function (obj) {
if (!obj.isMesh || !obj.geometry) return;
if (!obj.geometry.boundingBox) obj.geometry.computeBoundingBox();
var meshBox = obj.geometry.boundingBox.clone();
meshBox.applyMatrix4(obj.matrixWorld);
box.union(meshBox);
foundMesh = true;
});
if (!foundMesh) box.setFromObject(model);
var size = new T.Vector3();
var center = new T.Vector3();
box.getSize(size);
box.getCenter(center);
var maxDim = Math.max(size.x, size.y, size.z) || 1;
var scale = 1.8 / maxDim;
model.position.set(-center.x, -box.min.y, -center.z);
wrapper.scale.setScalar(scale);
wrapper.add(model);
return wrapper;
};
ThreeRenderer.prototype._loadModel = function (resolved, cb) {
if (!resolved || !resolved.model || !resolved.model.url || !this.GLTFLoader) { cb(null); return; }
var url = resolved.model.url;
if (this.models[url]) {
if (this.models[url].ready) cb(this.models[url]);
else this.models[url].cbs.push(cb);
return;
}
var rec = this.models[url] = { ready: false, cbs: [cb] };
var loader = new this.GLTFLoader();
loader.load(url, function (gltf) {
rec.ready = true;
rec.gltf = gltf;
var cbs = rec.cbs; rec.cbs = [];
cbs.forEach(function (fn) { fn(rec); });
}, null, function () {
rec.ready = true;
rec.error = true;
var cbs = rec.cbs; rec.cbs = [];
cbs.forEach(function (fn) { fn(null); });
});
};
ThreeRenderer.prototype._playAction = function (shell, name) {
if (!shell || !shell._actions || shell._activeActionName === name) return;
var next = shell._actions[name] || shell._actions[Object.keys(shell._actions)[0]];
if (!next) return;
if (shell._activeAction && shell._activeAction !== next) shell._activeAction.fadeOut(0.12);
next.reset().fadeIn(0.12).play();
shell._activeAction = next;
shell._activeActionName = name;
};
ThreeRenderer.prototype._visualFor = function (e) {
var appearance = (e && e.appearance) || { avatar: (e && e.avatar) || 'default' };
if (root.RK && RK.avatarVisuals && RK.avatarVisuals.resolve) {
return RK.avatarVisuals.resolve(appearance, { projection: '3d', context: 'tavern', entity: e });
}
if (root.RK && RK.resolveAppearance) return RK.resolveAppearance(e, '3d');
return null;
};
ThreeRenderer.prototype._makeAvatar = function (e) {
var T = this.THREE, self = this;
var shell = new T.Group();
var visual = this._visualFor(e);
shell._isAvatar = true;
shell._body = this._fallbackAvatar(e, visual);
shell.add(shell._body);
if (visual && visual.allowed !== false && visual.model) {
this._loadModel(visual, function (rec) {
if (!rec || !rec.gltf || !shell.parent) return;
var model = self.SkeletonUtils && self.SkeletonUtils.clone
? self.SkeletonUtils.clone(rec.gltf.scene)
: rec.gltf.scene.clone(true);
self._applyModelTint(model, visual);
model.rotation.y = Math.PI;
var fitted = self._fitModel(model);
if (shell._body) {
shell.remove(shell._body);
self._disposeObject(shell._body);
shell._body = null;
}
shell.add(fitted);
shell._model = fitted;
if (rec.gltf.animations && rec.gltf.animations.length) {
var mixer = new T.AnimationMixer(model);
shell._mixer = mixer;
shell._actions = {};
rec.gltf.animations.forEach(function (clip) {
shell._actions[String(clip.name).toLowerCase()] = mixer.clipAction(clip);
});
self._playAction(shell, 'idle');
self.mixers.push(mixer);
}
});
}
return shell;
};
ThreeRenderer.prototype._makeEntity = function (e) {
if (e.kind === 'feature' || e.kind === 'item') return this._makeFeature(e);
if (e.kind === 'monster') return this._makeMonster(e);
return this._makeAvatar(e);
};
ThreeRenderer.prototype.render = function (scene) {
if (!scene || !this.renderer) return;
this._fitToHost();
// Track the followed player's CELL first: the wall cutaway is computed from it during the
// tile build, so it has to be current before _buildTiles runs.
var pcell = null, i;
for (i = 0; i < scene.entities.length; i++) {
var pe = scene.entities[i];
if (pe.you || pe.cameraTarget || (!pcell && pe.kind === 'player')) pcell = pe;
if (pe.you || pe.cameraTarget) break;
}
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
// 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 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;
for (i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i], id = e.id;
seen[id] = true;
var ent = this.entities[id];
if (!ent) {
var obj = this._makeEntity(e);
obj.position.set(e.x - cx, 0, e.y - cz);
ent = this.entities[id] = { obj: obj, x: e.x, y: e.y };
this.entityLayer.add(ent.obj);
}
ent.e = e;
ent.tx = e.x - cx;
ent.tz = e.y - cz;
}
for (id in this.entities) {
if (!seen[id]) {
var removed = this.entities[id].obj;
this.entityLayer.remove(removed);
if (removed._mixer) {
removed._mixer.stopAllAction();
var mixerIndex = this.mixers.indexOf(removed._mixer);
if (mixerIndex >= 0) this.mixers.splice(mixerIndex, 1);
}
this._disposeObject(removed);
delete this.entities[id];
}
}
};
// Reassign the small torch-light pool to whichever braziers are nearest the followed player.
ThreeRenderer.prototype._updateTorchLights = function (px, pz, now) {
var lights = this.torchLights;
if (!lights || !lights.length) return;
var cells = this.torchCells || [];
var near = [];
for (var i = 0; i < cells.length; i++) {
var d = Math.abs(cells[i].x - px) + Math.abs(cells[i].z - pz);
if (d < 16) near.push({ c: cells[i], d: d });
}
near.sort(function (a, b) { return a.d - b.d; });
for (var li = 0; li < lights.length; li++) {
var slot = near[li];
var light = lights[li];
if (!slot) { light.visible = false; light.intensity = 0; continue; }
var flicker = 0.78 + Math.sin(now / 90 + slot.c.gx * 3.1) * 0.13 + Math.sin(now / 37 + slot.c.gy) * 0.07;
light.visible = true;
light.position.set(slot.c.x, 1.5, slot.c.z);
light.intensity = 3.6 * flicker * Math.max(0.3, slot.c.b);
if (slot.c.flame) {
slot.c.flame.scale.set(1, 0.85 + flicker * 0.3, 1);
slot.c.flame.material.opacity = 0.7 + flicker * 0.25;
}
}
};
ThreeRenderer.prototype._animate = function () {
if (!this.renderer) return;
try {
var dt = this.clock.getDelta();
var now = Date.now();
for (var i = 0; i < this.mixers.length; i++) this.mixers[i].update(dt);
for (var id in this.entities) {
var ent = this.entities[id], o = ent.obj;
var dx = (ent.tx || 0) - o.position.x;
var dz = (ent.tz || 0) - o.position.z;
var moving = Math.abs(dx) + Math.abs(dz) > 0.025;
o.position.x += dx * 0.18;
o.position.z += dz * 0.18;
// Set dressing bobs and spins on its own clock; only characters get the gait bounce.
if (o._static) {
o.position.y = o._bob ? 0.06 + Math.sin(now / 520 + o.position.x) * 0.06 : 0;
if (o._spin) o._spin.rotation.y = now / 900;
if (o._beam) o._beam.material.opacity = 0.34 + Math.abs(Math.sin(now / 900)) * 0.26;
if (o._pulse) o._pulse.intensity = 1.1 + Math.abs(Math.sin(now / 700)) * 0.7;
continue;
}
o.position.y = moving
? Math.abs(Math.sin(now / 95)) * 0.08
: Math.sin(now / 620) * 0.018;
if (o._menace) o.position.y += Math.sin(now / 380) * 0.03;
if (o._body) {
o._body.rotation.z = moving ? Math.sin(now / 120) * 0.055 : 0;
}
if (o._model) {
o._model.rotation.z = moving ? Math.sin(now / 120) * 0.045 : 0;
}
this._playAction(o, moving ? 'run' : 'idle');
// Face the way you move. Prefer explicit facing (tavern); else infer from the world delta
// (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;
if (face) {
var r = face === 'up' ? Math.PI : face === 'left' ? -Math.PI / 2 : face === 'right' ? Math.PI / 2 : 0;
o.rotation.y += (r - o.rotation.y) * 0.18;
}
}
// 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(); // picks up any host resize
var pcam = null;
for (var pid in this.entities) {
var pen = this.entities[pid];
if (pen.e && (pen.e.you || pen.e.cameraTarget)) { pcam = pen.obj; break; }
if (!pcam && pen.e && pen.e.kind === 'player') pcam = pen.obj;
}
if (pcam) {
// Dragging the viewport should move the rendered dungeon with the pointer. Translate the
// camera target opposite the corresponding screen-space axes while retaining the fixed
// isometric camera offset and player-follow smoothing.
var viewportHeight = (this.host && (this.host.clientHeight || this.host.offsetHeight)) || 400;
var unitsPerPixel = (13.2 / (this.zoom || 1)) / Math.max(1, viewportHeight);
var diagonal = unitsPerPixel / Math.sqrt(2);
var targetX = pcam.position.x + (-this.panX - this.panY) * diagonal;
var targetZ = pcam.position.z + (this.panX - this.panY) * diagonal;
this.camera.position.set(targetX + 9, 11, targetZ + 9);
this.camera.lookAt(targetX, 0, targetZ);
if (this.playerLight) {
this.playerLight.position.set(pcam.position.x, 2.6, pcam.position.z);
// Hand-held torch: a slow irregular flicker, not a strobe.
this.playerLight.intensity = 4.2 + Math.sin(now / 140) * 0.3 + Math.sin(now / 61) * 0.15;
}
// Keep the shadow frustum tight around the player so a 1024 map stays sharp on a big level.
if (this.keyLight) {
this.keyLight.position.set(pcam.position.x + 10, 8.5, pcam.position.z + 4);
this.keyLight.target.position.set(pcam.position.x, 0, pcam.position.z);
this.keyLight.target.updateMatrixWorld();
}
if (this.motes) {
this.motes.position.set(pcam.position.x, 0, pcam.position.z);
this.motes.rotation.y = now / 60000;
}
this._updateTorchLights(pcam.position.x, pcam.position.z, now);
}
this.renderer.render(this.scene, this.camera);
} catch (err) {
if (root.console) console.warn('3D animate error; stopping 3D loop:', err && err.message);
return false;
}
return true;
};
ThreeRenderer.prototype.destroy = function () {
this._destroyed = true;
if (this._raf) cancelAnimationFrame(this._raf);
this._raf = null;
for (var i = 0; i < this.mixers.length; i++) this.mixers[i].stopAllAction();
this._disposeObject(this.world);
for (var name in this.buckets) {
if (this.buckets[name].mesh.dispose) this.buckets[name].mesh.dispose();
}
this.buckets = {};
for (var g in (this._geom || {})) this._geom[g].dispose();
this._geom = null;
[this.wallMat, this.groundMat, this.propMat, this.glowMat, this._moteMat].forEach(function (m) {
if (m && m.dispose) m.dispose();
});
(this._textures || []).forEach(function (t) { if (t && t.dispose) t.dispose(); });
this._textures = [];
if (this.motes && this.motes.geometry) this.motes.geometry.dispose();
if (this.renderer) {
if (this.renderer.domElement && this.renderer.domElement.parentNode) this.renderer.domElement.parentNode.removeChild(this.renderer.domElement);
this.renderer.dispose();
if (this.renderer.forceContextLoss) this.renderer.forceContextLoss();
}
this.renderer = null;
this.entities = {};
this.models = {};
this.mixers = [];
this.torchCells = [];
};
root.RK = root.RK || {};
root.RK.ThreeRenderer = ThreeRenderer;
})(window);
+507
View File
@@ -0,0 +1,507 @@
// 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,
// and a lightweight requestAnimationFrame flicker/ember loop composited over the last scene.
(function (root) {
'use strict';
function facingDelta(f) {
if (f === 'up') return { x: 0, y: -1 };
if (f === 'left') return { x: -1, y: 0 };
if (f === 'right') return { x: 1, y: 0 };
return { x: 0, y: 1 };
}
// Deterministic per-cell hash so a given (x,y) always maps to the same tile variant.
function cellHash(x, y) {
var h = (x * 73856093) ^ (y * 19349663);
h = h % 100000;
return h < 0 ? h + 100000 : h;
}
// A tile coord is either a single [col,row] or an ARRAY of [col,row] variants.
// Resolve to one [col,row] for this cell.
function pickVariant(coord, x, y) {
if (!coord) return null;
if (Array.isArray(coord[0])) return coord[cellHash(x, y) % coord.length];
return coord;
}
// Dungeon lighting: darken a cell based on the scene's light grid (1 = lit, 0 = dark).
function applyCellLight(ctx, scene, x, y, px, py, cell) {
if (!scene.lightGrid || !scene.lightGrid[y] || scene.lightGrid[y][x] == null) return;
var brightness = scene.lightGrid[y][x];
if (brightness < 1) {
ctx.fillStyle = 'rgba(0,0,0,' + (1 - brightness) + ')';
ctx.fillRect(px, py, cell, cell);
}
}
// The player/you entity that carries the torch (for the light composite + embers).
function findPlayer(scene) {
if (!scene || !scene.entities) return null;
var live = null, fallback = null;
for (var i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i];
if (!(e.kind === 'player' || e.you)) continue;
if (e.you || e.cameraTarget) return e;
if (!live && e.alive !== false && !e.finished) live = e;
if (!fallback) fallback = e;
}
return live || fallback;
}
// Real-tile coord for a dungeon feature entity, keyed off its glyph.
function featureCoord(tmap, e) {
var ch = e.char;
if (ch === '<') return tmap.entrance;
if (ch === '>') return tmap.exit;
if (ch === '$' || ch === '$W' || ch === '$M') return tmap.treasure;
return null;
}
function TileRenderer(host, opts) {
opts = opts || {};
this.name = 'tiles';
this.host = host;
this.cell = opts.cell || 24;
this.canvas = document.createElement('canvas');
this.canvas.className = 'rk-canvas';
this.ctx = this.canvas.getContext('2d');
host.appendChild(this.canvas);
this._snap = null; // offscreen snapshot of the base scene (tiles + entities)
this._lastScene = null;
this._embers = [];
this._raf = null;
this._t = 0;
}
TileRenderer.prototype.render = function (scene) {
if (!scene || !this.ctx) return;
var cell = this.cell, ctx = this.ctx;
this.canvas.width = scene.cols * cell;
this.canvas.height = scene.rows * cell;
ctx.fillStyle = scene.background || '#000';
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
var atlas = (window.RK && RK.themeAtlas) ? RK.themeAtlas() : null;
var tmap = (window.RK && RK.tileMap) ? RK.tileMap() : {};
var useAtlas = !!(atlas && atlas.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;
atlas.onReady(function () { if (self.ctx && self._lastScene) self.render(self._lastScene); });
}
if (!scene.isDungeon && window.RK && RK.roomReady && RK.roomReady()) {
// A designed room (imported .tmx) is loaded: draw its layered tiles.
RK.drawRoomCanvas(ctx, cell);
} else {
for (var y = 0; y < scene.rows; y++) {
for (var x = 0; x < scene.cols; x++) {
var kind = scene.grid[y][x];
var px = x * cell, py = y * cell;
var def = scene.legend[kind] || { color: '#333' };
// 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;
if (bco) atlas.draw(ctx, bco[0], bco[1], px, py, cell);
else {
var bdef = scene.legend[baseKind] || def;
ctx.fillStyle = bdef.color || def.color;
ctx.fillRect(px, py, cell, cell);
}
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); 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);
}
atlas.draw(ctx, coord[0], coord[1], px, py, cell);
// Dark bottom-edge strip grounds a solid WALL against the floor below (not
// objects, which already sit on their own base tile).
if (def.solid && !def.over) {
var strip = Math.max(2, cell * 0.16);
var sg = ctx.createLinearGradient(0, py + cell - strip, 0, py + cell);
sg.addColorStop(0, 'rgba(0,0,0,0)');
sg.addColorStop(1, 'rgba(0,0,0,0.42)');
ctx.fillStyle = sg;
ctx.fillRect(px, py + cell - strip, cell, strip);
}
applyCellLight(ctx, scene, x, y, px, py, cell);
continue;
}
// Flat-colour fallback for any unmapped kind (or atlas not yet loaded).
if (def.over && scene.legend[def.over]) {
ctx.fillStyle = scene.legend[def.over].color; // base colour under the object
ctx.fillRect(px, py, cell, cell);
}
ctx.fillStyle = def.color;
ctx.fillRect(px, py, cell, cell);
ctx.strokeStyle = 'rgba(0,0,0,0.25)';
ctx.lineWidth = 1;
ctx.strokeRect(px + 0.5, py + 0.5, cell - 1, cell - 1);
if (def.solid) {
ctx.fillStyle = 'rgba(255,255,255,0.06)';
ctx.fillRect(px, py, cell, Math.max(1, cell * 0.14));
ctx.fillStyle = 'rgba(0,0,0,0.35)';
ctx.fillRect(px, py + cell - Math.max(1, cell * 0.14), cell, Math.max(1, cell * 0.14));
}
applyCellLight(ctx, scene, x, y, px, py, cell);
}
}
}
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.
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;
if (fc) {
atlas.draw(ctx, fc[0], fc[1], fpx, fpy, cell);
// Soft colour accent so entrance (green) / exit (amber) stay legible.
if (e.color) {
var acx = fpx + cell / 2, acy = fpy + cell / 2;
var ag = ctx.createRadialGradient(acx, acy, 0, acx, acy, cell * 0.6);
ag.addColorStop(0, hexToRgba(e.color, 0.32));
ag.addColorStop(1, hexToRgba(e.color, 0));
ctx.save();
ctx.globalCompositeOperation = 'lighter';
ctx.fillStyle = ag;
ctx.fillRect(fpx, fpy, cell, cell);
ctx.restore();
}
} else {
softGlyph(ctx, e.char || '?', e.color || '#fff', fpx + cell / 2, fpy + cell / 2, cell);
}
continue;
}
if (e.kind === 'item') {
var ipx = e.x * cell, ipy = e.y * cell;
var ic = useAtlas ? pickVariant(tmap.treasure, e.x, e.y) : null;
drawEntityShadow(ctx, e.x * cell + cell / 2, ipy + cell * 0.86, cell * 0.3, cell * 0.12);
if (ic) {
atlas.draw(ctx, ic[0], ic[1], ipx, ipy, cell);
} else {
softGlyph(ctx, '$', e.color || '#fbbf24', ipx + cell / 2, ipy + cell / 2, cell);
}
continue;
}
if (e.kind === 'monster') {
drawEntityShadow(ctx, e.x * cell + cell / 2, e.y * cell + cell * 0.9, cell * 0.32, cell * 0.13);
// 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';
if (window.RK && RK.avatarVisuals && RK.avatarVisuals.drawTopdownWorld) {
var mv = RK.avatarVisuals.resolve({ avatar: mAvatar }, { projection: 'topdown', context: 'dungeon', entity: e });
if (RK.avatarVisuals.drawTopdownWorld(ctx, mv, e, { screenX: e.x, screenY: e.y, cell: cell }, { now: now })) continue;
}
if (window.RK && RK.drawCharCanvas && RK.drawCharCanvas(ctx, { x: e.x, y: e.y, avatar: mAvatar }, cell, now)) continue;
var mx = e.x * cell + cell / 2, my = e.y * cell + cell / 2, mr = cell * 0.34;
ctx.beginPath();
ctx.arc(mx, my, mr, 0, Math.PI * 2);
ctx.fillStyle = e.color || '#f85149';
ctx.fill();
ctx.strokeStyle = 'rgba(255,100,100,0.4)';
ctx.lineWidth = 2;
ctx.stroke();
continue;
}
// 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 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; }
}
// Roguelike character sprite, or premium animated skin; else the fallback circle.
if (window.RK && RK.avatarVisuals && RK.avatarVisuals.drawTopdownWorld) {
var visual = RK.avatarVisuals.resolve(e.appearance || { avatar: e.avatar }, {
projection: 'topdown',
context: 'tavern',
entity: e
});
if (RK.avatarVisuals.drawTopdownWorld(ctx, visual, e, {
screenX: e.x,
screenY: e.y,
cell: cell
}, { now: now })) continue;
} else {
if (window.RK && RK.isChar && RK.isChar(e.avatar) && RK.drawCharCanvas(ctx, e, cell, now)) continue;
if (window.RK && RK.isSkin && RK.isSkin(e.avatar) && RK.drawSkinCanvas(ctx, e, cell, now)) continue;
}
var cx = e.x * cell + cell / 2, cy = e.y * cell + cell / 2, r = cell * 0.36;
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.fillStyle = e.color || '#fff';
ctx.fill();
// facing pip
var d = facingDelta(e.facing);
ctx.beginPath();
ctx.arc(cx + d.x * r * 0.6, cy + d.y * r * 0.6, cell * 0.08, 0, Math.PI * 2);
ctx.fillStyle = '#0a0c0f';
ctx.fill();
if (e.you) {
ctx.lineWidth = 2;
ctx.strokeStyle = '#ffffff';
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.stroke();
}
if (e.label) {
ctx.fillStyle = '#d7dbe0';
ctx.font = '11px monospace';
ctx.textAlign = 'center';
ctx.fillText(e.label, cx, cy - cell * 0.5);
}
}
// 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.
// 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 };
this._lastScene = scene;
this._collectEmitters(scene);
this._snapshot();
this._ensureEmbers(scene);
this._composite(scene);
this._startLoop();
};
// Cache the fire/hazard tile positions once per scene so the flicker loop can animate them
// without rescanning the grid every frame.
TileRenderer.prototype._collectEmitters = function (scene) {
var em = [], cell = this.cell, legend = scene.legend || {};
for (var y = 0; y < scene.rows; y++) {
for (var x = 0; x < scene.cols; x++) {
var def = legend[scene.grid[y][x]];
if (!def) continue;
if (def.fx === 'fire') {
em.push({ fire: true, px: x * cell, py: y * cell, cx: x * cell + cell / 2,
fy: y * cell + cell * 0.82, scale: cell * (def.fxScale || 0.34),
seed: (x * 7 + y * 13) % 97 });
} else if (def.hazard) {
em.push({ hazard: def.hazard, px: x * cell, py: y * cell,
cx: x * cell + cell / 2, cy: y * cell + cell / 2 });
}
}
}
this._emitters = em;
};
// Soft drop shadow (an ellipse) under an entity's feet.
function drawEntityShadow(ctx, cx, cy, rx, ry) {
ctx.save();
ctx.beginPath();
ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(0,0,0,0.33)';
ctx.fill();
ctx.restore();
}
// A softened glyph fallback (used only when the atlas tile is unavailable).
function softGlyph(ctx, ch, color, cx, cy, cell) {
ctx.save();
ctx.globalAlpha = 0.85;
ctx.beginPath();
ctx.arc(cx, cy, cell * 0.3, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(0,0,0,0.35)';
ctx.fill();
ctx.fillStyle = color;
ctx.font = 'bold ' + Math.round(cell * 0.62) + 'px monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(ch, cx, cy + 1);
ctx.restore();
}
function hexToRgba(hex, a) {
hex = String(hex).replace('#', '');
if (hex.length === 3) hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
var n = parseInt(hex, 16);
if (isNaN(n)) return 'rgba(255,255,255,' + a + ')';
return 'rgba(' + ((n >> 16) & 255) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + a + ')';
}
// Copy the freshly-drawn base scene into an offscreen canvas so the flicker loop can
// restore it each frame without re-running the (expensive) tile + entity passes.
TileRenderer.prototype._snapshot = function () {
if (!this.canvas) return;
if (!this._snap) this._snap = document.createElement('canvas');
if (this._snap.width !== this.canvas.width) this._snap.width = this.canvas.width;
if (this._snap.height !== this.canvas.height) this._snap.height = this.canvas.height;
var sctx = this._snap.getContext('2d');
sctx.clearRect(0, 0, this._snap.width, this._snap.height);
sctx.drawImage(this.canvas, 0, 0);
};
TileRenderer.prototype._ensureEmbers = function (scene) {
// 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; }
if (this._embers.length) return;
var cell = this.cell;
var pcx = p.x * cell + cell / 2, pcy = p.y * cell + cell / 2;
for (var i = 0; i < 10; i++) this._embers.push(this._spawnEmber(pcx, pcy, cell, true));
};
TileRenderer.prototype._spawnEmber = function (pcx, pcy, cell, seed) {
var max = 60 + Math.random() * 60;
return {
x: pcx + (Math.random() - 0.5) * cell * 2.2,
y: pcy + (Math.random() - 0.5) * cell * 1.6,
vx: (Math.random() - 0.5) * 0.25,
vy: -(0.15 + Math.random() * 0.35),
size: cell * (0.05 + Math.random() * 0.06),
life: seed ? Math.random() * max : max,
max: max
};
};
TileRenderer.prototype._advanceEmbers = function () {
var scene = this._lastScene;
var p = findPlayer(scene);
if (!p) return;
var cell = this.cell;
var pcx = p.x * cell + cell / 2, pcy = p.y * cell + cell / 2;
for (var i = 0; i < this._embers.length; i++) {
var m = this._embers[i];
m.x += m.vx;
m.y += m.vy;
m.life -= 1;
if (m.life <= 0) this._embers[i] = this._spawnEmber(pcx, pcy, cell, false);
}
};
// 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). 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;
var flick = 1 + Math.sin(this._t * 0.18) * 0.08 + Math.sin(this._t * 0.5 + 1.3) * 0.04;
var rad = cell * 4.4 * flick;
var g = ctx.createRadialGradient(cx, cy, 0, cx, cy, rad);
g.addColorStop(0, 'rgba(255,190,110,0.42)');
g.addColorStop(0.5, 'rgba(255,150,70,0.14)');
g.addColorStop(1, 'rgba(255,150,70,0)');
ctx.save();
ctx.globalCompositeOperation = 'lighter';
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(cx, cy, rad, 0, Math.PI * 2);
ctx.fill();
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;
var eg = ctx.createRadialGradient(m.x, m.y, 0, m.x, m.y, m.size * 3);
eg.addColorStop(0, 'rgba(255,220,150,' + a + ')');
eg.addColorStop(1, 'rgba(255,150,60,0)');
ctx.fillStyle = eg;
ctx.beginPath();
ctx.arc(m.x, m.y, m.size * 3, 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
}
// Edge vignette (normal blend, darkens the borders).
var vig = ctx.createRadialGradient(
w / 2, h / 2, Math.min(w, h) * 0.34,
w / 2, h / 2, Math.max(w, h) * 0.72
);
vig.addColorStop(0, 'rgba(0,0,0,0)');
vig.addColorStop(1, 'rgba(0,0,0,0.55)');
ctx.save();
ctx.fillStyle = vig;
ctx.fillRect(0, 0, w, h);
ctx.restore();
// 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) {
var nowMs = Date.now();
for (var k = 0; k < em.length; k++) {
var it = em[k];
if (it.hazard) {
RK.fx.hazard(ctx, it.hazard, it.cx, it.cy, cell * 0.9, nowMs, makeRect(it.px, it.py, cell));
} else {
RK.fx.fire(ctx, it.cx, it.fy, it.scale, nowMs, it.seed);
}
}
}
};
// Footprint tracer for a square cell (RK.fx.hazard clips its base tint to this).
function makeRect(px, py, cell) {
return function (c) { c.beginPath(); c.rect(px, py, cell, cell); };
}
TileRenderer.prototype._startLoop = function () {
if (this._raf != null) return;
var self = this;
function loop() {
if (!self.ctx || !self._snap) { self._raf = null; return; }
self._t += 1;
self._advanceEmbers();
self.ctx.clearRect(0, 0, self.canvas.width, self.canvas.height);
self.ctx.drawImage(self._snap, 0, 0);
self._composite(self._lastScene);
self._raf = root.requestAnimationFrame(loop);
}
this._raf = root.requestAnimationFrame(loop);
};
TileRenderer.prototype.destroy = function () {
if (this._raf != null) { root.cancelAnimationFrame(this._raf); this._raf = null; }
if (this.canvas && this.canvas.parentNode) this.canvas.parentNode.removeChild(this.canvas);
this.canvas = null;
this.ctx = null;
this._snap = null;
this._lastScene = null;
this._embers = [];
};
root.RK = root.RK || {};
root.RK.TileRenderer = TileRenderer;
})(window);
+275
View File
@@ -0,0 +1,275 @@
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
var MIN = 0.4, MAX = 4.0;
// Apply the host's current zoom to whatever canvas is mounted in it (2D or WebGL). Re-callable
// after a renderer/mode switch so the new canvas inherits the zoom.
RK.applyZoom = function (host) {
if (!host) return;
var z = host._rkZoom || 1;
var c = host.querySelector('canvas');
if (!c) return;
c.style.transformOrigin = 'center center';
c.style.transform = z === 1 ? '' : 'scale(' + z + ')';
c.style.imageRendering = 'pixelated'; // keep pixel art crisp when zoomed
};
// Wheel + trackpad-pinch zoom on a render host, shared by every mode. Trackpad pinch arrives as
// a wheel event with ctrlKey set; a normal wheel over the canvas zooms instead of scrolling.
RK.attachZoom = function (host) {
if (!host || host._rkZoomAttached) return;
host._rkZoomAttached = true;
host._rkZoom = host._rkZoom || 1;
host.style.overflow = 'hidden';
host.title = 'Scroll / pinch to zoom · double-click to reset';
host.addEventListener('wheel', function (e) {
e.preventDefault();
var factor = Math.exp(-e.deltaY * 0.0015); // smooth, direction-correct
host._rkZoom = Math.max(MIN, Math.min(MAX, (host._rkZoom || 1) * factor));
RK.applyZoom(host);
}, { passive: false });
host.addEventListener('dblclick', function () {
host._rkZoom = 1;
RK.applyZoom(host);
});
};
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
function rendererCanvas(renderer) {
return renderer && (renderer.canvas || (renderer.app && renderer.app.view) ||
(renderer.renderer && renderer.renderer.domElement));
}
// Player-follow camera for fixed viewports (single/multiplayer races and spectator views).
// Renderers only need to expose `canvas` + `focusPoint`; ThreeRenderer instead handles zoom and
// following internally through setZoom(). The older attachZoom API above remains unchanged for
// whole-room previews that intentionally do not follow an avatar.
RK.attachCamera = function (host, opts) {
if (!host) return null;
if (host._rkCamera) return host._rkCamera.api;
opts = opts || {};
var state = host._rkCamera = {
zoom: clamp(Number(opts.zoom) || 1.35, Number(opts.min) || 0.55, Number(opts.max) || 3.2),
defaultZoom: Number(opts.zoom) || 1.35,
fitRatio: Number(opts.fitRatio) || 0,
autoFit: false,
min: Number(opts.min) || 0.55,
max: Number(opts.max) || 3.2,
panX: 0,
panY: 0,
renderer: null,
pointers: {},
pinchDistance: null,
listeners: [],
destroyed: false
};
host.style.position = host.style.position || 'relative';
host.style.overflow = 'hidden';
host.style.touchAction = 'none';
host.style.cursor = 'grab';
function updateReadout() {
if (state.readout) state.readout.textContent = Math.round(state.zoom * 100) + '%';
}
function listen(target, type, handler, options) {
target.addEventListener(type, handler, options);
state.listeners.push({ target: target, type: type, handler: handler, options: options });
}
function fitZoom(renderer, ratio) {
if (!renderer || renderer.name === '3d') return clamp(state.defaultZoom, state.min, state.max);
var canvas = rendererCanvas(renderer);
if (!canvas) return clamp(state.defaultZoom, state.min, state.max);
var cw = canvas.width || canvas.offsetWidth || 1;
var ch = canvas.height || canvas.offsetHeight || 1;
var w = host.clientWidth || host.offsetWidth || 640;
var h = host.clientHeight || host.offsetHeight || 400;
return clamp(Math.min(w / cw, h / ch) * (Number(ratio) || state.fitRatio || 0.72), state.min, state.max);
}
function setZoom(next, manual) {
if (state.destroyed) return;
if (manual) state.autoFit = false;
state.zoom = clamp(Number(next) || 1, state.min, state.max);
updateReadout();
RK.updateCamera(host, state.renderer);
}
function reset() {
if (state.destroyed) return;
state.panX = 0;
state.panY = 0;
state.autoFit = !!(state.fitRatio && state.renderer);
setZoom(state.autoFit ? fitZoom(state.renderer) : state.defaultZoom);
}
function onWheel(e) {
if (state.destroyed) return;
e.preventDefault();
setZoom(state.zoom * Math.exp(-e.deltaY * 0.0015), true);
}
function onDoubleClick(e) {
if (state.destroyed) return;
if (e.target && e.target.closest && e.target.closest('.rk-camera-controls')) return;
reset();
}
function onPointerDown(e) {
if (state.destroyed) return;
if (e.target && e.target.closest && e.target.closest('.rk-camera-controls')) return;
state.pointers[e.pointerId] = { x: e.clientX, y: e.clientY };
state.dragId = e.pointerId;
host.style.cursor = 'grabbing';
try { host.setPointerCapture(e.pointerId); } catch (_) {}
}
function onPointerMove(e) {
if (state.destroyed) return;
var prev = state.pointers[e.pointerId];
if (!prev) return;
state.pointers[e.pointerId] = { x: e.clientX, y: e.clientY };
var ids = Object.keys(state.pointers);
if (ids.length > 1) {
var a = state.pointers[ids[0]], b = state.pointers[ids[1]];
var dist = Math.hypot(a.x - b.x, a.y - b.y);
if (state.pinchDistance) setZoom(state.zoom * (dist / state.pinchDistance));
state.pinchDistance = dist;
} else {
state.autoFit = false;
state.panX += e.clientX - prev.x;
state.panY += e.clientY - prev.y;
RK.updateCamera(host, state.renderer);
}
}
function releasePointer(e) {
if (state.destroyed) return;
delete state.pointers[e.pointerId];
state.pinchDistance = null;
if (!Object.keys(state.pointers).length) host.style.cursor = 'grab';
}
listen(host, 'wheel', onWheel, { passive: false });
listen(host, 'dblclick', onDoubleClick);
listen(host, 'pointerdown', onPointerDown);
listen(host, 'pointermove', onPointerMove);
listen(host, 'pointerup', releasePointer);
listen(host, 'pointercancel', releasePointer);
if (opts.controls !== false && root.document) {
var controls = root.document.createElement('div');
controls.className = 'rk-camera-controls';
controls.setAttribute('aria-label', 'Camera controls');
controls.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:20;display:flex;' +
'align-items:center;gap:4px;padding:4px;background:rgba(4,7,10,.82);border:1px solid rgba(255,255,255,.2);' +
'border-radius:7px;box-shadow:0 4px 18px rgba(0,0,0,.45);font:12px ui-monospace,monospace;';
function button(label, title, fn) {
var b = root.document.createElement('button');
b.type = 'button'; b.textContent = label; b.title = title; b.setAttribute('aria-label', title);
b.style.cssText = 'min-width:30px;height:28px;padding:0 7px;background:#151b22;color:#e5e7eb;' +
'border:1px solid #3b4552;border-radius:4px;cursor:pointer;font:inherit;';
listen(b, 'click', function (e) { e.stopPropagation(); fn(); });
controls.appendChild(b);
}
button('−', 'Zoom out', function () { setZoom(state.zoom / 1.18, true); });
state.readout = root.document.createElement('span');
state.readout.style.cssText = 'min-width:42px;text-align:center;color:#a7f3d0;';
controls.appendChild(state.readout);
button('+', 'Zoom in', function () { setZoom(state.zoom * 1.18, true); });
button('⌂', 'Reset camera', reset);
host.appendChild(controls);
state.controls = controls;
}
updateReadout();
if (typeof root.ResizeObserver === 'function') {
state.observer = new root.ResizeObserver(function () {
if (state.destroyed) return;
if (state.autoFit) setZoom(fitZoom(state.renderer));
else RK.updateCamera(host, state.renderer);
});
state.observer.observe(host);
}
state.api = {
update: function (renderer) {
if (!state.destroyed) RK.updateCamera(host, renderer);
},
setZoom: setZoom,
setDefaultZoom: function (zoom) {
if (!state.destroyed) state.defaultZoom = Number(zoom) || state.defaultZoom;
},
fit: function (renderer, ratio) {
if (state.destroyed) return;
state.renderer = renderer || state.renderer;
if (ratio != null) state.fitRatio = Number(ratio) || state.fitRatio;
state.panX = 0;
state.panY = 0;
state.autoFit = !!state.renderer;
setZoom(fitZoom(state.renderer));
},
reset: reset,
getZoom: function () { return state.zoom; },
destroy: function () {
if (state.destroyed) return;
state.destroyed = true;
state.listeners.splice(0).forEach(function (entry) {
if (entry.target && typeof entry.target.removeEventListener === 'function') {
entry.target.removeEventListener(entry.type, entry.handler, entry.options);
}
});
Object.keys(state.pointers).forEach(function (pointerId) {
try {
if (typeof host.releasePointerCapture === 'function') {
host.releasePointerCapture(Number(pointerId));
}
} catch (_) {}
});
state.pointers = {};
state.pinchDistance = null;
host.style.cursor = 'grab';
if (state.observer) {
state.observer.disconnect();
state.observer = null;
}
if (state.controls && state.controls.parentNode) state.controls.parentNode.removeChild(state.controls);
state.controls = null;
state.readout = null;
state.renderer = null;
if (host._rkCamera === state) delete host._rkCamera;
}
};
return state.api;
};
RK.updateCamera = function (host, renderer) {
var state = host && host._rkCamera;
if (!state || !renderer) return;
state.renderer = renderer;
if (renderer.name === '3d') {
if (typeof renderer.setZoom === 'function') renderer.setZoom(state.zoom);
if (typeof renderer.setPan === 'function') renderer.setPan(state.panX, state.panY);
return;
}
var canvas = rendererCanvas(renderer);
if (!canvas) return;
var cw = canvas.width || canvas.offsetWidth || 1;
var ch = canvas.height || canvas.offsetHeight || 1;
var w = host.clientWidth || host.offsetWidth || 640;
var h = host.clientHeight || host.offsetHeight || 400;
var focus = renderer.focusPoint || { x: cw / 2, y: ch / 2 };
var z = state.zoom;
var tx = w / 2 - focus.x * z + state.panX;
var ty = h / 2 - focus.y * z + state.panY;
var sw = cw * z, sh = ch * z;
tx = sw <= w ? (w - sw) / 2 : clamp(tx, w - sw, 0);
ty = sh <= h ? (h - sh) / 2 : clamp(ty, h - sh, 0);
canvas.style.position = 'absolute';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.style.maxWidth = 'none';
canvas.style.maxHeight = 'none';
canvas.style.transformOrigin = '0 0';
canvas.style.imageRendering = 'pixelated';
canvas.style.transition = 'transform 110ms ease-out';
canvas.style.transform = 'translate(' + tx + 'px,' + ty + 'px) scale(' + z + ')';
};
})(window);