All files / js region.js

53.04% Statements 523/986
58.18% Branches 64/110
53.33% Functions 24/45
53.04% Lines 523/986

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 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 98773x 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 86x 86x 86x 2129x 2129x   86x 73x 73x                                                   73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 222x     78x   39x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 827717x 827717x 827717x 827717x 827717x 73x       73x 73x 73x 73x 65202x 65202x 73x 73x 73x 73x 65010x 65010x 192x 192x 192x   65010x 73x 73x 73x 73x 39x 39x 39x   39x 39x 39x 39x 39x 39x                     39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 73x 73x 73x 73x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 73x 73x 73x 73x 39x         39x 39x 39x 39x 39x 73x 73x 73x 73x 1x 1x 1x 1x 1x 1x 1x 73x 73x 73x 73x 2838x 2838x 2798x 2836x 2838x 73x 73x 73x 73x 2x 2x 2x 73x 73x 73x 73x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 73x 73x 73x 73x 2x 2x 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 73x 73x 73x 73x           73x 73x 73x 73x 6097x 6097x 54x 54x 54x 54x 54x 54x 396x 89x 2x 2x 2x 2x 2x 89x 54x 54x 396x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 86x 86x 86x 86x             86x 87x 87x 54x 404x           404x           6097x 73x 73x 73x 73x                                                                                               73x 73x 73x 73x 8762x 8762x 8762x 8762x 8762x 933x 933x 933x 933x   933x 933x       933x 8762x 8762x 8762x 933x 933x 933x 933x 1x 1x 1x 1x 933x 8762x 8762x 8762x 933x 933x 933x 933x         933x 8762x 8762x 8762x 73x 73x 73x 73x                 73x 73x 73x 73x                       73x 73x 73x 73x       73x 73x 73x 73x                 73x 73x 73x 73x 812724x 812724x 63061x 63061x 63061x 63061x 63061x 812575x 812724x 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 78x 78x 78x 78x 135x 135x 78x 78x 73x 73x 73x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x       39x 73x 73x 73x 73x 73x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x       39x 39x 39x 39x                                                                               39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 73x 73x 73x 73x 2x 2x 2x 2x 2x           2x 2x 2x 2x 2x 2x 2x 2x 2x 2x               2x 2x 2x 2x 2x 2x 2x 73x 73x 73x 73x 73x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x                                                                                                           86x 73x 73x 73x 73x                           73x 73x 73x 73x 15x 15x 15x 15x                       15x 15x 73x 73x 73x 73x                                                              
// region.js — Region effects (port of region.c)
// C ref: region.c — 1408 lines
//
// Regions are area effects (gas clouds, force fields) that persist
// across turns and affect monsters/hero that enter them.
 
import { game } from './gstate.js';
import { c_d, rn2, rnd, rn1 } from './rng.js';
import { You, You_see, Your, impossible, pline, pline1, pline_The } from './pline.js';
import { cansee } from './vision.js';
import { isok, COLNO, ROWNO, MONST_INC, M_POISONGAS_OK, u_at,
         PLNMSG_ENVELOPED_IN_GAS, ACCESSIBLE, KILLED_BY_AN,
         FM_FMON, M_SEEN_POISON, TELEDS_NO_FLAGS } from './const.js';
