Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 | 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 73x 73x 15523x 15523x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1034x 1034x 1034x 1034x 73x 73x 614654x 614654x 614654x 614654x 614654x 614654x 614654x 614654x 73x 73x 73x 73x 82545x 82545x 82545x 82545x 73x 73x 11434x 11434x 11434x 73x 73x 8249x 8249x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1005836x 1005836x 1005836x 1005836x 73x 73x 1005836x 1005836x 960568x 960568x 1005836x 73x 965486x 965486x 965486x 965486x 965486x 965486x 965486x 73x 73x 73x 73x 73x 73x 73x 73x 144x 144x 144x 144x 144x 144x 1152x 1152x 1152x 144x 144x 144x 144x 144x 144x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1003894x 1003894x 1003894x 1003894x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 2237x 2237x 2237x 2237x 2237x 2237x 73x 73x 73x 73x 73x 73x 907352x 907352x 907352x 907352x 907352x 907352x 907352x 907352x 907352x 907352x 907352x 907352x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 50017x 50017x 50017x 50017x 50017x 50017x 50017x 73x 73x 73x 73x 40350x 40350x 40350x 40350x 40350x 73x 73x 73x 73x 73x 73x 73x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 53x 53x 158x 158x 158x 158x 13x 13x 13x 13x 158x 158x 158x 158x 73x 73x 73x 73x 73x 73x 73x 2x 2x 2x 2x 2x 2x 5x 5x 2x 2x 73x 73x 73x 73x 73x 73x 73x 5494x 5494x 5494x 46367x 46367x 5494x 5494x 5494x 5494x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 891x 891x 891x 891x 891x 891x 417x 887x 474x 474x 891x 891x 891x 891x 73x 73x 73x 73x 73x 73x 1574x 1574x 1574x 1574x 1574x 1574x 1574x 1574x 1574x 1574x 1574x 1574x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x | // rng.js -- Random number generation
// Faithful port of rnd.c from the C source.
// Uses ISAAC64 PRNG for exact C compatibility.
// C ref: rnd.c, isaac64.c
import { game } from './gstate.js';
import { isaac64_init, isaac64_next_uint64, isaac64_peek_uint64 } from './isaac64.js';
import { getEnv, getEnvObject, envFlag } from './runtime_env.js';
// CORE ISAAC64 context (C rn2)
// DISP ISAAC64 context (C rn2_on_display_rng)
// LUA ISAAC64 context (Lua nh.random-driven logic)
const CORE = 0;
const DISP = 1;
const LUA = 2;
// C ref: rnl() accesses the global Luck macro. In JS, we use a lazy accessor
// to avoid circular imports (rng.js is imported very early in the module graph).
export function setRnlPlayerAccessor(fn) { game.rnlPlayerAccessor = fn; }
// --- PRNG call logging ---
// When enabled, every rn2/rnd/rnl/d call is logged in the same format
// as the C PRNG logger (003-prng-logging patch). Enable with enableRngLog(),
// retrieve with getRngLog(), disable with disableRngLog().
//
// Caller context propagation (withTags=true):
// Like C's improved 003 patch, wrapper functions (rnz, rne, rnl, rn1)
// capture the caller's identity once on entry. Internal rn2/rnd calls
// inherit that context rather than showing "rnz" or "rne" as the caller.
// Context is cleared when the outermost RNG function returns.
// null = disabled, Array = enabled
// when true, log includes caller info
// when true, include parent/grandparent in tag
// when true, add caller tags to ^event log entries
// current caller annotation (propagated through wrappers)
// nesting depth for context propagation
// explicit caller tag override for hotspot paths
const rngTagCache = new Map();
const rngEventTagCache = new Map();
const rngDispTagCache = new Map();
const cosmicOwnerStack = [];
function cosmicDisplayEnabled() {
const env = getEnvObject();
return !!(game.rngLog && env?.WEBHACK_COSMIC_DISPLAY_LOGS === '1');
}
function cosmicCurrentOwner() {
return cosmicOwnerStack.length > 0
? cosmicOwnerStack[cosmicOwnerStack.length - 1]
: null;
}
export function cosmic_display_log_enabled() {
return cosmicDisplayEnabled();
}
export function cosmic_display_push_owner(owner) {
if (!cosmicDisplayEnabled()) return;
const parent = cosmicCurrentOwner();
cosmicOwnerStack.push(owner);
pushRngLogEntry(`^disp_owner_begin[owner=${owner} depth=${cosmicOwnerStack.length}${parent ? ` parent=${parent}` : ''}]`);
}
export function cosmic_display_pop_owner(owner) {
if (!cosmicDisplayEnabled()) return;
const current = cosmicCurrentOwner();
pushRngLogEntry(`^disp_owner_end[owner=${owner} depth=${cosmicOwnerStack.length}${current ? ` current=${current}` : ''}]`);
if (cosmicOwnerStack.length > 0) cosmicOwnerStack.pop();
}
export function cosmic_display_set_cell(x, y) {
game.cosmicCell = { x, y };
}
export function cosmic_display_clear_cell() {
game.cosmicCell = null;
}
export function cosmic_display_set_newsym_branch(branch) {
game.cosmicNewsymBranch = branch;
}
export function cosmic_display_clear_newsym_branch() {
game.cosmicNewsymBranch = null;
}
export function cosmic_display_set_maploc_branch(branch) {
game.cosmicMaplocBranch = branch;
}
export function cosmic_display_clear_maploc_branch() {
game.cosmicMaplocBranch = null;
}
export function cosmic_display_prepare_rng_kind(kind) {
game.cosmicRngKind = kind;
}
export function cosmic_display_log_newsym(x, y, branch, cansee) {
if (!cosmicDisplayEnabled()) return;
cosmic_display_set_cell(x, y);
cosmic_display_set_newsym_branch(branch);
pushRngLogEntry(`^disp_newsym[owner=${cosmicCurrentOwner() || '?'} x=${x} y=${y} cansee=${cansee ? 1 : 0} branch=${branch}]`);
}
export function cosmic_display_log_maploc(x, y, branch, show) {
if (!cosmicDisplayEnabled()) return;
cosmic_display_set_cell(x, y);
cosmic_display_set_maploc_branch(branch);
pushRngLogEntry(`^disp_maploc[owner=${cosmicCurrentOwner() || '?'} x=${x} y=${y} show=${show ? 1 : 0} branch=${branch}]`);
}
export function enableRngLog(withTags = true) {
const tagsPref = getEnv('RNG_LOG_TAGS');
if (tagsPref === '0') withTags = false;
else if (tagsPref === '1') withTags = true;
const parentPref = getEnv('RNG_LOG_PARENT');
const eventTagPref = getEnv('RNG_LOG_EVENT_TAGS');
game.rngLog = [];
game.rngCallCount = 0;
animFrameId = 0;
game.rngLogWithTags = withTags;
// Default-on parent context whenever caller tags are enabled; opt out with RNG_LOG_PARENT=0.
game.rngLogWithParent = !!withTags && parentPref !== '0';
// Event caller tags are lower-value and high-overhead in monster-heavy replays.
// Keep disabled by default; opt in with RNG_LOG_EVENT_TAGS=1.
game.rngLogEventTags = !!withTags && eventTagPref === '1';
game.rngCallerTag = null;
game.rngDepth = 0;
rngTagCache.clear();
rngEventTagCache.clear();
rngDispTagCache.clear();
}
export function getRngLog() {
return game.rngLog;
}
// Midlog enter/exit with RNG call count range tracking (matches C's midlog system)
const midlogStack = [];
export function midlogEnter(fn) {
midlogStack.push(game.rngCallCount);
pushRngLogEntry(`>${fn}`);
}
export function midlogExitInt(fn, result) {
const entry = midlogStack.pop() || 0;
pushRngLogEntry(`<${fn}=${result} #${entry + 1}-${game.rngCallCount}`);
return result;
}
export function midlogExitVoid(fn) {
const entry = midlogStack.pop() || 0;
pushRngLogEntry(`<${fn} #${entry + 1}-${game.rngCallCount}`);
}
export function midlogExitPtr(fn, result) {
const entry = midlogStack.pop() || 0;
pushRngLogEntry(`<${fn} #${entry + 1}-${game.rngCallCount}`);
return result;
}
// Animation-frame counter — matches C's nomux_anim_id. Bumped by
// pushAnimFrameEvent() on every animation-delay boundary so the event
// marker and the animation-frames appendix can be cross-referenced by id.
let animFrameId = 0;
export function resetAnimFrameId() { animFrameId = 0; }
export function pushAnimFrameEvent() {
animFrameId++;
pushRngLogEntry(`^anim_frame[id=${animFrameId}]`);
return animFrameId;
}
export function pushRngLogEntry(entry) {
if (!game.rngLog) return;
if (typeof entry !== 'string' || entry.length === 0) return;
// For event (^) and midlog (>/<) entries, append caller context via stack trace.
// Midlog caller tracing is gated by WEBHACK_MIDLOG_CALLERS (slow — debug only).
const traceMidlog = (entry[0] === '>' || entry[0] === '<') && envFlag('WEBHACK_MIDLOG_CALLERS');
if ((game.rngLogWithTags && game.rngLogEventTags && entry[0] === '^') || traceMidlog) {
const holder = {};
const prevLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 5;
Error.captureStackTrace(holder, pushRngLogEntry);
const stack = holder.stack || '';
Error.stackTraceLimit = prevLimit;
const lines = stack.split('\n');
const callerLine = lines[1] || '';
const parentLine = lines[2] || '';
const cacheKey = `${callerLine}\n${parentLine}`;
let callers = rngEventTagCache.get(cacheKey);
if (callers === undefined) {
const callerTag = parseStackFrameTag(callerLine);
const parentTag = parseStackFrameTag(parentLine);
callers = callerTag && parentTag
? `${callerTag} <= ${parentTag}`
: (callerTag || parentTag || null);
rngEventTagCache.set(cacheKey, callers);
}
if (callers) {
game.rngLog.push(`${entry} @ ${callers}`);
return;
}
}
game.rngLog.push(entry);
}
// Monster event formatting helper.
// Always include per-instance id when available to disambiguate same-species mons.
export function formatMonsterEventRef(mon, mnum = mon?.mnum, x = mon?.mx, y = mon?.my) {
const mId = mon?.m_id;
const idPart = Number.isInteger(mId) ? `#${mId}` : '';
return `${mnum}${idPart}@${x},${y}`;
}
export function pushCtxMoveLog(site, value) {
const umv = game.u?.umovement ?? 0;
pushRngLogEntry(`^ctx_move[${site}=${value} umv=${umv}]`);
}
export function pushMultiLog(site, value) {
pushRngLogEntry(`^multi[${site}=${value}]`);
}
export function disableRngLog() {
game.rngLog = null;
game.rngLogWithParent = false;
game.rngLogEventTags = false;
game.rngCallerTag = null;
game.rngDepth = 0;
game.rngTagOverride = null;
rngTagCache.clear();
rngEventTagCache.clear();
rngDispTagCache.clear();
cosmicOwnerStack.length = 0;
game.cosmicCell = null;
game.cosmicNewsymBranch = null;
game.cosmicMaplocBranch = null;
game.cosmicRngKind = null;
}
// C ref: rnd.c:37 rng_log_init()
export function rng_log_init(withTags = true) {
enableRngLog(withTags);
}
// C ref: rnd.c:48 rng_log_set_caller()
export function rng_log_set_caller(tag) {
game.rngTagOverride = (typeof tag === 'string' && tag.length > 0) ? tag : null;
}
// C ref: rnd.c:56 rng_log_get_call_count()
export function rng_log_get_call_count() {
return getRngCallCount();
}
// C ref: rnd.c:62 rng_log_write()
export function rng_log_write(entry) {
pushRngLogEntry(String(entry ?? ''));
}
// C ref: rnd.c:103 midlog_enter()
export function midlog_enter(_name, _file, _line, _func) {
return;
}
// C ref: rnd.c:114 midlog_exit_int()
export function midlog_exit_int(_name, _result, _file, _line, _func) {
return;
}
// C ref: rnd.c:127 midlog_exit_void()
export function midlog_exit_void(_name, _file, _line, _func) {
return;
}
// C ref: rnd.c:140 midlog_exit_ptr()
export function midlog_exit_ptr(_name, _result, _file, _line, _func) {
return;
}
// Hot-path helper: avoid per-call stack parsing by supplying explicit tag context.
export async function withRngTag(tag, fn) {
const prev = game.rngTagOverride;
game.rngTagOverride = (typeof tag === 'string' && tag.length > 0) ? tag : null;
try {
const out = await fn();
if (out && typeof out.then === 'function') {
return out.finally(() => {
game.rngTagOverride = prev;
});
}
game.rngTagOverride = prev;
return out;
} catch (err) {
game.rngTagOverride = prev;
throw err;
}
}
function parseStackFrameTag(line) {
if (!line || typeof line !== 'string') return null;
const at = line.indexOf('at ');
if (at < 0) return null;
const frame = line.slice(at + 3).trim();
if (!frame) return null;
let fn = null;
let loc = frame;
const lparen = frame.indexOf(' (');
if (lparen > 0 && frame.endsWith(')')) {
fn = frame.slice(0, lparen).trim() || null;
loc = frame.slice(lparen + 2, -1);
}
const slash = loc.lastIndexOf('/');
const tail = slash >= 0 ? loc.slice(slash + 1) : loc;
const colon2 = tail.lastIndexOf(':');
if (colon2 <= 0) return null;
const colon1 = tail.lastIndexOf(':', colon2 - 1);
if (colon1 <= 0) return null;
const file = tail.slice(0, colon1);
const lineNo = tail.slice(colon1 + 1, colon2);
if (!file || !lineNo) return null;
return fn ? `${fn}(${file}:${lineNo})` : `${file}:${lineNo}`;
}
// Capture caller context on first entry into an RNG function.
// Wrapper functions (rnz, rne, rnl, rn1) and primitives (rn2, rnd)
// all call this. Only the outermost call (depth 0→1) captures the
// stack trace; inner calls inherit the existing tag.
function enterRng() {
game.rngDepth++;
if (game.rngDepth === 1 && game.rngLogWithTags) {
if (game.rngTagOverride) {
game.rngCallerTag = game.rngTagOverride;
return;
}
const holder = {};
const prevLimit = Error.stackTraceLimit;
Error.stackTraceLimit = game.rngLogWithParent ? 6 : 4;
Error.captureStackTrace(holder, enterRng);
const stack = holder.stack || '';
Error.stackTraceLimit = prevLimit;
const lines = stack.split('\n');
// [0]=Error, [1]=enterRng, [2]=rn2/rnz/etc, [3]=caller
const parentLine = lines[4] || '';
const grandLine = lines[5] || '';
const callerLine = lines[3] || '';
const cacheKey = game.rngLogWithParent
? `${callerLine}\n${parentLine}\n${grandLine}`
: callerLine;
if (rngTagCache.has(cacheKey)) {
game.rngCallerTag = rngTagCache.get(cacheKey);
return;
}
const callerTag = parseStackFrameTag(callerLine);
if (!callerTag) {
game.rngCallerTag = null;
rngTagCache.set(cacheKey, null);
return;
}
let fullTag = callerTag;
if (game.rngLogWithParent) {
const parentTag = parseStackFrameTag(parentLine);
if (parentTag) {
fullTag = `${fullTag} <= ${parentTag}`;
const grandTag = parseStackFrameTag(grandLine);
if (grandTag) {
fullTag = `${fullTag} <= ${grandTag}`;
}
}
}
game.rngCallerTag = fullTag;
rngTagCache.set(cacheKey, fullTag);
}
}
// Clear caller context when the outermost RNG function returns.
function exitRng() {
if (--game.rngDepth === 0) {
game.rngCallerTag = null;
}
}
function logRng(func, args, result) {
if (!game.rngLog) return;
game.rngCallCount++;
const tag = game.rngCallerTag ? ` @ ${game.rngCallerTag}` : '';
game.rngLog.push(`${game.rngCallCount} ${func}(${args})=${result}${tag}`);
if (typeof process !== 'undefined' && process.env?.RN2_TRACE) {
const stack = new Error().stack || '';
const caller = stack.split('\n')[3]?.trim() || '';
// eslint-disable-next-line no-console
console.error(`[RN2:${game.rngCallCount}] ${func}(${args})=${result} ${caller}`);
}
}
function cloneIsaacCtx(state) {
if (!state) return null;
return {
a: state.a,
b: state.b,
c: state.c,
n: state.n,
r: state.r.slice(),
m: state.m.slice(),
};
}
// Get the current RNG seed
export function getRngSeed() {
return game.currentSeed;
}
// Initialize the PRNG with a seed (unsigned long, up to 64 bits)
// C ref: rnd.c init_isaac64() -- converts seed to little-endian bytes
export function initRng(seed) {
game.currentSeed = seed;
// Convert seed to BigInt, then to 8 little-endian bytes
// C ref: rnd.c init_isaac64() -- sizeof(unsigned long) = 8 on 64-bit Linux
let s = BigInt(seed) & 0xFFFFFFFFFFFFFFFFn;
const bytes = new Uint8Array(8);
for (let i = 0; i < 8; i++) {
bytes[i] = Number(s & 0xFFn);
s >>= 8n;
}
game.coreCtx = isaac64_init(bytes);
game.dispCtx = isaac64_init(bytes);
game.luaCtx = isaac64_init(bytes);
// Reset log counter on re-init (like C's init_random)
if (game.rngLog) {
game.rngLog.length = 0;
game.rngCallCount = 0;
}
}
// C ref: rnd.c:178 whichrng()
export function whichrng(fn) {
if (fn === rn2) return CORE;
if (fn === rn2_on_display_rng) return DISP;
if (fn === rn2_on_lua_rng) return LUA;
return -1;
}
// C ref: rnd.c:189 init_isaac64(seed, fn)
export function init_isaac64(seed, fn = rn2) {
// If contexts are uninitialized, seed both streams first for deterministic startup.
if (!game.coreCtx || !game.dispCtx || !game.luaCtx) {
initRng(seed);
return;
}
const s = BigInt(seed) & 0xFFFFFFFFFFFFFFFFn;
const bytes = new Uint8Array(8);
let tmp = s;
for (let i = 0; i < 8; i++) {
bytes[i] = Number(tmp & 0xFFn);
tmp >>= 8n;
}
const which = whichrng(fn);
if (which === DISP) {
game.dispCtx = isaac64_init(bytes);
} else if (which === LUA) {
game.luaCtx = isaac64_init(bytes);
} else {
game.coreCtx = isaac64_init(bytes);
}
}
// C ref: rnd.c:418 set_random(seed, fn)
export function set_random(seed, fn = rn2) {
init_isaac64(seed, fn);
}
function sys_random_seed() {
const forced = getEnv('NETHACK_SEED');
if (forced != null && forced !== '') {
const parsed = Number.parseInt(forced, 10);
if (Number.isFinite(parsed)) return parsed >>> 0;
}
return (Date.now() >>> 0);
}
// C ref: rnd.c:465 init_random(fn)
export function init_random(fn = rn2) {
set_random(sys_random_seed(), fn);
}
// C ref: rnd.c:472 reseed_random(fn)
export function reseed_random(fn = rn2) {
// JS/browser runtime does not model has_strong_rngseed; keep deterministic
// behavior by sharing init path.
init_random(fn);
}
// Raw 64-bit value, modulo x -- matches C's RND(x) macro
// C ref: rnd.c RND() = isaac64_next_uint64() % x
function RND(x) {
const raw = isaac64_next_uint64(game.coreCtx);
return Number(raw % BigInt(x));
}
// Raw rn2 that consumes PRNG without logging.
// Used when manually emitting log entries to match C's composite
// function logging (rne/rnz emit single entries, internal rn2 suppressed).
export function rn2_raw(x) {
if (x <= 0) return 0;
return RND(x);
}
// Peek at the next core PRNG value modulo x, without consuming it.
// Mixes in the turn count so the result changes every turn even if
// no other RNG calls advance the state between turns.
// Used for mail daemon delivery probability — deterministic but non-perturbing.
export function silent_rn2(x) {
if (x <= 0) return 0;
const raw = isaac64_peek_uint64(game.coreCtx);
const turns = BigInt(game.moves || 0);
const mixed = (raw ^ (turns * 0x9E3779B97F4A7C13n)) & 0xFFFFFFFFFFFFFFFFn;
return Number(mixed % BigInt(x));
}
function DRND(x) {
const raw = isaac64_next_uint64(game.dispCtx);
return Number(raw % BigInt(x));
}
function LRND(x) {
const raw = isaac64_next_uint64(game.luaCtx);
return Number(raw % BigInt(x));
}
// 0 <= rn2(x) < x
// C ref: rnd.c:93-107
export function rn2(x) {
enterRng();
if (!Number.isFinite(x) || !Number.isInteger(x)) {
const stack = new Error().stack || '';
exitRng();
throw new Error(`rn2 received invalid bound: ${x}\n${stack}`);
}
if (x <= 0) { exitRng(); return 0; }
// Debug Lua RNG calls
if (envFlag('DEBUG_LUA_RNG') && x >= 1000 && x <= 1040) {
const stack = new Error().stack;
console.log(`\n=== rn2(${x}) called (Lua RNG) ===`);
console.log(`Stack:\n${stack}`);
}
const result = RND(x);
logRng('rn2', x, result);
exitRng();
return result;
}
// 0 <= rn2_on_display_rng(x) < x
// C ref: rnd.c rn2_on_display_rng() -- separate stream for display-only randomness.
export function rn2_on_display_rng(x) {
if (x <= 0) return 0;
const result = DRND(x);
const processEnv = getEnvObject();
const dispLogEnabled = processEnv?.RNG_LOG_DISP === '1';
if (game.rngLog && dispLogEnabled) {
let tag = game.rngCallerTag ? ` @ ${game.rngCallerTag}` : '';
if (!tag && game.rngLogWithTags && processEnv?.RNG_LOG_DISP_CALLERS === '1') {
const holder = {};
const prevLimit = Error.stackTraceLimit;
Error.stackTraceLimit = game.rngLogWithParent ? 6 : 4;
Error.captureStackTrace(holder, rn2_on_display_rng);
const stack = holder.stack || '';
Error.stackTraceLimit = prevLimit;
const lines = stack.split('\n');
const callerLine = lines[1] || '';
const parentLine = lines[2] || '';
const grandLine = lines[3] || '';
const cacheKey = game.rngLogWithParent
? `${callerLine}\n${parentLine}\n${grandLine}`
: callerLine;
let callerTag = rngDispTagCache.get(cacheKey);
if (callerTag === undefined) {
const baseTag = parseStackFrameTag(callerLine);
if (baseTag && game.rngLogWithParent) {
const parentTag = parseStackFrameTag(parentLine);
if (parentTag) {
callerTag = `${baseTag} <= ${parentTag}`;
const grandTag = parseStackFrameTag(grandLine);
if (grandTag) callerTag = `${callerTag} <= ${grandTag}`;
} else {
callerTag = baseTag;
}
} else {
callerTag = baseTag || null;
}
rngDispTagCache.set(cacheKey, callerTag);
}
if (callerTag) {
tag = ` @ ${callerTag}`;
}
}
if (processEnv?.WEBHACK_COSMIC_DISPLAY_LOGS === '1') {
const xCoord = game.cosmicCell?.x ?? -1;
const yCoord = game.cosmicCell?.y ?? -1;
game.rngLog.push(`~drn2_disp[n=${x} idx=${result} owner=${cosmicCurrentOwner() || '?'} kind=${game.cosmicRngKind || '?'} x=${xCoord} y=${yCoord}${game.cosmicNewsymBranch ? ` newsym=${game.cosmicNewsymBranch}` : ''}${game.cosmicMaplocBranch ? ` maploc=${game.cosmicMaplocBranch}` : ''}]${tag}`);
} else {
game.rngLog.push(`~drn2(${x})=${result}${tag}`);
}
}
game.cosmicRngKind = null;
return result;
}
// 0 <= rn2_on_lua_rng(x) < x
// Used for Lua-side randomness so it never perturbs core gameplay RNG order.
export function rn2_on_lua_rng(x) {
if (x <= 0) return 0;
return LRND(x);
}
// 1 <= rnd_on_display_rng(x) <= x
// C ref: rnd.c drnd() helper semantics.
export function rnd_on_display_rng(x) {
if (x <= 0) return 1;
return rn2_on_display_rng(x) + 1;
}
// 1 <= rnd(x) <= x
// C ref: rnd.c:153-165
export function rnd(x) {
enterRng();
if (x <= 0) { exitRng(); return 1; }
const result = RND(x) + 1;
logRng('rnd', x, result);
exitRng();
return result;
}
// rn1(x, y) = rn2(x) + y -- random in [y, y+x-1]
// C ref: hack.h macro -- NOT logged separately (rn2 inside is logged)
export function rn1(x, y) {
enterRng();
const result = rn2(x) + y;
exitRng();
return result;
}
// rnl(x) - luck-adjusted random, good luck approaches 0
// C ref: rnd.c:109-151
// C's rnl() uses the global Luck macro (u.uluck + u.moreluck). When called
// without an explicit luck argument, auto-read from the global game state
// so callers don't need to pass it (matching C's implicit global access).
export function rnl(x, luck) {
enterRng();
if (x <= 0) { exitRng(); return 0; }
// Auto-detect luck from global game state if not explicitly provided.
// C ref: youprop.h — #define Luck (u.uluck + u.moreluck)
let adjustment;
if (luck !== undefined) {
adjustment = luck;
} else {
const player = game.rnlPlayerAccessor?.();
adjustment = player
? ((player.uluck ?? player.luck ?? 0) + (player.moreluck ?? 0))
: 0;
}
if (x <= 15) {
adjustment = Math.floor((Math.abs(adjustment) + 1) / 3) * Math.sign(adjustment);
}
let i = RND(x);
// C rnl() consumes this gate via rn2(), which the C harness logs as
// a separate rn2 entry. Use rn2() here to match.
if (adjustment && rn2(37 + Math.abs(adjustment))) {
i -= adjustment;
if (i < 0) i = 0;
else if (i >= x) i = x - 1;
}
logRng('rnl', x, i);
exitRng();
return i;
}
// d(n, x) = NdX dice roll = n + sum of n random calls
// When called from Lua code (themerms.js), matches Lua's d() implementation
// which uses math.random() that is replaced with nh.random()
// C ref: dat/nhlib.lua d() uses math.random(1, faces), replaced with nh.random(1, faces)
// C ref: nhlua.c nhl_random(1, faces) = 1 + rn2(faces), logs rn2() call
export function lua_d(n, x) {
// Lua's d(): for i=1,dice do sum = sum + math.random(1, faces) end
// math.random is replaced with nh.random in C
// nh.random(1, x) = 1 + rn2(x), logs rn2(x)
// Match C's logging by calling rn2(x) + 1 directly
let tmp = 0;
for (let i = 0; i < n; i++) {
tmp += 1 + rn2(x); // Match nh.random(1, x) = 1 + rn2(x)
}
return tmp;
}
// C ref: rnd.c d() — C-style d(n,x) that uses RND directly.
// Unlike Lua's d() which calls rn2() per die (logged individually),
// C's rnd.c d() calls RND() per die (not logged individually) and logs
// the result as a composite d(n,x)=result entry.
// Use this for C code paths (e.g. newmonhp), not for Lua code paths.
export function c_d(n, x) {
enterRng();
let tmp = n;
for (let i = 0; i < n; i++) {
tmp += RND(x);
}
logRng('d', `${n},${x}`, tmp);
exitRng();
return tmp;
}
// Advance ISAAC state without emitting a logged RNG entry.
// Used only for narrow parity fixes when C consumes raw PRNG output
// through non-logged paths between logged rn2/rnd calls.
export function advanceRngRaw(count = 1) {
if (!game.coreCtx) return;
const n = Math.max(0, Number.isInteger(count) ? count : 0);
const processEnv = getEnvObject();
const rawAdvanceLogEnabled = processEnv?.WEBHACK_LOG_RAW_ADVANCES === '1';
if (game.rngLog && rawAdvanceLogEnabled) {
let tag = '';
if (game.rngLogWithTags) {
const stack = new Error().stack;
const lines = stack.split('\n');
const callerLine = lines[2] || '';
const m = callerLine.match(/at (?:(\S+) \()?.*?([^/\s]+\.js):(\d+)/);
if (m) {
tag = ` @ ${m[1] ? `${m[1]}(${m[2]}:${m[3]})` : `${m[2]}:${m[3]}`}`;
}
}
game.rngLog.push(`~advanceRngRaw(${n})${tag}`);
}
for (let i = 0; i < n; i++) {
isaac64_next_uint64(game.coreCtx);
}
}
// C ref: rnd.c rnz() -- randomized scaling
// C logs rnz summary via explicit rng_log_write; internal rn2 calls are
// suppressed by RNGLOG_IN_RND_C. Internal rne(4) IS logged (explicit log).
export function rnz(i) {
enterRng();
let x = i;
let tmp = 1000;
tmp += rn2(1000);
tmp *= rne(4);
if (rn2(2)) {
x = Math.trunc(x * tmp / 1000);
} else {
x = Math.trunc(x * 1000 / tmp);
}
logRng('rnz', i, x);
exitRng();
return x;
}
// C ref: rnd.c rne() -- 1 <= rne(x) <= max(u.ulevel/3, 5)
// During mklev at level 1, u.ulevel = 1, so utmp = 5
// C logs rne summary via explicit rng_log_write; internal rn2 calls are
// suppressed by RNGLOG_IN_RND_C. We match this with rngDepth check in rn2.
export function rne(x) {
enterRng();
// C ref: rnd.c — utmp = max(u.ulevel/3, 5) when ulevel < 15 → 5;
// ulevel >= 15 → ulevel/3. Read from game state when available.
const ulevel = game.rnlPlayerAccessor?.()?.ulevel || 1;
const utmp = ulevel < 15 ? 5 : Math.trunc(ulevel / 3);
let tmp = 1;
while (tmp < utmp && !rn2(x))
tmp++;
logRng('rne', x, tmp);
exitRng();
return tmp;
}
// Advance the PRNG by n steps without logging.
// Used to skip past C startup calls (o_init, u_init, etc.) that JS
// doesn't implement yet, aligning the PRNG state for level generation.
export function skipRng(n) {
for (let i = 0; i < n; i++) {
isaac64_next_uint64(game.coreCtx);
}
}
// Return the raw ISAAC64 context (for save/restore)
export function getRngState() {
return cloneIsaacCtx(game.coreCtx);
}
// Restore ISAAC64 context (for save/restore)
export function setRngState(savedCtx) {
if (!savedCtx) return;
// Backward-compatible behavior: setting core state also syncs DISP
// when no explicit DISP state has been provided.
game.coreCtx = cloneIsaacCtx(savedCtx);
game.dispCtx = cloneIsaacCtx(savedCtx);
}
// Return DISP RNG state (for display-focused diagnostics/save parity)
export function getDispRngState() {
return cloneIsaacCtx(game.dispCtx);
}
// Restore DISP RNG state (for display-focused diagnostics/save parity)
export function setDispRngState(savedCtx) {
if (!savedCtx) return;
game.dispCtx = cloneIsaacCtx(savedCtx);
}
// Get the RNG call count (for save/restore)
export function getRngCallCount() {
return game.rngCallCount;
}
// Set the RNG call count (for save/restore)
export function setRngCallCount(count) {
game.rngCallCount = count;
}
// cf. rnd.c:482 — randomize the given array of numbers in-place (Fisher-Yates)
export function shuffle_int_array(indices) {
for (let i = indices.length - 1; i > 0; i--) {
const iswap = rn2(i + 1);
if (iswap === i) continue;
const temp = indices[i];
indices[i] = indices[iswap];
indices[iswap] = temp;
}
}
// Module-level initRng removed — now in init_rng_globals after game exists.
export function init_rng_globals() {
game.coreCtx = null;
game.dispCtx = null;
game.luaCtx = null;
game.rnlPlayerAccessor = null;
game.rngLog = null;
game.rngCallCount = 0;
game.rngLogWithTags = false;
game.rngLogWithParent = false;
game.rngLogEventTags = false;
game.rngCallerTag = null;
game.rngDepth = 0;
game.rngTagOverride = null;
game.cosmicCell = null;
game.cosmicNewsymBranch = null;
game.cosmicMaplocBranch = null;
game.cosmicRngKind = null;
// Clear const-but-mutable caches
rngTagCache.clear();
rngEventTagCache.clear();
rngDispTagCache.clear();
cosmicOwnerStack.length = 0;
midlogStack.length = 0;
// Default PRNG — overwritten by initRng(seed) in nhGame.start()
initRng(Math.floor(Math.random() * 0xFFFFFFFF));
game.currentSeed = 0;
}
|