feat: add tavern render kit and character entitlements

This commit is contained in:
jwinterm
2026-07-05 20:57:46 -04:00
parent bb565f9cbf
commit 454e6ab69a
78 changed files with 5839 additions and 134 deletions
+8
View File
@@ -0,0 +1,8 @@
Art assets in this folder are by Kenney (https://kenney.nl), released under
Creative Commons Zero (CC0 1.0 Universal) — public domain.
- roguelikeIndoor.png — Kenney "Roguelike Interior Pack"
- roguelikeChar.png — Kenney "Roguelike Characters Pack"
Tile grid: 16x16 px, 1 px spacing (17 px stride), no margin.
No attribution is legally required; Kenney is credited here with thanks.
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

@@ -0,0 +1,18 @@
{
"_note": "Generated tile metadata for Kenney's roguelikeSheet (a grid sheet with no shipped names). Labelled by sight from the room's palette. This is the 'metadata layer' themes use; packs that ship XML (<SubTexture name=...>) are parsed instead of hand-labelled.",
"tile": 16, "spacing": 1, "cols": 57,
"names": {
"23": "barrel", "32": "barrel", "25": "crate",
"28": "counter_sink", "29": "counter", "194": "counter_stove", "677": "sink",
"87": "shelf", "88": "bookshelf", "258": "dresser", "360": "nightstand",
"311": "wardrobe", "368": "wardrobe", "138": "wardrobe",
"129": "bed", "201": "mirror", "482": "clock", "282": "banner", "141": "sack",
"137": "chair", "190": "chair", "191": "table", "197": "bench", "198": "bench", "312": "table",
"156": "window", "158": "window", "159": "window", "215": "window", "216": "window",
"550": "door", "620": "rubble", "585": "bush", "642": "tree", "897": "item",
"119": "floor_wood", "120": "floor_stone", "982": "floor_plank", "983": "floor_plank", "984": "floor_plank",
"922": "rug", "923": "rug", "924": "rug", "979": "rug", "980": "rug", "981": "rug", "1036": "rug", "1037": "rug", "1038": "rug",
"697": "wall", "698": "wall", "699": "wall", "700": "wall", "701": "wall",
"756": "wall", "757": "wall", "758": "wall", "868": "wall", "869": "wall", "871": "wall", "872": "wall", "873": "wall", "874": "wall"
}
}
File diff suppressed because one or more lines are too long
+3
View File
@@ -108,6 +108,9 @@
<button id="watchGamesButton" style="background: #053655; color: #0af; border: 2px solid #0af; padding: 8px 16px; font-weight: bold; cursor: pointer; margin-top: 5px; margin-left: 10px;">
👁️ <span class="lbl-full">WATCH GAMES</span><span class="lbl-short">WATCH</span>
</button>
<button id="tavernButton" style="background: #2a0a3a; color: #d8b4fe; border: 2px solid #a855f7; padding: 8px 16px; font-weight: bold; cursor: pointer; margin-top: 5px; margin-left: 10px; display: none;" onclick="window.location.href='/tavern.html'">
🍺 <span class="lbl-full">TAVERN</span><span class="lbl-short">TAVERN</span>
</button>
<button id="shopButton" style="background: #004400; color: #0f0; border: 2px solid #0f0; padding: 8px 16px; font-weight: bold; cursor: pointer; margin-top: 5px; margin-left: 10px; display: none;">
🛒 SHOP
</button>
+16 -3
View File
@@ -683,6 +683,14 @@ const SocketHandlers = {
SocketHandlers._currencyLabel = data.currencyLabel || data.cryptoType || 'WOW'; // sXMR on stagenet
SocketHandlers._explorerTxUrl = data.explorerTxUrl || null;
// Mode availability (Solo / Tavern / Multiplayer). Backward compatible: if the server
// doesn't send `modes`, assume solo-only (the historical behavior).
var modes = data.modes || { solo: true, tavern: false, multiplayer: false };
SocketHandlers._modes = modes;
if (modes.tavern) { $('#tavernButton').show(); } else { $('#tavernButton').hide(); }
// Tavern-only / no single-player instance: don't surface the solo start button.
if (modes.solo === false) { $('#startButton').hide(); }
// Initialize Smirk auth if enabled and not already initialized
if (SocketHandlers._smirkEnabled && typeof SmirkAuth !== 'undefined' && !SmirkAuth._initialized) {
SmirkAuth.init();
@@ -769,13 +777,18 @@ const SocketHandlers = {
try {
// Use human-readable amount (e.g. "1"), NOT atomic units (e.g. 100000000000)
var payAmount = data.humanAmount || data.amountFormatted || String(data.amount);
var description = 'Single game entry';
if (data.paymentType === 'credits_package') {
description = 'Buy ' + (data.package ? data.package.credits : '') + ' credits';
} else if (data.paymentType === 'cosmetic_pack') {
description = 'Unlock ' + (data.package ? (data.package.label || data.package.id || 'premium pack') : 'premium pack');
}
await window.smirk.requestPayment({
address: data.address,
amount: payAmount,
asset: (SocketHandlers._cryptoType || 'WOW').toLowerCase(),
description: data.paymentType === 'credits_package'
? 'Buy ' + (data.package ? data.package.credits : '') + ' credits'
: 'Single game entry'
description: description
});
// User confirmed in Smirk — TX submitted, server monitoring handles the rest
+74
View File
@@ -0,0 +1,74 @@
// 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;
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 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 = (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 def = scene.legend[scene.grid[y][x]] || { char: '?', color: '#555' };
ctx.fillStyle = def.color;
ctx.fillText(def.char, x * cell + cell / 2, y * cell + cell / 2);
}
}
}
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';
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);
}
}
};
AsciiRenderer.prototype.destroy = function () {
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);
+255
View File
@@ -0,0 +1,255 @@
// 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' };
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 || {};
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;
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 = {
'roguelike-interior': {
id: 'roguelike-interior',
label: 'Kenney Roguelike Interior',
tileset: { url: 'assets/kenney/roguelikeIndoor.png', tile: 16, spacing: 1 },
// Defaults are null until mapped via the tile-picker (localStorage overrides win).
tiles: { floor: null, wall: null, bar: null, table: null }
}
};
RK.activeThemeId = 'roguelike-interior';
RK.theme = function (id) { 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;
}
RK.packAppearances = function () {
var out = [];
for (var id in RK.EXTRA_APPEARANCES) out.push(RK.EXTRA_APPEARANCES[id]);
return out;
};
RK.isoAssets = {
pack: 'iso-dungeon',
tile: { w: 84, h: 42, imageW: 92, imageH: 184 },
tiles: {
floor: 'assets/kenney/iso-dungeon/tiles/stone_S.png',
wall: 'assets/kenney/iso-dungeon/tiles/stoneWall_S.png',
bar: 'assets/kenney/iso-dungeon/tiles/barrelsStacked_S.png',
table: 'assets/kenney/iso-dungeon/tiles/chestClosed_S.png',
fallback: 'assets/kenney/iso-dungeon/tiles/planks_S.png'
},
character: {
idle: 'assets/kenney/iso-dungeon/characters/male0/Male_0_Idle0.png',
run: [
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run0.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run1.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run2.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run3.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run4.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run5.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run6.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run7.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run8.png',
'assets/kenney/iso-dungeon/characters/male0/Male_0_Run9.png'
],
imageW: 74,
imageH: 148
}
};
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' }
}
}
};
RK.resolveAppearance = function (entity, projection) {
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),
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)
};
}
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);
+335
View File
@@ -0,0 +1,335 @@
// 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' };
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 baseAppearances() {
var list = [
{ id: 'default', label: 'Operator', 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 isChar = !!(RK.isChar && RK.isChar(avatar));
var tint = 'none';
var equipment = cloneEquipment(DEFAULT_EQUIPMENT);
if (isChar) {
if (RK.CHAR_TINTS && RK.CHAR_TINTS[input.tint]) tint = input.tint;
equipment = RK.normalizeCharEquipment ? RK.normalizeCharEquipment(input.equipment) : cloneEquipment(input.equipment);
}
return { avatar: avatar, tint: tint, equipment: equipment };
};
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.tint && ap.tint !== 'none' && RK.CHAR_TINTS && RK.CHAR_TINTS[ap.tint]) {
label += ' / ' + RK.CHAR_TINTS[ap.tint].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 drawBaseThumb(ctx, a, draft, onReady) {
ctx.clearRect(0, 0, 72, 80);
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 ap = RK.normalizeAppearance(draft || { avatar: a.id });
ap.avatar = a.id;
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() { drawBaseThumb(ctx, a, getDraft && getDraft(), 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 tint = item.tint === false ? 'none' : draft.tint;
if (!RK.drawCharTileCanvas || !RK.drawCharTileCanvas(ctx, item.frame, tint, 2, 2, 48, 48)) {
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;
}
RK.openCustomize = function (current, onSave) {
var draft = RK.normalizeAppearance(current);
var redrawers = [];
var wrap = document.createElement('div');
wrap.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.82);z-index:9999;overflow:auto;padding:20px;font-family:ui-monospace,monospace;color:#d7dbe0;';
var h = document.createElement('div');
h.textContent = 'Customize your character';
h.style.cssText = 'font-size:16px;font-weight:600;margin-bottom:12px;';
wrap.appendChild(h);
var preview = document.createElement('canvas');
preview.width = 92; preview.height = 100;
preview.style.cssText = 'display:block;margin:0 0 14px;image-rendering:pixelated;background:#0a0c0f;border:1px solid #2a313a;border-radius:6px;';
var pctx = preview.getContext('2d');
wrap.appendChild(preview);
var grid = document.createElement('div');
grid.style.cssText = 'display:flex;flex-wrap:wrap;gap:12px;max-width:820px;';
var cards = {};
RK.appearances().forEach(function (a) {
var card = document.createElement('div');
var locked = !!(RK.canUseAppearance && !RK.canUseAppearance(a));
card.style.cssText = 'width:108px;padding:8px;border:2px solid #2a313a;border-radius:8px;background:#0f1216;cursor:pointer;text-align:center;';
if (locked) card.style.cssText += 'opacity:0.55;';
if (locked) card.title = 'Premium pack - buy credits to unlock';
card.appendChild(thumbCanvas(a, function () { return draft; }, redrawers));
var lab = document.createElement('div');
lab.textContent = a.label + (a.premium ? ' *' : '');
lab.style.cssText = 'font-size:11px;margin-top:6px;color:#c7ccd4;';
card.appendChild(lab);
card.onclick = function () {
if (RK.canUseAppearance && !RK.canUseAppearance(a)) return;
draft.avatar = a.id;
if (!(RK.isChar && RK.isChar(draft.avatar))) {
draft.tint = 'none';
draft.equipment = cloneEquipment(DEFAULT_EQUIPMENT);
}
mark();
renderRows();
redrawAll();
};
grid.appendChild(card);
cards[a.id] = card;
});
wrap.appendChild(grid);
var rows = document.createElement('div');
rows.style.cssText = 'max-width:820px;margin-top:14px;';
wrap.appendChild(rows);
function optionButton(label, selected, onclick, canvas) {
var b = document.createElement('button');
b.type = 'button';
b.style.cssText = 'width:86px;min-height:78px;border:2px solid ' + (selected ? '#3fb950' : '#2a313a') + ';border-radius:6px;background:#0f1216;color:#c7ccd4;cursor:pointer;padding:6px;font:inherit;font-size:11px;';
if (canvas) b.appendChild(canvas);
var t = document.createElement('div');
t.textContent = label;
b.appendChild(t);
b.onclick = onclick;
return b;
}
function renderRows() {
rows.innerHTML = '';
if (!(RK.isChar && RK.isChar(draft.avatar))) return;
var tintRow = document.createElement('div');
tintRow.style.cssText = 'display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px;';
var tintLabel = document.createElement('div');
tintLabel.textContent = 'Tint';
tintLabel.style.cssText = 'width:68px;font-size:12px;color:#8b949e;';
tintRow.appendChild(tintLabel);
for (var tid in (RK.CHAR_TINTS || {})) {
(function (tint) {
var sw = document.createElement('span');
sw.style.cssText = 'display:block;width:28px;height:28px;margin:2px auto 5px;border-radius:50%;background:' + (tint.color || '#9aa4b2') + ';border:1px solid rgba(255,255,255,0.35);';
var b = optionButton(tint.label, draft.tint === tint.id, function () {
draft.tint = tint.id;
renderRows();
redrawAll();
}, sw);
b.style.minHeight = '64px';
tintRow.appendChild(b);
})(RK.CHAR_TINTS[tid]);
}
rows.appendChild(tintRow);
(RK.CHAR_EQUIPMENT_SLOTS || []).forEach(function (slot) {
var catalog = RK.CHAR_EQUIPMENT[slot] || {};
var row = document.createElement('div');
row.style.cssText = 'display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px;';
var label = document.createElement('div');
label.textContent = slot.charAt(0).toUpperCase() + slot.slice(1);
label.style.cssText = 'width:68px;font-size:12px;color:#8b949e;';
row.appendChild(label);
for (var id in catalog) {
(function (item) {
row.appendChild(optionButton(item.label, draft.equipment[slot] === item.id, function () {
draft.equipment[slot] = item.id;
renderRows();
redrawAll();
}, optionTileCanvas(slot, item, draft, redrawers)));
})(catalog[id]);
}
rows.appendChild(row);
});
}
function drawPreview() {
pctx.clearRect(0, 0, preview.width, preview.height);
var base = baseAppearance(draft.avatar);
if (base.kind === 'color') {
pctx.beginPath(); pctx.arc(46, 52, 24, 0, Math.PI * 2);
pctx.fillStyle = base.color; pctx.fill();
pctx.lineWidth = 2; pctx.strokeStyle = 'rgba(255,255,255,0.35)'; pctx.stroke();
} else if (base.kind === 'char') {
if (!RK.drawCharCompositeCanvas || !RK.drawCharCompositeCanvas(pctx, draft, 6, 8, 80)) RK.loadCharAtlas(redrawAll);
} else if (base.kind === 'model3d') {
pctx.beginPath(); pctx.arc(46, 52, 24, 0, Math.PI * 2);
pctx.fillStyle = '#64748b'; pctx.fill();
pctx.fillStyle = '#d7dbe0'; pctx.font = '20px monospace'; pctx.textAlign = 'center'; pctx.fillText('3D', 46, 59);
} else {
drawBaseThumb(pctx, base, draft, redrawAll);
}
}
function redrawAll() {
drawPreview();
redrawers.forEach(function (fn) { try { fn(); } catch (_) { /* ignore */ } });
}
function mark() {
for (var id in cards) cards[id].style.borderColor = (id === draft.avatar) ? '#3fb950' : '#2a313a';
}
var bar = document.createElement('div');
bar.style.cssText = 'margin-top:16px;display:flex;gap:8px;';
var save = document.createElement('button');
save.textContent = 'Save';
save.style.cssText = 'font:inherit;padding:8px 16px;border:0;border-radius:6px;background:#3fb950;color:#08130a;font-weight:600;cursor:pointer;';
save.onclick = function () {
var saved = RK.normalizeAppearance(draft);
RK.saveIdentity(saved);
document.body.removeChild(wrap);
if (onSave) onSave(saved);
};
var cancel = document.createElement('button');
cancel.textContent = 'Cancel';
cancel.style.cssText = 'font:inherit;padding:8px 16px;border:1px solid #2a313a;border-radius:6px;background:#0f1216;color:#d7dbe0;cursor:pointer;';
cancel.onclick = function () { document.body.removeChild(wrap); };
bar.appendChild(save); bar.appendChild(cancel);
wrap.appendChild(bar);
document.body.appendChild(wrap);
mark();
renderRows();
redrawAll();
};
})(window);
+269
View File
@@ -0,0 +1,269 @@
// 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
};
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_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, tint: false },
helm: { id: 'helm', label: 'Helm', frame: 454, tint: false },
horns: { id: 'horns', label: 'Horns', frame: 354, tint: false },
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, tint: false }
},
weapon: {
none: { id: 'none', label: 'None', frame: null },
staff: { id: 'staff', label: 'Staff', frame: 154 },
sword: { id: 'sword', label: 'Sword', frame: 369, tint: false },
axe: { id: 'axe', label: 'Axe', frame: 375, tint: false },
bow: { id: 'bow', label: 'Bow', frame: 107, tint: false }
}
};
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 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';
return {
avatar: avatar,
tint: validTint(ap.tint),
equipment: RK.normalizeCharEquipment(ap.equipment)
};
};
RK.charRenderKey = function (e) {
var ap = RK.charAppearance(e);
return [
ap.avatar, ap.tint,
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 tintedTileCanvas(idx, tintId) {
var a = RK.charAtlas();
tintId = validTint(tintId);
if (!a || tintId === 'none') return null;
var tint = RK.CHAR_TINTS[tintId];
if (!tint || !tint.ramp) return null;
var key = idx + '|' + tintId;
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);
var ramp = tint.ramp.map(hexToRgb);
for (var i = 0; i < img.data.length; i += 4) {
var k = img.data[i] + ',' + img.data[i + 1] + ',' + img.data[i + 2];
var ri = TINT_SOURCE[k];
if (ri == null || img.data[i + 3] === 0) 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;
}
ctx.putImageData(img, 0, 0);
tintedTiles[key] = cv;
return cv;
}
RK.charTileTexture = function (idx, tintId) {
tintId = validTint(tintId);
if (tintId === 'none') return RK.charTexture(idx);
if (typeof PIXI === 'undefined') return null;
var key = idx + '|' + tintId;
if (tintedTextures[key]) return tintedTextures[key];
var cv = tintedTileCanvas(idx, tintId);
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) {
var a = RK.charAtlas();
if (!a) return false;
var tinted = tintedTileCanvas(idx, tintId);
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 tint = validTint(appearance.tint);
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;
out.push({ slot: slot, id: item.id, frame: item.frame, tint: item.tint === false ? 'none' : tint });
});
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);
RK.charOverlayParts(appearance).forEach(function (part) {
RK.drawCharTileCanvas(ctx, part.frame, part.tint, dx, dy2, dw, dh);
});
}
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);
RK.charOverlayParts(ap).forEach(function (part) {
RK.drawCharTileCanvas(ctx, part.frame, part.tint, dx, dy, size, size);
});
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);
+384
View File
@@ -0,0 +1,384 @@
// 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';
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);
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);
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;
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;
}
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);
+169
View File
@@ -0,0 +1,169 @@
// 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.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.last = {};
this.lastScene = null;
this._raf = null;
this._animating = false;
host.appendChild(this.canvas);
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 ch = this.assets.character || {};
this._load(ch.idle);
(ch.run || []).forEach(this._load.bind(this));
};
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);
};
IsoRenderer.prototype._tileUrl = function (kind) {
var tiles = this.assets.tiles || {};
return tiles[kind] || tiles.fallback || tiles.floor;
};
IsoRenderer.prototype._charFrame = function (e, now) {
var key = e.id || 'anon';
var st = this.last[key] || (this.last[key] = { x: e.x, y: e.y, t: 0 });
if (st.x !== e.x || st.y !== e.y) { st.x = e.x; st.y = e.y; st.t = now; }
var moving = (now - st.t) < 360;
var resolved = (root.RK && RK.resolveAppearance) ? RK.resolveAppearance(e, 'iso') : null;
var ch = (resolved && resolved.character) || (this.assets.character || {});
if (!moving || !ch.run || ch.run.length === 0) return ch.idle;
this._animating = true;
return ch.run[Math.floor(now / 80) % ch.run.length];
};
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;
this.canvas.width = Math.ceil((scene.cols + scene.rows) * this.tileW / 2 + margin * 2 + this.tileW * 2);
this.canvas.height = Math.ceil((scene.cols + scene.rows) * this.tileH / 2 + this.imageH + margin * 2);
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;
var items = [], x, y, kind, p;
for (y = 0; y < scene.rows; y++) {
for (x = 0; x < scene.cols; x++) {
kind = scene.grid[y][x];
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 (kind === 'bar' || kind === 'table') {
items.push({ type: 'prop', kind: kind, x: x, y: y, sx: p.x, sy: p.y, depth: x + y + 0.25 });
}
}
}
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 });
}
items.sort(function (a, b) { return a.depth === b.depth ? (a.y || 0) - (b.y || 0) : a.depth - b.depth; });
var now = Date.now();
for (i = 0; i < items.length; i++) {
var it = items[i];
if (it.type === 'tile') {
var tileKind = (it.kind === 'bar' || it.kind === 'table') ? 'floor' : it.kind;
var rec = this._load(this._tileUrl(tileKind));
if (rec && rec.ready) this._drawImage(rec.img, it.sx, it.sy + this.tileH, this.imageW, this.imageH);
} else if (it.type === 'prop') {
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 === 'entity') {
var frame = this._charFrame(it.e, now);
rec = this._load(frame);
if (rec && rec.ready) {
var ch = this.assets.character || {};
this._drawImage(rec.img, it.sx, it.sy + this.tileH * 0.95, ch.imageW || 74, ch.imageH || 148);
} 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);
}
}
}
if (this._animating) this._invalidate();
};
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.last = {};
this.lastScene = null;
};
root.RK = root.RK || {};
root.RK.IsoRenderer = IsoRenderer;
})(window);
+131
View File
@@ -0,0 +1,131 @@
// Render mode registry, factory, and entitlements for the render kit (RK).
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
// 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.
RK.RENDER_MODES = [
{ id: 'tiles', label: 'Tiled', premium: false },
{ id: 'ascii', label: 'ASCII', premium: true },
{ id: 'fancy', label: 'Fancy', premium: true, pack: 'generated-skins' },
{ id: 'iso', label: 'Iso', premium: true, pack: 'iso-dungeon' },
{ id: '3d', label: '3D', premium: true, pack: 'kenney-3d-characters' }
// Planned: 'fancy-ascii' — shader-lit, animated glyphs.
];
RK.entitlements = RK.entitlements || { premium: false, level: 'free', packs: {} };
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 (m.pack && RK.canUsePack) return RK.canUsePack(m.pack);
return !m.premium || !!RK.entitlements.premium;
};
RK.createRenderer = function (mode, 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) return new RK.ThreeRenderer(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; }
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.ensureThree = function (cb) {
if (RK.threeReady()) { cb(true); return; }
threeCbs.push(cb);
if (threeLoading) return;
threeLoading = true;
Promise.all([
import('https://cdn.jsdelivr.net/npm/three@0.160.0/+esm'),
import('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/loaders/GLTFLoader.js/+esm')
]).then(function (mods) {
RK.THREE = { THREE: mods[0], GLTFLoader: mods[1].GLTFLoader };
var cbs = threeCbs; threeCbs = [];
cbs.forEach(function (f) { f(true); });
}).catch(function (e) {
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 (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);
+77
View File
@@ -0,0 +1,77 @@
// 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).
var TAVERN_LEGEND = {
wall: { char: '#', color: '#20262e', solid: true },
floor: { char: '·', color: '#0c1410', solid: false },
bar: { char: '=', color: '#5a4632', solid: true },
table: { char: 'o', color: '#4a3a28', solid: true }
};
// Layout character -> tile kind.
var TAVERN_TILE_OF = { '#': 'wall', '.': 'floor', '@': 'floor', '=': 'bar', 'o': 'table' };
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 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++) {
row.push(TAVERN_TILE_OF[srcRow[x]] || '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
};
root.RK = root.RK || {};
root.RK.scene = api;
if (typeof module !== 'undefined' && module.exports) module.exports = api;
})(typeof window !== 'undefined' ? window : this);
+118
View File
@@ -0,0 +1,118 @@
// Character skins for the render kit. A skin is an animated sprite sheet (rows = facing
// directions, cols = animation frames) produced by the sprite pipeline
// (~/src/docs/animated-sprite-pipeline.md). Sheets are HEAVY and PREMIUM, so they are:
// - 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);
+210
View File
@@ -0,0 +1,210 @@
// ThreeRenderer — lightweight 3D projection for the shared Scene. It uses generated GLB avatars
// when available and falls back to low-poly pieces so the mode remains usable during asset work.
(function (root) {
'use strict';
function colorNum(hex) { return parseInt(String(hex || '#9aa4b2').replace('#', ''), 16) || 0x9aa4b2; }
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.models = {};
this.mixers = [];
this.entities = {};
this.last = {};
this._sizeKey = null;
this._init();
}
ThreeRenderer.prototype._init = function () {
var T = this.THREE;
this.scene = new T.Scene();
this.scene.background = new T.Color(0x0a0c0f);
this.camera = new T.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
this.camera.position.set(8, 9, 8);
this.camera.lookAt(0, 0, 0);
this.renderer = new T.WebGLRenderer({ antialias: true, alpha: false, preserveDrawingBuffer: true });
this.renderer.domElement.className = 'rk-canvas';
this.renderer.setPixelRatio(Math.min(2, root.devicePixelRatio || 1));
this.host.appendChild(this.renderer.domElement);
var hemi = new T.HemisphereLight(0xfff3d2, 0x283044, 2.1);
this.scene.add(hemi);
var key = new T.DirectionalLight(0xffffff, 1.6);
key.position.set(6, 10, 5);
this.scene.add(key);
this.world = new T.Group();
this.scene.add(this.world);
this.clock = new T.Clock();
var self = this;
this._raf = requestAnimationFrame(function tick() { self._animate(); self._raf = requestAnimationFrame(tick); });
};
ThreeRenderer.prototype._resize = function (scene) {
var w = Math.max(420, scene.cols * 32);
var h = Math.max(360, scene.rows * 28 + 120);
this.renderer.setSize(w, h, false);
var aspect = w / h, span = Math.max(scene.cols, scene.rows) * 0.78 + 2.5;
this.camera.left = -span * aspect;
this.camera.right = span * aspect;
this.camera.top = span;
this.camera.bottom = -span;
this.camera.updateProjectionMatrix();
};
ThreeRenderer.prototype._mat = function (hex) {
var T = this.THREE;
return new T.MeshStandardMaterial({ color: colorNum(hex), roughness: 0.82, metalness: 0.02 });
};
ThreeRenderer.prototype._buildTiles = function (scene) {
var T = this.THREE;
this.world.clear();
this.tileLayer = new T.Group();
this.entityLayer = new T.Group();
this.world.add(this.tileLayer, this.entityLayer);
var cx = (scene.cols - 1) / 2, cz = (scene.rows - 1) / 2;
for (var y = 0; y < scene.rows; y++) {
for (var x = 0; x < scene.cols; x++) {
var kind = scene.grid[y][x];
var def = scene.legend[kind] || {};
var h = kind === 'wall' ? 0.9 : (kind === 'bar' ? 0.42 : (kind === 'table' ? 0.28 : 0.08));
var geom = new T.BoxGeometry(kind === 'wall' ? 1 : 0.96, h, kind === 'wall' ? 1 : 0.96);
var mesh = new T.Mesh(geom, this._mat(kind === 'floor' ? '#4f4a3e' : (def.color || '#333333')));
mesh.position.set(x - cx, h / 2 - 0.05, y - cz);
this.tileLayer.add(mesh);
}
}
this.world.position.set(0, 0, 0);
};
ThreeRenderer.prototype._fallbackAvatar = function (e) {
var T = this.THREE;
var g = new T.Group();
var body = new T.Mesh(new T.CapsuleGeometry(0.24, 0.56, 4, 8), this._mat(e.color || '#9aa4b2'));
body.position.y = 0.52;
g.add(body);
var face = new T.Mesh(new T.BoxGeometry(0.11, 0.07, 0.035), this._mat('#0a0c0f'));
face.position.set(0, 0.7, 0.23);
g.add(face);
return g;
};
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._makeEntity = function (e) {
var T = this.THREE, self = this;
var shell = new T.Group();
shell._body = this._fallbackAvatar(e);
shell.add(shell._body);
var resolved = (root.RK && RK.resolveAppearance) ? RK.resolveAppearance(e, '3d') : null;
if (root.RK && RK.canUsePack && resolved && RK.canUsePack(resolved.pack)) {
this._loadModel(resolved, function (rec) {
if (!rec || !rec.gltf || !shell.parent) return;
shell.remove(shell._body);
var model = rec.gltf.scene.clone(true);
model.scale.setScalar(0.55);
model.rotation.y = Math.PI;
shell.add(model);
shell._body = model;
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);
});
var idle = shell._actions.idle || shell._actions[Object.keys(shell._actions)[0]];
if (idle) idle.play();
self.mixers.push(mixer);
}
});
}
return shell;
};
ThreeRenderer.prototype.render = function (scene) {
if (!scene || !this.renderer) return;
this._resize(scene);
var key = scene.cols + 'x' + scene.rows + ':' + scene.grid.map(function (r) { return r.join(''); }).join('/');
if (key !== this._sizeKey) {
this._buildTiles(scene);
this._sizeKey = key;
}
var seen = {}, cx = (scene.cols - 1) / 2, cz = (scene.rows - 1) / 2;
for (var 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) {
ent = this.entities[id] = { obj: this._makeEntity(e), 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]) {
this.entityLayer.remove(this.entities[id].obj);
delete this.entities[id];
}
}
};
ThreeRenderer.prototype._animate = function () {
if (!this.renderer) return;
var dt = this.clock.getDelta();
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;
o.position.x += ((ent.tx || 0) - o.position.x) * 0.18;
o.position.z += ((ent.tz || 0) - o.position.z) * 0.18;
if (ent.e && ent.e.facing) {
var r = ent.e.facing === 'up' ? Math.PI : ent.e.facing === 'left' ? -Math.PI / 2 : ent.e.facing === 'right' ? Math.PI / 2 : 0;
o.rotation.y += (r - o.rotation.y) * 0.18;
}
}
this.renderer.render(this.scene, this.camera);
};
ThreeRenderer.prototype.destroy = function () {
if (this._raf) cancelAnimationFrame(this._raf);
if (this.renderer) {
if (this.renderer.domElement && this.renderer.domElement.parentNode) this.renderer.domElement.parentNode.removeChild(this.renderer.domElement);
this.renderer.dispose();
}
this.renderer = null;
this.entities = {};
this.models = {};
this.mixers = [];
};
root.RK = root.RK || {};
root.RK.ThreeRenderer = ThreeRenderer;
})(window);
+82
View File
@@ -0,0 +1,82 @@
// Tile-picker — a dev overlay to map a theme's tileset cells to game tile-kinds by CLICKING.
// Pick a kind (floor/wall/bar/table), click the matching cell in the sheet; it's saved to
// localStorage and the tavern re-renders live. Works for any pack, so no coordinate-guessing.
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
RK.openTilePicker = function (onChange) {
var themeId = RK.activeThemeId;
var atlas = RK.themeAtlas(themeId);
if (!atlas) return;
atlas.onReady(function () { build(themeId, atlas, onChange); });
};
function build(themeId, atlas, onChange) {
var SCALE = 2;
var stride = atlas.tile + atlas.spacing;
var wrap = document.createElement('div');
wrap.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.82);z-index:9999;overflow:auto;padding:16px;font-family:ui-monospace,monospace;color:#d7dbe0;';
var bar = document.createElement('div');
bar.style.cssText = 'display:flex;gap:8px;align-items:center;margin-bottom:8px;flex-wrap:wrap;';
var active = RK.TILE_KINDS[0];
var status = document.createElement('span');
status.style.cssText = 'font-size:13px;color:#9cf;';
RK.TILE_KINDS.forEach(function (k) {
var b = document.createElement('button');
b.textContent = k; b.dataset.kind = k;
b.style.cssText = 'font:inherit;padding:6px 10px;border:1px solid #2a313a;border-radius:4px;background:#0a0c0f;color:#d7dbe0;cursor:pointer;';
b.onclick = function () { active = k; refresh(); status.textContent = 'Click the tile for: ' + k; };
bar.appendChild(b);
});
var done = document.createElement('button');
done.textContent = 'Done';
done.style.cssText = 'font:inherit;padding:6px 12px;border:0;border-radius:4px;background:#3fb950;color:#08130a;cursor:pointer;font-weight:600;margin-left:auto;';
done.onclick = function () { document.body.removeChild(wrap); };
bar.appendChild(status); bar.appendChild(done);
function refresh() {
Array.prototype.forEach.call(bar.querySelectorAll('button[data-kind]'), function (b) {
b.style.outline = b.dataset.kind === active ? '2px solid #3fb950' : 'none';
});
}
wrap.appendChild(bar);
var cv = document.createElement('canvas');
cv.width = atlas.img.width * SCALE; cv.height = atlas.img.height * SCALE;
cv.style.cssText = 'image-rendering:pixelated;border:1px solid #2a313a;background:#111;cursor:crosshair;';
var ctx = cv.getContext('2d');
function draw() {
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, cv.width, cv.height);
ctx.drawImage(atlas.img, 0, 0, cv.width, cv.height);
ctx.strokeStyle = 'rgba(63,185,80,0.22)'; ctx.lineWidth = 1;
for (var c = 0; c <= atlas.cols; c++) { ctx.beginPath(); ctx.moveTo(c * stride * SCALE, 0); ctx.lineTo(c * stride * SCALE, cv.height); ctx.stroke(); }
for (var r = 0; r <= atlas.rows; r++) { ctx.beginPath(); ctx.moveTo(0, r * stride * SCALE); ctx.lineTo(cv.width, r * stride * SCALE); ctx.stroke(); }
var map = RK.tileMap(themeId);
RK.TILE_KINDS.forEach(function (k) {
var co = map[k]; if (!co) return;
ctx.strokeStyle = '#ffb800'; ctx.lineWidth = 2;
ctx.strokeRect(co[0] * stride * SCALE, co[1] * stride * SCALE, atlas.tile * SCALE, atlas.tile * SCALE);
ctx.fillStyle = '#ffb800'; ctx.font = 'bold 11px monospace';
ctx.fillText(k[0].toUpperCase(), co[0] * stride * SCALE + 2, co[1] * stride * SCALE + 11);
});
}
cv.onclick = function (e) {
var rect = cv.getBoundingClientRect();
var col = Math.floor(((e.clientX - rect.left) / SCALE) / stride);
var row = Math.floor(((e.clientY - rect.top) / SCALE) / stride);
if (col < 0 || row < 0 || col >= atlas.cols || row >= atlas.rows) return;
RK.setTile(themeId, active, col, row);
draw();
if (onChange) onChange();
};
wrap.appendChild(cv);
document.body.appendChild(wrap);
refresh(); status.textContent = 'Click the tile for: ' + active; draw();
}
})(window);
+102
View File
@@ -0,0 +1,102 @@
// TileRenderer — draws a Scene as coloured tiles + entity sprites on a 2D canvas.
// The default tier. Uses programmatic tiles for now; a real tileset/atlas can slot in here.
(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 };
}
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);
}
TileRenderer.prototype.render = function (scene) {
if (!scene) 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);
if (window.RK && RK.roomReady && RK.roomReady()) {
// A designed room (imported .tmx) is loaded — draw its layered tiles.
RK.drawRoomCanvas(ctx, cell);
} else {
// Theme atlas tile if mapped, else the programmatic coloured tile.
var atlas = (window.RK && RK.themeAtlas) ? RK.themeAtlas() : null;
var tmap = (window.RK && RK.tileMap) ? RK.tileMap() : {};
var useAtlas = atlas && atlas.ready;
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 coord = useAtlas ? tmap[kind] : null;
if (coord) { atlas.draw(ctx, coord[0], coord[1], px, py, cell); continue; }
var def = scene.legend[kind] || { color: '#333' };
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));
}
}
}
}
var now = Date.now();
for (var i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i];
// Roguelike character sprite, or premium animated skin; else the fallback circle.
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);
}
}
};
TileRenderer.prototype.destroy = function () {
if (this.canvas && this.canvas.parentNode) this.canvas.parentNode.removeChild(this.canvas);
this.canvas = null;
this.ctx = null;
};
root.RK = root.RK || {};
root.RK.TileRenderer = TileRenderer;
})(window);
+85 -3
View File
@@ -101,6 +101,43 @@ const PaymentUI = {
return (atomicAmount / divisor).toFixed(decimals === 12 ? 4 : 2);
},
escapeHtml: function(value) {
return String(value == null ? '' : value).replace(/[&<>"']/g, function(ch) {
return ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
})[ch];
});
},
grantLabel: function(packId) {
const pack = window.RK && window.RK.PACKS ? window.RK.PACKS[packId] : null;
const labels = {
'generated-skins': 'Premium skins',
'iso-dungeon': 'Isometric dungeon',
'kenney-3d-characters': '3D characters',
'roguelike-interior': 'Roguelike interior'
};
return (pack && pack.label) || labels[packId] || packId;
},
grantSummaryHtml: function(grants, options = {}) {
if (!grants) return '';
const parts = [];
if (options.includeCredits && Number(grants.credits || 0) > 0) {
parts.push(`${Number(grants.credits)} credits`);
}
(grants.packs || []).forEach(packId => parts.push(this.grantLabel(packId)));
if (grants.premiumLevel) {
parts.push(`${grants.premiumLevel} tier`);
}
if (parts.length === 0) return '';
return `<div style="font-size:0.78em;color:#fbbf24;margin-top:4px;margin-left:${options.indent || 0}px;">Includes: ${this.escapeHtml(parts.join(' • '))}</div>`;
},
render: function() {
if (!this.config) return;
@@ -109,6 +146,7 @@ const PaymentUI = {
const currency = this.config.currencyLabel || this.config.cryptoType || 'WOW';
const hasCredits = this.userCredits >= (this.config.creditsPerGame || 1);
const creditPackages = this.config.creditPackages || [];
const cosmeticProducts = this.config.cosmeticProducts || [];
const $container = $('.game-modes');
$container.empty();
@@ -228,6 +266,7 @@ const PaymentUI = {
const bonusText = pkg.bonus > 0
? `<span style="color:#4ade80;"> +${pkg.bonus} bonus</span>`
: '';
const grantSummary = this.grantSummaryHtml(pkg.grants, { indent: 22 });
const checked = index === 0 ? 'checked' : '';
if (index === 0) this.selectedPackageId = pkg.id;
@@ -241,6 +280,7 @@ const PaymentUI = {
<div style="font-size:0.8em;color:#888;margin-top:4px;margin-left:22px;">
${perGamePrice} ${currency}/game for ${totalCredits} games
</div>
${grantSummary}
</label>
`;
});
@@ -262,6 +302,39 @@ const PaymentUI = {
</div>
`);
}
// === SECTION 4: Standalone cosmetic/render products ===
if (this.config.paymentsEnabled && cosmeticProducts.length > 0) {
let productsHtml = '';
cosmeticProducts.forEach(product => {
const priceFormatted = product.priceFormatted || this.formatPrice(product.price);
const label = this.escapeHtml(product.label || product.id);
const grantSummary = this.grantSummaryHtml(product.grants, { includeCredits: true });
productsHtml += `
<div style="padding:10px;margin:5px 0;background:#252540;border:1px solid #444;border-radius:4px;">
<div style="display:flex;gap:10px;justify-content:space-between;align-items:center;">
<strong style="color:#f0f0f0;">${label}</strong>
<span style="color:#fbbf24;font-weight:bold;">${priceFormatted} ${currency}</span>
</div>
${grantSummary}
<button class="mode-option" data-mode="SHOP" data-action="buy_product" data-package-id="${this.escapeHtml(product.id)}"
style="width:100%;padding:8px;margin-top:8px;background:#334155;border:none;color:#fff;cursor:pointer;border-radius:4px;">
Unlock Pack
</button>
</div>
`;
});
$container.append(`
<div class="payment-section" style="margin-bottom:15px;padding:12px;background:#1a1a2e;border:1px solid #444;border-radius:6px;">
<div style="margin-bottom:10px;">
<strong style="color:#f0f0f0;">Premium Packs</strong>
<span style="font-size:0.85em;color:#888;margin-left:10px;">Cosmetics and render modes</span>
</div>
${productsHtml}
</div>
`);
}
// === Credits balance display (if has some but not enough) ===
if (this.config.creditsModeEnabled && this.userCredits > 0 && !hasCredits) {
@@ -314,11 +387,17 @@ const PaymentUI = {
let paymentType = 'single_game';
if (action === 'buy_credits') {
paymentType = 'credits_package';
} else if (action === 'buy_product') {
paymentType = 'cosmetic_pack';
}
const requestData = { type: paymentType };
if (packageId) {
requestData.packageId = packageId;
if (paymentType === 'cosmetic_pack') {
requestData.productId = packageId;
} else {
requestData.packageId = packageId;
}
}
if (window.socket) {
@@ -339,10 +418,13 @@ const PaymentUI = {
$('.game-modes').hide();
const isCreditsPurchase = data.paymentType === 'credits_package';
const isProductPurchase = data.paymentType === 'cosmetic_pack';
let headerText = '💳 Payment Required';
if (isCreditsPurchase && data.package) {
const bonus = data.package.bonus > 0 ? ` +${data.package.bonus} bonus` : '';
headerText = `🎫 Buy ${data.package.credits}${bonus} Credits`;
} else if (isProductPurchase && data.package) {
headerText = `Buy ${data.package.label || data.package.id || 'Pack'}`;
}
$('.payment-header strong').text(headerText);
@@ -354,9 +436,9 @@ const PaymentUI = {
if (data.reused) {
$('#payment-status').html('<span style="color:#ff0">♻️ Using existing pending payment</span>');
} else {
const statusText = isCreditsPurchase
const statusText = isCreditsPurchase
? 'Send payment to receive credits...'
: 'Waiting for payment...';
: (isProductPurchase ? 'Send payment to unlock this pack...' : 'Waiting for payment...');
$('#payment-status').text(statusText);
}
},
+301
View File
@@ -0,0 +1,301 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tavern - Wownerogue</title>
<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
<!-- PixiJS (+ @pixi/unsafe-eval for the CSP) is lazy-loaded by renderModes.js only when the
Fancy mode is first selected, so ASCII/Tiled users never download the WebGL library. -->
<script src="js/render/sceneModel.js"></script>
<script src="js/render/skins.js"></script>
<script src="js/render/charCustomize.js"></script>
<script src="js/render/atlas.js"></script>
<script src="js/render/charSprites.js"></script>
<script src="js/render/assetPacks.js"></script>
<script src="js/render/designedRoom.js"></script>
<script src="js/render/asciiRenderer.js"></script>
<script src="js/render/tileRenderer.js"></script>
<script src="js/render/fancyRenderer.js"></script>
<script src="js/render/isoRenderer.js"></script>
<script src="js/render/threeRenderer.js"></script>
<script src="js/render/renderModes.js"></script>
<style>
:root { --bg: #0f1216; --panel: #171b21; --line: #2a313a; --text: #d7dbe0; --accent: #3fb950; }
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text);
font-family: ui-monospace, Menlo, Consolas, monospace; }
.wrap { max-width: 760px; margin: 0 auto; padding: 16px; }
h1 { font-size: 18px; margin: 4px 0 12px; }
.muted { color: #8b949e; font-size: 13px; }
.rk-canvas { background: #0a0c0f; border: 1px solid var(--line); border-radius: 6px;
display: block; max-width: 100%; }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 6px;
padding: 12px; margin-bottom: 12px; }
label { font-size: 13px; margin-right: 6px; }
input, select, button { font: inherit; background: #0a0c0f; color: var(--text);
border: 1px solid var(--line); border-radius: 4px; padding: 6px 8px; }
button { background: var(--accent); color: #08130a; border: 0; cursor: pointer; font-weight: 600; }
button:disabled { opacity: 0.5; cursor: default; }
#status { min-height: 18px; font-size: 13px; }
.hidden { display: none; }
#modebar { display: flex; gap: 6px; margin-bottom: 8px; }
.modebtn { background: #0a0c0f; color: var(--text); border: 1px solid var(--line); font-weight: 500; }
.modebtn.active { background: var(--accent); color: #08130a; border-color: var(--accent); }
.modebtn.locked { opacity: 0.55; }
#chatPanel { margin-top: 12px; }
#chatLog { height: 160px; overflow-y: auto; border: 1px solid var(--line); border-radius: 4px;
padding: 8px; background: #0a0c0f; font-size: 13px; line-height: 1.45; }
#chatLog .cname { color: var(--accent); font-weight: 600; }
#chatLog .cline { margin: 2px 0; word-break: break-word; }
#chatLog .csys { color: #8b949e; font-style: italic; }
#chatForm { display: flex; gap: 6px; margin-top: 8px; }
#chatInput { flex: 1; }
</style>
</head>
<body>
<div class="wrap">
<h1>Tavern <span class="muted">— early preview</span></h1>
<div id="joinPanel" class="panel">
<label for="name">Name</label>
<input id="name" maxlength="16" placeholder="anon" autocomplete="off">
<button id="customizeBtn" type="button">🎭 Customize</button>
<span id="appearancePreview" class="muted"></span>
<button id="joinBtn">Enter tavern</button>
</div>
<div id="modebar" class="hidden"></div>
<div id="stage" class="hidden"></div>
<p id="status" class="muted"></p>
<p class="muted">Move with arrow keys or WASD. ★ modes are premium (credit unlock).</p>
<div id="chatPanel" class="panel hidden">
<div id="chatLog" aria-live="polite"></div>
<form id="chatForm" autocomplete="off">
<input id="chatInput" maxlength="200" placeholder="Say something…">
<button type="submit">Send</button>
</form>
</div>
</div>
<script>
(function () {
var socketOpts = {};
try {
var resumeToken = localStorage.getItem('wownerogue_token');
if (resumeToken) socketOpts.auth = { resumeToken: resumeToken };
} catch (_) {}
var socket = io(socketOpts);
var RK = window.RK;
var statusEl = document.getElementById('status');
var joinPanel = document.getElementById('joinPanel');
var joinBtn = document.getElementById('joinBtn');
var stageEl = document.getElementById('stage');
var modebar = document.getElementById('modebar');
var chatLog = document.getElementById('chatLog');
var chatForm = document.getElementById('chatForm');
var chatInput = document.getElementById('chatInput');
// Character customization — persisted appearance identity, chosen before entering.
var customizeBtn = document.getElementById('customizeBtn');
var appearancePreview = document.getElementById('appearancePreview');
var selectedAppearance = ((RK.loadIdentity && RK.loadIdentity()) || {}).appearance || RK.normalizeAppearance('default');
function updateAppearancePreview() {
var a = RK.appearance ? RK.appearance(selectedAppearance) : null;
appearancePreview.textContent = a ? ('- ' + a.label + (a.premium ? ' *' : '')) : '';
}
customizeBtn.addEventListener('click', function () {
RK.openCustomize(selectedAppearance, function (appearance) {
selectedAppearance = RK.normalizeAppearance(appearance);
updateAppearancePreview();
socket.emit('identity:update', { appearance: selectedAppearance });
});
});
updateAppearancePreview();
var state = { layout: null, cols: 0, rows: 0, occupants: [], you: null, channel: null };
var currentRenderer = null;
var currentMode = null;
var currentScene = null;
function setStatus(msg) { statusEl.textContent = msg; }
function applyEntitlements(data) {
if (RK.setEntitlementSnapshot) RK.setEntitlementSnapshot(data || {});
updateAppearancePreview();
if (!modebar.classList.contains('hidden')) {
buildModebar();
if (currentMode && !RK.canUseMode(currentMode)) setMode('tiles');
}
}
// ---- Rendering ---------------------------------------------------------------
function rebuildScene() {
if (!state.layout) return;
currentScene = RK.scene.sceneFromTavern(state, state.you);
}
function draw() {
if (currentRenderer && currentScene) currentRenderer.render(currentScene);
}
function setMode(mode) {
if (!RK.canUseMode(mode)) { setStatus(mode + ' is a premium mode (credit unlock).'); return; }
if (currentRenderer) { currentRenderer.destroy(); currentRenderer = null; }
currentMode = mode;
RK.saveMode(mode);
updateModeButtons();
if (mode === 'fancy' && !RK.pixiReady()) setStatus('Loading Fancy renderer…');
// Async: Fancy lazy-loads PixiJS on first use.
RK.createRendererAsync(mode, stageEl, {}, function (r) {
if (currentMode !== mode) { r.destroy(); return; } // switched again while loading
currentRenderer = r;
draw();
var active = r.name || mode;
setStatus(active === mode
? 'Render mode: ' + active
: '“' + mode + '” unavailable here — using “' + active + '”.');
});
}
function buildModebar() {
modebar.innerHTML = '';
RK.RENDER_MODES.forEach(function (m) {
var b = document.createElement('button');
b.className = 'modebtn';
b.dataset.mode = m.id;
b.textContent = m.label + (m.premium ? ' ★' : '');
if (!RK.canUseMode(m.id)) { b.classList.add('locked'); b.title = 'Premium pack — buy credits to unlock'; }
b.addEventListener('click', function () { setMode(m.id); });
modebar.appendChild(b);
});
updateModeButtons();
}
function updateModeButtons() {
Array.prototype.forEach.call(modebar.children, function (b) {
b.classList.toggle('active', b.dataset.mode === currentMode);
});
}
// ---- Join / state ------------------------------------------------------------
joinBtn.addEventListener('click', function () {
var name = document.getElementById('name').value || '';
var appearance = RK.normalizeAppearance(selectedAppearance);
joinBtn.disabled = true;
socket.emit('tavern_join', { name: name, avatar: appearance.avatar, appearance: appearance });
});
socket.on('tavern_error', function (e) {
joinBtn.disabled = false;
setStatus((e && e.message) || 'Could not enter the tavern.');
});
socket.on('game_mode_info', function (data) {
if (data && data.entitlements) applyEntitlements(data.entitlements);
});
socket.on('credits_update', applyEntitlements);
socket.on('session_token', function (data) {
try { if (data && data.token) localStorage.setItem('wownerogue_token', data.token); } catch (_) {}
});
socket.on('session_resumed', function (data) {
try { if (data && data.token) localStorage.setItem('wownerogue_token', data.token); } catch (_) {}
applyEntitlements(data || {});
});
socket.on('identity_update', function (data) {
if (!data) return;
if (data.entitlements) applyEntitlements(data.entitlements);
if (data.appearance) {
selectedAppearance = RK.normalizeAppearance(data.appearance);
RK.saveIdentity(selectedAppearance);
updateAppearancePreview();
}
});
socket.on('identity_error', function (data) {
if (data && data.message) setStatus(data.message);
});
socket.on('tavern_joined', function (data) {
state.you = data.you;
applyFull(data.state);
joinPanel.classList.add('hidden');
modebar.classList.remove('hidden');
stageEl.classList.remove('hidden');
document.getElementById('chatPanel').classList.remove('hidden');
rebuildScene();
buildModebar();
setMode(RK.loadMode('tiles'));
// Load the designed room (if the server is using one); re-render when ready.
if (state.roomUrl) RK.loadRoom(state.roomUrl, function () { draw(); });
setStatus('You are in the tavern.');
});
socket.on('tavern_update', function (snap) {
if (!snap) return;
state.occupants = snap.occupants || [];
rebuildScene();
draw();
});
function applyFull(s) {
state.layout = s.layout || [];
state.cols = s.cols || (state.layout[0] ? state.layout[0].length : 0);
state.rows = s.rows || state.layout.length;
state.occupants = s.occupants || [];
state.channel = 'tavern:' + (s.roomId || 'main');
state.roomUrl = s.roomUrl || null;
}
// ---- Chat --------------------------------------------------------------------
socket.on('chat_broadcast', function (m) {
if (!m || !state.channel || m.scope !== state.channel) return;
addChatLine(m.username, m.message);
});
socket.on('tavern_notice', function (n) {
if (n && n.message) addSystemLine(n.message);
});
function addSystemLine(text) {
var line = document.createElement('div');
line.className = 'cline csys';
line.textContent = text;
chatLog.appendChild(line);
while (chatLog.childElementCount > 200) chatLog.removeChild(chatLog.firstChild);
chatLog.scrollTop = chatLog.scrollHeight;
}
function addChatLine(name, message) {
var line = document.createElement('div');
line.className = 'cline';
line.innerHTML = '<span class="cname"></span> ';
line.firstChild.textContent = name || '???';
line.insertAdjacentHTML('beforeend', message); // server-escaped
chatLog.appendChild(line);
while (chatLog.childElementCount > 200) chatLog.removeChild(chatLog.firstChild);
chatLog.scrollTop = chatLog.scrollHeight;
}
chatForm.addEventListener('submit', function (e) {
e.preventDefault();
var text = chatInput.value;
if (text && text.trim()) socket.emit('tavern_chat', { text: text });
chatInput.value = '';
});
// ---- Input -------------------------------------------------------------------
var KEYS = {
ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right',
w: 'up', s: 'down', a: 'left', d: 'right', W: 'up', S: 'down', A: 'left', D: 'right'
};
window.addEventListener('keydown', function (e) {
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
var dir = KEYS[e.key];
if (!dir || !state.you) return;
e.preventDefault();
socket.emit('tavern_move', { dir: dir });
});
setStatus('Connecting…');
socket.on('connect', function () {
socket.emit('register_client', { clientId: socket.id, userAgent: navigator.userAgent });
socket.emit('identity:get');
setStatus('Connected. Choose a name and enter.');
});
socket.on('disconnect', function () { setStatus('Disconnected.'); });
})();
</script>
</body>
</html>