import { m_at, levl } from './map_access.js';
import { block_point, canseemon, cmap_to_glyph, does_block, newsym, show_glyph, unblock_point } from './display.js';
import { DEADMONSTER, m_monnam, Monnam, setmangry, wake_nearto } from './mon.js';
import { S_poisoncloud, S_cloud } from './symbols.js';
import { AD_RBRE, AT_BREA, mons, PM_FOG_CLOUD, PM_HEZROU, PM_LONG_WORM, PM_VROCK, S_EEL, AD_DRST } from './monsters.js';
import { EYE, LUNG } from './const.js';
import { makeplural } from './objnam.js';
import { body_part } from './polyself.js';
import { attacktype_fordmg, breathless, haseyes, is_silent, is_vampshifter, nonliving, resists_poison } from './mondata.js';
import { monstseesu, monstunseesu } from './mondata.js';
import { Blind, BlindedTimeout, Breathless, Half_gas_damage, Is_waterlevel, Maybe_Half_Phys, Poison_resistance, Underwater } from './macros.js';
import { is_pool, is_lava } from './dbridge.js';
import { plur } from './hacklib.js';
import { losehp, killed, monkilled } from './hack.js';
import { make_blinded } from './potion.js';
import { safe_teleds } from './teleport.js';
import { set_itimeout } from './timeout.js';
import { distu } from './hacklib.js';
// ── Local stubs for deps not yet fully ported ──
// block_point: imported from display.js
// does_block: imported from display.js
// show_glyph: imported from display.js
// cmap_to_glyph: imported from display.js
function find_mid(id, flags) { // TODO: proper implementation
    if (!game.level?.monsters) return null;
    for (const m of game.level.monsters) {
        if (m && m.m_id === id) return m;
    }
    return null;
}
// C ref: mon.c:311 — m_poisongas_ok: is monster OK with poison gas?
// Returns M_POISONGAS_OK(2), M_POISONGAS_MINOR(1), or M_POISONGAS_BAD(0)
function m_poisongas_ok(mtmp) {
    const M_POISONGAS_OK = 2, M_POISONGAS_MINOR = 1, M_POISONGAS_BAD = 0;
    const is_you = (mtmp === game.youmonst);
    // Non-living, non-breathing, immune monsters are not concerned
    if (nonliving(mtmp?.data) || is_vampshifter(mtmp)
        || breathless(mtmp?.data)
        || mtmp?.data === mons[PM_HEZROU] || mtmp?.data === mons[PM_VROCK])
        return M_POISONGAS_OK;
    // Eels in water or water level
    const px = is_you ? (game.u?.ux ?? 0) : (mtmp.mx ?? 0);
    const py = is_you ? (game.u?.uy ?? 0) : (mtmp.my ?? 0);
    if ((mtmp?.data?.mlet === S_EEL || Is_waterlevel(game.u?.uz))
        && is_pool(px, py))
        return M_POISONGAS_OK;
    // Poison gas breath attack
    if (attacktype_fordmg(mtmp?.data, AT_BREA, AD_DRST)
        || attacktype_fordmg(mtmp?.data, AT_BREA, AD_RBRE))
        return M_POISONGAS_OK;
    // Hero-specific checks
    if (is_you && (Breathless() || Underwater()))
        return M_POISONGAS_OK;
    if (is_you ? Poison_resistance() : resists_poison(mtmp))
        return M_POISONGAS_MINOR;
    return M_POISONGAS_BAD;
}
function lookup_id_mapping(oldid, newid_ref) { return false; } // TODO: bones
// pline1 imported from pline.js
// ── Callback indices (match C's callbacks[] array) ──
const NO_CALLBACK = -1;
const INSIDE_GAS_CLOUD = 0;
const EXPIRE_GAS_CLOUD = 1;
 
// ── player_flags bits (from region.h) ──
const REG_HERO_INSIDE = 0x01;
const REG_NOT_HEROS   = 0x02;
 
function hero_inside(r) { return !!(r.player_flags & REG_HERO_INSIDE); }
function heros_fault(r) { return !(r.player_flags & REG_NOT_HEROS); }
function set_hero_inside(r) { r.player_flags |= REG_HERO_INSIDE; }
function clear_hero_inside(r) { r.player_flags &= ~REG_HERO_INSIDE; }
function set_heros_fault(r) { r.player_flags &= ~REG_NOT_HEROS; }
function clear_heros_fault(r) { r.player_flags |= REG_NOT_HEROS; }
 
// ── Callback dispatch ──
const callbacks = [
    inside_gas_cloud,  // INSIDE_GAS_CLOUD = 0
    expire_gas_cloud,  // EXPIRE_GAS_CLOUD = 1
];
 
// ── Region list accessors ──
// C uses gr.regions[] with svn.n_regions count.
// JS uses game.level.regions[] with .length as count.
function get_regions() {
    if (!game.level) return [];
    if (!game.level.regions) game.level.regions = [];
    return game.level.regions;
}
 
function n_regions() {
    return get_regions().length;
}
 
// ── inside_rect: is point inside rectangle? ──
// C ref: region.c:53
export function inside_rect(r, x, y) {
    return x >= r.lx && x <= r.hx && y >= r.ly && y <= r.hy;
}
 
// ── inside_region: check if point is inside a region ──
// C ref: region.c:62
export function inside_region(reg, x, y) {
    if (!reg || !inside_rect(reg.bounding_box, x, y))
        return false;
    for (let i = 0; i < reg.nrects; i++)
        if (inside_rect(reg.rects[i], x, y))
            return true;
    return false;
}
 
// ── create_region: create but do not activate a region ──
// C ref: region.c:79
export function create_region(rects, nrect) {
    const reg = {};
    // Determine bounding box
    if (nrect > 0) {
        reg.bounding_box = { ...rects[0] };
    } else {
        reg.bounding_box = { lx: COLNO, ly: ROWNO, hx: 0, hy: 0 };
    }
    reg.nrects = nrect;
    reg.rects = [];
    for (let i = 0; i < nrect; i++) {
        if (rects[i].lx < reg.bounding_box.lx)
            reg.bounding_box.lx = rects[i].lx;
        if (rects[i].ly < reg.bounding_box.ly)
            reg.bounding_box.ly = rects[i].ly;
        if (rects[i].hx > reg.bounding_box.hx)
            reg.bounding_box.hx = rects[i].hx;
        if (rects[i].hy > reg.bounding_box.hy)
            reg.bounding_box.hy = rects[i].hy;
        reg.rects[i] = { ...rects[i] };
    }
    reg.ttl = -1;           // Defaults
    reg.attach_2_u = false;
    reg.attach_2_m = 0;
    reg.enter_msg = null;
    reg.leave_msg = null;
    reg.expire_f = NO_CALLBACK;
    reg.enter_f = NO_CALLBACK;
    reg.can_enter_f = NO_CALLBACK;
    reg.leave_f = NO_CALLBACK;
    reg.can_leave_f = NO_CALLBACK;
    reg.inside_f = NO_CALLBACK;
    reg.player_flags = 0;
    clear_hero_inside(reg);
    clear_heros_fault(reg);
    reg.n_monst = 0;
    reg.max_monst = 0;
    reg.monsters = [];
    reg.arg = { a_int: 0 }; // cg.zeroany
    reg.visible = false;
    reg.glyph = cmap_to_glyph(0); // canonical S_stone glyph (no visible region)
    return reg;
}
 
// ── add_rect_to_reg: add rectangle to region ──
// C ref: region.c:133
export function add_rect_to_reg(reg, rect) {
    reg.rects.push({ ...rect });
    reg.nrects++;
    // Update bounding box if needed
    if (reg.bounding_box.lx > rect.lx)
        reg.bounding_box.lx = rect.lx;
    if (reg.bounding_box.ly > rect.ly)
        reg.bounding_box.ly = rect.ly;
    if (reg.bounding_box.hx < rect.hx)
        reg.bounding_box.hx = rect.hx;
    if (reg.bounding_box.hy < rect.hy)
        reg.bounding_box.hy = rect.hy;
}
 
// ── add_mon_to_reg: add a monster to the region ──
// C ref: region.c:161
export function add_mon_to_reg(reg, mon) {
    if (mon_in_region(reg, mon)) {
        if (mon.data !== mons[PM_LONG_WORM])
            impossible(`add_mon_to_reg: ${m_monnam(mon)} [#${mon.m_id}] already in region.`);
        return;
    }
    if (reg.max_monst <= reg.n_monst) {
        reg.max_monst += MONST_INC;
    }
    reg.monsters[reg.n_monst++] = mon.m_id;
}
 
// ── remove_mon_from_reg: remove monster from region ──
// C ref: region.c:192
export function remove_mon_from_reg(reg, mon) {
    for (let i = 0; i < reg.n_monst; i++)
        if (reg.monsters[i] === mon.m_id) {
            reg.n_monst--;
            reg.monsters[i] = reg.monsters[reg.n_monst];
            return;
        }
}
 
// ── mon_in_region: check if monster is in region ──
// C ref: region.c:210
export function mon_in_region(reg, mon) {
    for (let i = 0; i < reg.n_monst; i++)
        if (reg.monsters[i] === mon.m_id)
            return true;
    return false;
}
 
// ── free_region: free a region ──
// C ref: region.c:263
export function free_region(reg) {
    // In JS, garbage collection handles memory.
    // Nothing explicit to do, but we keep the function for API parity.
}
 
// ── add_region: add region to the list and activate it ──
// C ref: region.c:284
export function add_region(reg) {
    const regions = get_regions();
    regions.push(reg);
 
    // Check for monsters inside the region
    for (let i = reg.bounding_box.lx; i <= reg.bounding_box.hx; i++)
        for (let j = reg.bounding_box.ly; j <= reg.bounding_box.hy; j++) {
            let is_inside = false;
 
            // Some regions can cross the level boundaries
            if (!isok(i, j))
                continue;
            if (inside_region(reg, i, j)) {
                is_inside = true;
                const mtmp = m_at(i, j);
                if (mtmp) {
                    add_mon_to_reg(reg, mtmp);
                }
            }
            if (reg.visible) {
                if (is_inside)
                    block_point(i, j);
                if (cansee(i, j))
                    newsym(i, j);
            }
        }
    // Check for player now
    if (inside_region(reg, game.u.ux, game.u.uy))
        set_hero_inside(reg);
    else
        clear_hero_inside(reg);
}
 
// ── remove_region: remove region from list and free it ──
// C ref: region.c:344
export function remove_region(reg) {
    const regions = get_regions();
    let i;
    for (i = 0; i < regions.length; i++)
        if (regions[i] === reg)
            break;
    if (i === regions.length)
        return;
 
    // remove region before potential newsym() calls, but don't free it yet
    const last = regions.length - 1;
    if (last !== i)
        regions[i] = regions[last];
    regions.length = last;
 
    // Update screen if necessary
    reg.ttl = -2; // for visible_region_at
    if (reg.visible) {
        let pass;
        const tmp_uinwater = game.u.uinwater;
 
        for (pass = 1; pass <= (Blind() ? 1 : 2); ++pass) {
            game.u.uinwater = (pass === 1) ? 0 : tmp_uinwater;
 
            for (let x = reg.bounding_box.lx; x <= reg.bounding_box.hx; x++)
                for (let y = reg.bounding_box.ly; y <= reg.bounding_box.hy; y++)
                    if (isok(x, y) && inside_region(reg, x, y)) {
                        if (pass === 1) {
                            if (!does_block(x, y, levl(x, y)))
                                unblock_point(x, y);
                        } else { // pass==2
                            if (cansee(x, y))
                                newsym(x, y);
                        }
                    }
        }
        game.u.uinwater = tmp_uinwater;
    }
    free_region(reg);
}
 
// ── clear_regions: remove all regions ──
// C ref: region.c:394
export function clear_regions() {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++)
        free_region(regions[i]);
    if (game.level) game.level.regions = [];
}
 
// ── run_regions: process all active regions every turn ──
// C ref: region.c:414
export async function run_regions() {
    const regions = get_regions();
    if (!regions.length) return;
 
    // reset some messaging variables
    game.gas_cloud_diss_within = false;
    game.gas_cloud_diss_seen = 0;
 
    // End of life? Do it backward because the array will be modified
    for (let i = regions.length - 1; i >= 0; i--) {
        if (regions[i].ttl === 0) {
            const f_indx = regions[i].expire_f;
            if (f_indx === NO_CALLBACK
                || callbacks[f_indx](regions[i], null))
                remove_region(regions[i]);
        }
    }
 
    // Process remaining regions
    for (let i = 0; i < regions.length; i++) {
        // Make the region age
        if (regions[i].ttl > 0)
            regions[i].ttl--;
        // Check if player is inside region
        let f_indx = regions[i].inside_f;
        if (f_indx !== NO_CALLBACK && hero_inside(regions[i]))
            await callbacks[f_indx](regions[i], null);
        // Check if any monster is inside region
        if (f_indx !== NO_CALLBACK) {
            for (let j = 0; j < regions[i].n_monst; j++) {
                const mtmp = find_mid(regions[i].monsters[j], FM_FMON);
 
                if (!mtmp || DEADMONSTER(mtmp)
                    || await callbacks[f_indx](regions[i], mtmp)) {
                    // The monster died, remove it from list
                    const k = (regions[i].n_monst -= 1);
                    regions[i].monsters[j] = regions[i].monsters[k];
                    regions[i].monsters[k] = 0;
                    --j; // current slot has been reused; recheck it next
                }
            }
        }
    }
 
    if (game.gas_cloud_diss_within) {
        await pline_The("gas cloud around you dissipates.");
        if ((game.u.xray_range || 0) <= 1)
            game.gas_cloud_diss_seen = 0;
        game.gas_cloud_diss_within = false;
    }
    if (game.gas_cloud_diss_seen) {
        await You_see(
            `${game.gas_cloud_diss_seen === 1 ? "a" : "some"} gas cloud${plur(game.gas_cloud_diss_seen)} dissipate.`
        );
        game.gas_cloud_diss_seen = 0;
    }
}
 
// ── in_out_region: check player enters/leaves regions ──
// C ref: region.c:480
export async function in_out_region(x, y) {
    const regions = get_regions();
    let f_indx = 0;

    // First check if hero can do the move
    for (let i = 0; i < regions.length; i++) {
        if (regions[i].attach_2_u)
            continue;
        if (inside_region(regions[i], x, y)
            ? (!hero_inside(regions[i])
               && (f_indx = regions[i].can_enter_f) !== NO_CALLBACK)
            : (hero_inside(regions[i])
               && (f_indx = regions[i].can_leave_f) !== NO_CALLBACK)) {
            if (!callbacks[f_indx](regions[i], null))
                return false;
        }
    }

    // Callbacks for the regions hero does leave
    for (let i = 0; i < regions.length; i++) {
        if (regions[i].attach_2_u)
            continue;
        if (hero_inside(regions[i])
            && !inside_region(regions[i], x, y)) {
            clear_hero_inside(regions[i]);
            if (regions[i].leave_msg !== null)
                await pline1(regions[i].leave_msg);
            if ((f_indx = regions[i].leave_f) !== NO_CALLBACK)
                callbacks[f_indx](regions[i], null);
        }
    }

    // Callbacks for the regions hero does enter
    for (let i = 0; i < regions.length; i++) {
        if (regions[i].attach_2_u)
            continue;
        if (!hero_inside(regions[i])
            && inside_region(regions[i], x, y)) {
            set_hero_inside(regions[i]);
            if (regions[i].enter_msg !== null)
                await pline1(regions[i].enter_msg);
            if ((f_indx = regions[i].enter_f) !== NO_CALLBACK)
                callbacks[f_indx](regions[i], null);
        }
    }

    return true;
}
 
// ── m_in_out_region: check monster enters/leaves regions ──
// C ref: region.c:533
export function m_in_out_region(mon, x, y) {
    const regions = get_regions();
    let f_indx = 0;
 
    // First check if mon can do the move
    for (let i = 0; i < regions.length; i++) {
        if (regions[i].attach_2_m === mon.m_id)
            continue;
        if (inside_region(regions[i], x, y)
            ? (!mon_in_region(regions[i], mon)
               && (f_indx = regions[i].can_enter_f) !== NO_CALLBACK)
            : (mon_in_region(regions[i], mon)
               && (f_indx = regions[i].can_leave_f) !== NO_CALLBACK)) {
            if (!callbacks[f_indx](regions[i], mon))
                return false;
        }
    }
 
    // Callbacks for the regions mon does leave
    for (let i = 0; i < regions.length; i++) {
        if (regions[i].attach_2_m === mon.m_id)
            continue;
        if (mon_in_region(regions[i], mon)
            && !inside_region(regions[i], x, y)) {
            remove_mon_from_reg(regions[i], mon);
            if ((f_indx = regions[i].leave_f) !== NO_CALLBACK)
                callbacks[f_indx](regions[i], mon);
        }
    }
 
    // Callbacks for the regions mon does enter
    for (let i = 0; i < regions.length; i++) {
        if (regions[i].attach_2_m === mon.m_id)
            continue;
        if (!mon_in_region(regions[i], mon)
            && inside_region(regions[i], x, y)) {
            add_mon_to_reg(regions[i], mon);
            if ((f_indx = regions[i].enter_f) !== NO_CALLBACK)
                callbacks[f_indx](regions[i], mon);
        }
    }
 
    return true;
}
 
// ── update_player_regions: after teleport etc. ──
// C ref: region.c:582
export function update_player_regions() {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++)
        if (!regions[i].attach_2_u
            && inside_region(regions[i], game.u.ux, game.u.uy))
            set_hero_inside(regions[i]);
        else
            clear_hero_inside(regions[i]);
}
 
// ── update_monster_region: update regions for a monster ──
// C ref: region.c:598
export function update_monster_region(mon) {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++) {
        if (inside_region(regions[i], mon.mx, mon.my)) {
            if (!mon_in_region(regions[i], mon))
                add_mon_to_reg(regions[i], mon);
        } else {
            if (mon_in_region(regions[i], mon))
                remove_mon_from_reg(regions[i], mon);
        }
    }
}
 
// ── reg_damg: per-turn damage from visible region ──
// C ref: region.c:651
export function reg_damg(reg) {
    const damg = (!reg.visible || reg.ttl === -2) ? 0 : reg.arg.a_int;
    return damg;
}
 
// ── any_visible_region: check if level has any visible regions ──
// C ref: region.c:660
export function any_visible_region() {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++) {
        if (!regions[i].visible || regions[i].ttl === -2)
            continue;
        return true;
    }
    return false;
}
 
// ── visible_region_at: return visible region at position, or null ──
// C ref: region.c:718
export function visible_region_at(x, y) {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++) {
        if (!regions[i].visible || regions[i].ttl === -2)
            continue;
        if (inside_region(regions[i], x, y))
            return regions[i];
    }
    return null;
}
 
// ── show_region ──
// C ref: region.c:732
export function show_region(reg, x, y) {
    show_glyph(x, y, reg.glyph);
}
 
// ── region_at: check if any region at position (used externally) ──
export function region_at(x, y) {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++) {
        if (inside_region(regions[i], x, y))
            return regions[i];
    }
    return null;
}
 
// ── save_regions ──
// C ref: region.c:741
export function save_regions(nhfp) {
    const regions = get_regions();
    // timestamp
    nhfp.writeLong(game.moves || 0);
    nhfp.writeInt(regions.length);

    for (let i = 0; i < regions.length; i++) {
        const r = regions[i];
        nhfp.writeNhRect(r.bounding_box);
        nhfp.writeShort(r.nrects);
        for (let j = 0; j < r.nrects; j++) {
            nhfp.writeNhRect(r.rects[j]);
        }
        nhfp.writeBoolean(r.attach_2_u);
        nhfp.writeUnsigned(r.attach_2_m);
        const enter_msg_len = r.enter_msg ? r.enter_msg.length : 0;
        nhfp.writeUnsigned(enter_msg_len);
        if (enter_msg_len > 0)
            nhfp.writeString(r.enter_msg);
        const leave_msg_len = r.leave_msg ? r.leave_msg.length : 0;
        nhfp.writeUnsigned(leave_msg_len);
        if (leave_msg_len > 0)
            nhfp.writeString(r.leave_msg);
        nhfp.writeLong(r.ttl);
        nhfp.writeShort(r.expire_f);
        nhfp.writeShort(r.can_enter_f);
        nhfp.writeShort(r.enter_f);
        nhfp.writeShort(r.can_leave_f);
        nhfp.writeShort(r.leave_f);
        nhfp.writeShort(r.inside_f);
        nhfp.writeUnsigned(r.player_flags);
        nhfp.writeShort(r.n_monst);
        for (let j = 0; j < r.n_monst; j++) {
            nhfp.writeUnsigned(r.monsters[j]);
        }
        nhfp.writeBoolean(r.visible);
        nhfp.writeInt(r.glyph);
        nhfp.writeAny(r.arg);
    }

    if (nhfp.release_data) {
        clear_regions();
    }
}
 
// ── rest_regions ──
// C ref: region.c:799
export function rest_regions(nhfp) {
    clear_regions(); // Just for security
    let tmstamp = nhfp.readLong();
    const ghostly = nhfp.ghostly || false;
    if (ghostly)
        tmstamp = 0;
    else
        tmstamp = (game.moves || 0) - tmstamp;
    const n_reg = nhfp.readInt();
    const regions = get_regions();

    for (let i = 0; i < n_reg; i++) {
        const r = {};
        r.bounding_box = nhfp.readNhRect();
        r.nrects = nhfp.readShort();
        r.rects = [];
        for (let j = 0; j < r.nrects; j++) {
            r.rects[j] = nhfp.readNhRect();
        }
        r.attach_2_u = nhfp.readBoolean();
        r.attach_2_m = nhfp.readUnsigned();
        let n = nhfp.readUnsigned();
        if (n > 0) {
            r.enter_msg = nhfp.readString(n);
        } else {
            r.enter_msg = null;
        }
        n = nhfp.readUnsigned();
        if (n > 0) {
            r.leave_msg = nhfp.readString(n);
        } else {
            r.leave_msg = null;
        }
        r.ttl = nhfp.readLong();
        // check for expired region
        if (r.ttl >= 0)
            r.ttl = (r.ttl > tmstamp) ? r.ttl - tmstamp : 0;
        r.expire_f = nhfp.readShort();
        r.can_enter_f = nhfp.readShort();
        r.enter_f = nhfp.readShort();
        r.can_leave_f = nhfp.readShort();
        r.leave_f = nhfp.readShort();
        r.inside_f = nhfp.readShort();
        r.player_flags = nhfp.readUnsigned();
        if (ghostly) {
            clear_hero_inside(r);
            clear_heros_fault(r);
        }
        r.n_monst = nhfp.readShort();
        r.monsters = [];
        r.max_monst = r.n_monst;
        for (let j = 0; j < r.n_monst; j++) {
            r.monsters[j] = nhfp.readUnsigned();
        }
        r.visible = nhfp.readBoolean();
        r.glyph = nhfp.readInt();
        r.arg = nhfp.readAny();
        regions.push(r);
    }
    // remove expired regions; also update monster lists if bones
    for (let i = regions.length - 1; i >= 0; i--) {
        const r = regions[i];
        if (r.ttl === 0)
            remove_region(r);
        else if (ghostly && r.n_monst > 0)
            reset_region_mids(r);
    }
}
 
// ── reset_region_mids: update monster IDs for bones ──
// C ref: region.c:928
function reset_region_mids(reg) {
    let i = 0, n = reg.n_monst;
    const mid_list = reg.monsters;

    while (i < n) {
        const result = { value: mid_list[i] };
        if (!lookup_id_mapping(mid_list[i], result)) {
            // shrink list to remove missing monster
            mid_list[i] = mid_list[--n];
        } else {
            mid_list[i] = result.value;
            ++i;
        }
    }
    reg.n_monst = n;
}
 
// ── update_regions: update all regions (alias for update_player_regions) ──
export function update_regions() {
    update_player_regions();
}
 
// ── valid_cloud_pos: check if position is valid for gas cloud ──
// C ref: read.c:1069
// C ref: region.c:1158 valid_cloud_pos()
export function valid_cloud_pos(x, y) {
    if (!isok(x, y))
        return false;
    const lev = levl(x, y);
    return ACCESSIBLE(lev?.typ) || is_pool(x, y) || is_lava(x, y);
}
 
// ── is_hero_inside_gas_cloud ──
// C ref: region.c:1168
function is_hero_inside_gas_cloud() {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++)
        if (hero_inside(regions[i])
            && regions[i].inside_f === INSIDE_GAS_CLOUD)
            return true;
    return false;
}
 
// ── make_gas_cloud: common details for gas cloud creation ──
// C ref: region.c:1182
async function make_gas_cloud(cloud, damage, inside_cloud) {
    if (!game.in_mklev && !game.context?.mon_moving)
        set_heros_fault(cloud); // assume player has created it
    cloud.inside_f = INSIDE_GAS_CLOUD;
    cloud.expire_f = EXPIRE_GAS_CLOUD;
    cloud.arg = { a_int: damage };
    cloud.visible = true;
    cloud.glyph = cmap_to_glyph(damage ? S_poisoncloud : S_cloud);
    add_region(cloud);
 
    if (!game.in_mklev && !inside_cloud && is_hero_inside_gas_cloud()) {
        await You(`are enveloped in a cloud of ${damage ? "noxious gas" : "steam"}!`);
        game.iflags.last_msg = PLNMSG_ENVELOPED_IN_GAS;
    }
}
 
// ── create_gas_cloud: create a gas cloud via BFS ──
// C ref: region.c:1213
const MAX_CLOUD_SIZE = 150;
export async function create_gas_cloud(x, y, cloudsize, damage) {
    const xcoords = new Array(MAX_CLOUD_SIZE);
    const ycoords = new Array(MAX_CLOUD_SIZE);
    xcoords[0] = x;
    ycoords[0] = y;
    let newidx = 1; // initial spot is already taken
    let inside_cloud = is_hero_inside_gas_cloud();
 
    // a single-point cloud on hero and it deals no damage
    if (!game.context?.mon_moving && u_at(x, y) && cloudsize === 1
        && (!damage
            || (damage && m_poisongas_ok(game.youmonst) === M_POISONGAS_OK)))
        inside_cloud = true;
 
    if (cloudsize > MAX_CLOUD_SIZE) {
        impossible(`create_gas_cloud: cloud too large (${cloudsize})!`);
        cloudsize = MAX_CLOUD_SIZE;
    }
 
    for (let curridx = 0; curridx < newidx; curridx++) {
        if (newidx >= cloudsize)
            break;
        const xx = xcoords[curridx];
        const yy = ycoords[curridx];

        // Primitive Fisher-Yates-Knuth shuffle
        const dirs = [ {x: 0, y: -1}, {x: 0, y: 1}, {x: -1, y: 0}, {x: 1, y: 0} ];
        for (let ii = 4; ii > 0; --ii) {
            const swapidx = rn2(ii);
            const tmp = dirs[swapidx];
            dirs[swapidx] = dirs[ii - 1];
            dirs[ii - 1] = tmp;
        }
        let nvalid = 0;
        for (let ii = 0; ii < 4; ++ii) {
            const dx = dirs[ii].x, dy = dirs[ii].y;
            let isunpicked = true;

            if (valid_cloud_pos(xx + dx, yy + dy)) {
                nvalid++;
                for (let j = 0; j < newidx; ++j) {
                    if (xcoords[j] === xx + dx && ycoords[j] === yy + dy) {
                        isunpicked = false;
                        break;
                    }
                }
                // randomly disrupt the natural BFS
                if (nvalid === 4 && !rn2(2))
                    continue;

                if (isunpicked) {
                    xcoords[newidx] = xx + dx;
                    ycoords[newidx] = yy + dy;
                    newidx++;
                }
            }
            if (newidx >= cloudsize) {
                break;
            }
        }
    }
    // Create the region from collected coordinates
    const cloud = create_region([], 0);
    for (let i = 0; i < newidx; ++i) {
        const tmprect = { lx: xcoords[i], hx: xcoords[i],
                          ly: ycoords[i], hy: ycoords[i] };
        add_rect_to_reg(cloud, tmprect);
    }
    cloud.ttl = rn1(3, 4);
    // If cloud was constrained in small space, give it more time to live
    cloud.ttl = Math.trunc((cloud.ttl * cloudsize) / newidx);
 
    await make_gas_cloud(cloud, damage, inside_cloud);
    return cloud;
}
 
// ── expire_gas_cloud: callback when gas cloud TTL reaches 0 ──
// C ref: region.c:1046
export function expire_gas_cloud(p1, p2) {
    const reg = p1;
    let damage = reg.arg.a_int;
 
    // If it was a thick cloud, it dissipates a little first
    if (damage >= 5) {
        damage = Math.trunc(damage / 2);
        reg.arg = { a_int: damage };
        reg.ttl = 2; // reset ttl
        return false; // "still there"
    }
 
    // The cloud no longer blocks vision
    for (let pass = 1; pass <= (Blind() ? 1 : 2); ++pass) {
        for (let x = reg.bounding_box.lx; x <= reg.bounding_box.hx; x++) {
            for (let y = reg.bounding_box.ly; y <= reg.bounding_box.hy; y++) {
                if (inside_region(reg, x, y)) {
                    if (pass === 1) {
                        if (!does_block(x, y, levl(x, y)))
                            unblock_point(x, y);
                    } else { // pass==2
                        if (!game.u.uswallow) {
                            if (u_at(x, y))
                                game.gas_cloud_diss_within = true;
                            else if (cansee(x, y))
                                game.gas_cloud_diss_seen = (game.gas_cloud_diss_seen || 0) + 1;
                        }
                    }
                }
            }
        }
    }
 
    return true; // OK, it's gone
}
 
// ── inside_gas_cloud: callback for creature inside gas cloud ──
// C ref: region.c:1091
// Returns true if p2 (monster) is killed, false otherwise
export async function inside_gas_cloud(p1, p2) {
    const reg = p1;
    const mtmp = p2;
    const umon = mtmp ? mtmp : game.youmonst;
    const dam = reg.arg.a_int;
 
    // fog clouds maintain gas clouds
    if (reg.ttl < 20 && umon && umon.data === mons[PM_FOG_CLOUD])
        reg.ttl += 5;
 
    if (dam < 1)
        return false; // no damage, nothing to do

    if (!mtmp) { // hero
        if (m_poisongas_ok(game.youmonst) === M_POISONGAS_OK)
            return false;
        if (!Blind()) {
            await Your(`${makeplural(body_part(EYE))} sting.`);
            await make_blinded(1, false);
        }
        if (!Poison_resistance()) {
            await pline(`Something is burning your ${makeplural(body_part(LUNG))}!`);
            await You("cough and spit blood!");
            wake_nearto(game.u.ux, game.u.uy, 2);
            let dmg = Maybe_Half_Phys(rnd(dam) + 5);
            if (Half_gas_damage())
                dmg = Math.trunc((dmg + 1) / 2);
            await losehp(dmg, "gas cloud", KILLED_BY_AN);
            monstunseesu(M_SEEN_POISON);
            return false;
        } else {
            await You("cough!");
            wake_nearto(game.u.ux, game.u.uy, 2);
            monstseesu(M_SEEN_POISON);
            return false;
        }
    } else { // A monster is inside the cloud
        if (m_poisongas_ok(mtmp) !== M_POISONGAS_OK) {
            if (!is_silent(mtmp.data)) {
                if (cansee(mtmp.mx, mtmp.my)
                    || (distu(mtmp.mx, mtmp.my) < 8))
                    await pline(`${Monnam(mtmp)} coughs!`);
                wake_nearto(mtmp.mx, mtmp.my, 2);
            }
            if (heros_fault(reg))
                await setmangry(mtmp, true);
            if (haseyes(mtmp.data) && mtmp.mcansee) {
                mtmp.mblinded = 1;
                mtmp.mcansee = 0;
            }
            if (resists_poison(mtmp))
                return false;
            mtmp.mhp -= rnd(dam) + 5;
            if (DEADMONSTER(mtmp)) {
                if (heros_fault(reg))
                    await killed(mtmp);
                else
                    await monkilled(mtmp, "gas cloud", AD_DRST);
                if (DEADMONSTER(mtmp)) { // not lifesaved
                    return true;
                }
            }
        }
    }
    return false; // Monster is still alive
}
 
// ── gas_cloud_in_sight: check if hero can see a gas cloud ──
// (Utility used externally)
export function gas_cloud_in_sight() {
    const regions = get_regions();
    for (let i = 0; i < regions.length; i++) {
        if (!regions[i].visible || regions[i].ttl === -2)
            continue;
        if (regions[i].inside_f === INSIDE_GAS_CLOUD) {
            for (let x = regions[i].bounding_box.lx; x <= regions[i].bounding_box.hx; x++)
                for (let y = regions[i].bounding_box.ly; y <= regions[i].bounding_box.hy; y++)
                    if (inside_region(regions[i], x, y) && cansee(x, y))
                        return true;
        }
    }
    return false;
}
 
// ── region_danger: is hero at risk from regions? (prayer check) ──
// C ref: region.c:1342
export function region_danger() {
    const regions = get_regions();
    let n = 0;
 
    for (let i = 0; i < regions.length; i++) {
        if (!hero_inside(regions[i]))
            continue;
        const f_indx = regions[i].inside_f;
        if (f_indx === INSIDE_GAS_CLOUD) {
            if (nonliving(game.youmonst?.data) || Breathless())
                continue;
            if (Poison_resistance())
                continue;
            ++n;
        }
    }
    return n ? true : false;
}
 
// ── region_safety: fix trouble from regions at end of prayer ──
// C ref: region.c:1368
export async function region_safety() {
    let r = null;
    const regions = get_regions();
    let n = 0;

    for (let i = 0; i < regions.length; i++) {
        if (!hero_inside(regions[i]))
            continue;
        const f_indx = regions[i].inside_f;
        if (f_indx === INSIDE_GAS_CLOUD) {
            if (!n++ && regions[i].ttl >= 0)
                r = regions[i];
        }
    }

    if (n > 1 || (n === 1 && !r)) {
        await safe_teleds(TELEDS_NO_FLAGS);
        if (region_danger()) {
            set_itimeout('HMagical_breathing', c_d(4, 4) + 4);
            await You("feel able to breathe.");
        }
    } else if (r) {
        remove_region(r);
        await pline_The("gas cloud enveloping you dissipates.");
    } else {
        await pline_The("gas cloud has dissipated.");
    }
    // maybe cure blindness too
    if (BlindedTimeout() === 1)
        await make_blinded(0, true);
}