All files / js vision.js

97.44% Statements 725/744
90.64% Branches 310/342
100% Functions 17/17
97.44% Lines 725/744

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 74573x 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 157778x 157778x 157778x 6343x 6343x 6343x 157778x 157778x 157778x 157778x 157778x 157778x 73x 73x 73x 73x 3006108x 3006108x 3006108x 3006108x 3006108x 3006108x 3006108x 1915266x 1915266x 3006108x 10186x 10186x 10186x 1912283x 1912283x 1912283x 3006108x 3006108x 3006108x 697256x 697256x 697256x 3006108x 3006108x 15816864x 15816864x 15816864x 692772x 692772x 692772x 692772x 3006108x 15516x 15516x 15516x 15505x 15516x 1x 15516x 15516x 15516x 692760x 692760x 692760x 692760x 3006108x 692668x 692668x 3006108x 73x 73x 73x 73x 1812x 1812x 1812x 1812x 38052x 38052x 38052x 38052x 3006108x 3006108x 294664x 147494x 147494x 923991x 923991x 923991x 294664x 147170x 147170x 147170x 147170x 672123x 672123x 672123x 672123x 147170x 294664x 294664x 294664x 3006108x 38052x 38052x 38052x 38052x 1448046x 1448046x 1448046x 1448046x 38052x 1812x 1812x 1812x 1812x 1812x 73x 73x 73x 73x 73x 60710x 60710x 60710x 60710x 60710x 13973x 13973x 38770x 38770x 38770x 38770x 38770x 60710x 46737x 46737x 158604x 158604x 158604x 158604x 158604x 20284x 25159x 60710x 73x 73x 79040x 79040x 79040x 79040x 79040x 31193x 31193x 66060x 66060x 66060x 66060x 66060x 79040x 47847x 47847x 237480x 237480x 237480x 237480x 237480x 23423x 42051x 79040x 73x 73x 95688x 95688x 95688x 95688x 95688x 29080x 29080x 59171x 59171x 59171x 59171x 59171x 95688x 66608x 66608x 225515x 225515x 225515x 225515x 225515x 40781x 56824x 95688x 73x 73x 78585x 78585x 78585x 78585x 78585x 10401x 10401x 32452x 32452x 32452x 32452x 32452x 78585x 68184x 68184x 241818x 241818x 241818x 241818x 241818x 40462x 44563x 78585x 73x 73x 62694x 62694x 62694x 62694x 62694x 62694x 62694x 62694x 62694x 62694x 62694x 83601x 83601x 83601x 83601x 30880x 30880x 19411x 19411x 19411x 30880x 30880x 30880x 30880x 52721x 52721x 83601x 18143x 55501x 55501x 55501x 55501x 55501x 18143x 18143x 642x 642x 642x 18143x 18143x 43907x 43907x 83591x 11455x 27400x 27400x 27400x 27400x 27400x 11455x 83601x 32452x 32452x 43907x 79948x 43407x 43407x 318x 318x 43407x 43407x 43407x 43407x 43407x 83601x 62694x 73x 73x 62127x 62127x 62127x 62127x 62127x 62127x 62127x 62127x 62127x 62127x 62127x 82135x 82135x 82135x 82135x 30184x 18729x 18729x 18729x 30184x 30184x 30184x 30184x 51951x 82135x 17373x 51346x 51346x 51346x 51346x 51346x 17373x 17373x 30x 30x 30x 17373x 17373x 43450x 43450x 82117x 12208x 29982x 29982x 29982x 29982x 29982x 12208x 82135x 31242x 31242x 43450x 78505x 42865x 42865x 297x 297x 42865x 42865x 42865x 42865x 42865x 82135x 62127x 73x 73x 9770x 9770x 9770x 9770x 9770x 9770x 9770x 9770x 9770x 9770x 9770x 9770x 9712x 9712x 9770x 58x 58x 58x 58x 58x 9770x 9770x 9770x 434x     434x 434x 434x 434x 9770x 9770x 9770x 9770x 9770x 9770x 9770x 9759x 9759x 9759x 9759x 9770x 9770x 9750x 9750x 9750x 9750x 9770x 9770x 9770x 73x 73x 73x 73x 73x 73x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 305403x 305403x 305403x 305403x 14543x 14543x 14543x 14543x 5202x 14503x 141x 141x 141x 9341x 5x 5x 5x 15x 15x 15x 15x 15x 9200x 9195x 9195x 9195x 14543x 14543x 14543x 14543x 14543x 215x 215x 215x 215x 14328x 14328x 14328x 14328x 14328x 14328x 14543x 300888x 300888x 698575x 660366x 698575x 698575x 660366x 660366x 698575x 82767x 82767x 82767x 577599x 577599x 698575x 401143x 401143x 401143x 401143x 152499x 152499x 152499x 152499x 137417x 137417x 152499x 401143x 248644x 248644x 401143x 698575x 300888x 14328x 14328x 14328x 14328x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 14543x 9200x 9200x 9200x 193200x 193200x 193200x 193200x 193200x 193200x 193200x 193200x 193200x 193200x 193200x 193200x 193200x 74550x 193200x 733770x 733770x 733770x 733770x 733770x 733770x 468828x 468828x 468828x 468828x 468828x 468828x 325356x 325356x 733770x 264942x 15082x 15082x 15082x 15082x 15082x 15082x 15082x 15082x               15082x                 264942x 2264x 2264x 2264x 249860x 247596x 247596x 247596x 149620x 149620x 247596x 733770x 74550x 9200x 9200x 9200x 14328x 14328x 14328x 14328x 14543x 73x 73x 73x 73x 73x 73x 150193x 150193x 56394x 17566x 56394x 38828x 38828x 150193x 93400x 37068x 93167x 56332x 56332x 93400x 150193x 73x 73x 73x 44807x 44807x 44804x 44807x 73x 73x 73x 73x 1437209x 1437209x 1437209x 73x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 73x 73x 73x 73x 73x 440x 440x     440x 434x 434x 434x 434x 6x 12x 6x 6x 12x 77x 77x 77x 77x 877x 351x 351x 877x 77x 440x 73x 73x 72x 72x 72x 72x 72x 72x 72x 72x 72x  
// vision.js — C ref: vision.c Algorithm C shadow-casting
// COULD_SEE: line-of-sight raycasting from hero
// IN_SIGHT: COULD_SEE AND (lit or within night vision range)
import { game } from './gstate.js';
import { CLOUD, D_CLOSED, D_LOCKED, D_TRAPPED, DOOR, LAVAWALL, POOL, SDOOR, SV0, SV1, SV2, SV3, SV4, SV5, SV6, SV7, IS_WALL, TEMP_LIT, WATER, M_AP_TYPE, M_AP_FURNITURE, M_AP_OBJECT, TT_PIT } from './const.js';
import { do_light_sources } from './light.js';
import { BOULDER } from './objects.js';
import { m_at } from './map_access.js';
import { S_hcdoor, S_vcdoor, S_ndoor, S_tree } from './symbols.js';
import { Blind, See_invisible, Underwater } from './macros.js';
import { newsym } from './display.js';
import { is_moat } from './dbridge.js';
import { visible_region_at } from './region.js';
 
const ROWNO = 21;
const COLNO = 80;
const COULD_SEE = 0x1;
const IN_SIGHT = 0x2;
// POOL imported from const.js — IS_OBSTRUCTED = typ < POOL
 
// C ref: vision.c seenv_matrix — maps (dy, dx) to seenv bit.
// Indexed by [sign(uy-row)+1][col<ux ? 0 : col>ux ? 2 : 1]
const seenv_matrix = [
    [SV2, SV1, SV0],
    [SV3, 0,   SV7],
    [SV4, SV5, SV6],
];
 
// Circle data for range limits (C vision.c:27-70)
export const circle_data = [
    /*  0*/ 0,
    /*  1*/ 1, 1,
    /*  3*/ 2, 2, 1,
    /*  6*/ 3, 3, 2, 1,
    /* 10*/ 4, 4, 4, 3, 2,
    /* 15*/ 5, 5, 5, 4, 3, 2,
    /* 21*/ 6, 6, 6, 5, 5, 4, 2,
    /* 28*/ 7, 7, 7, 6, 6, 5, 4, 2,
    /* 36*/ 8, 8, 8, 7, 7, 6, 6, 4, 2,
    /* 45*/ 9, 9, 9, 9, 8, 8, 7, 6, 5, 3,
    /* 55*/ 10, 10, 10, 10, 9, 9, 8, 7, 6, 5, 3,
    /* 66*/ 11, 11, 11, 11, 10, 10, 9, 9, 8, 7, 5, 3,
    /* 78*/ 12, 12, 12, 12, 11, 11, 10, 10, 9, 8, 7, 5, 3,
    /* 91*/ 13, 13, 13, 13, 12, 12, 12, 11, 10, 10, 9, 7, 6, 3,
    /*105*/ 14, 14, 14, 14, 13, 13, 13, 12, 12, 11, 10, 9, 8, 6, 3,
    /*120*/ 15, 15, 15, 15, 14, 14, 14, 13, 13, 12, 11, 10, 9, 8, 6, 3,
    /*136*/ 16,
];
const circle_start = [0, 1, 3, 6, 10, 15, 21, 38, 36, 45, 55, 66, 78, 91, 105, 120];
 
// Vision state
const viz_clear = Array.from({ length: ROWNO }, () => new Int8Array(COLNO));
const left_ptrs = Array.from({ length: ROWNO }, () => new Int16Array(COLNO));
const right_ptrs = Array.from({ length: ROWNO }, () => new Int16Array(COLNO));
 
// Double-buffered COULD_SEE bitmap
const cs_buf0 = Array.from({ length: ROWNO }, () => new Uint8Array(COLNO));
const cs_buf1 = Array.from({ length: ROWNO }, () => new Uint8Array(COLNO));
const cs_rmin0 = new Int16Array(ROWNO).fill(COLNO);
const cs_rmax0 = new Int16Array(ROWNO).fill(0);
const cs_rmin1 = new Int16Array(ROWNO).fill(COLNO);
const cs_rmax1 = new Int16Array(ROWNO).fill(0);
 
 // which buffer is active
 
// Globals used by right_side/left_side (C uses file-scope statics)
let vis_func = null;
let vis_arg = null;
 
function mark_visible_range(row, left, right) {
    if (left > right) return;
    if (vis_func) {
        for (let i = left; i <= right; i++) vis_func(i, row, vis_arg);
        return;
    }
    const rowp = game.cs_rows?.[row];
    if (!rowp) return;
    for (let i = left; i <= right; i++) rowp[i] = COULD_SEE;
    if (game.cs_left[row] > left) game.cs_left[row] = left;
    if (game.cs_right[row] < right) game.cs_right[row] = right;
}
 
// Check if level cell blocks vision
// C ref: vision.c:153 does_block + IS_OBSTRUCTED
// Full port of C's blockage check for shadow-casting vision.
function _blocks(level, x, y) {
    const loc = level.at(x, y);
    if (!loc) return true;
    const typ = loc.typ ?? 0;
 
    // C ref: IS_OBSTRUCTED(typ) — STONE, walls, TREE, SDOOR, SCORR
    if (typ < POOL) return true;
 
    // Closed/locked doors block sight
    if (typ === DOOR) {
        const mask = loc.doormask ?? loc.flags ?? 0;
        if (mask & (D_CLOSED | D_LOCKED | D_TRAPPED)) return true;
    }
 
    // Cloud terrain, water walls, lava walls block sight
    // C ref: also checks (Underwater && is_moat(x, y))
    if (typ === CLOUD || typ === WATER || typ === LAVAWALL
        || (Underwater() && is_moat(x, y)))
        return true;
 
    // Boulders block light
    // C ref: vision.c:182 — iterate floor objects at (x,y)
    const objs = level.objects || [];
    for (const obj of objs) {
        if (obj.ox === x && obj.oy === y && obj.otyp === BOULDER)
            return true;
    }
 
    // Mimics mimicking a door, boulder, or wall block light
    // C ref: vision.c:187 — is_lightblocker_mappear(mon)
    const mon = m_at(x, y);
    if (mon && (!mon.minvis || See_invisible())) {
        const aptype = M_AP_TYPE(mon);
        if (aptype === M_AP_OBJECT && mon.mappearance === BOULDER)
            return true;
        if (aptype === M_AP_FURNITURE
            && (mon.mappearance === S_hcdoor || mon.mappearance === S_vcdoor
                || mon.mappearance < S_ndoor /* walls */
                || mon.mappearance === S_tree))
            return true;
    }
 
    // Gas cloud regions block light
    // C ref: vision.c:195 — visible_region_at(x, y)
    if (visible_region_at(x, y))
        return true;
 
    return false;
}
 
// Rebuild viz_clear and left/right ptrs from current level terrain
// C ref: vision_reset() lines 210-265
export function vision_reset() {
    const level = game.level;
    if (!level) return;
 
    for (let y = 0; y < ROWNO; y++) {
        viz_clear[y].fill(0);
        let dig_left = 0;
        let block = true; // column 0 is always stone
        for (let x = 1; x < COLNO; x++) {
            const cur_block = _blocks(level, x, y);
            if (block !== cur_block) {
                if (block) {
                    // Transition from blocked to clear
                    for (let i = dig_left; i < x; i++) {
                        left_ptrs[y][i] = dig_left;
                        right_ptrs[y][i] = x - 1;
                    }
                } else {
                    // Transition from clear to blocked
                    let i = dig_left;
                    if (dig_left) dig_left--;
                    for (; i < x; i++) {
                        left_ptrs[y][i] = dig_left;
                        right_ptrs[y][i] = x;
                        viz_clear[y][i] = 1;
                    }
                }
                dig_left = x;
                block = !block;
            }
        }
        // Handle right boundary
        let i = dig_left;
        if (!block && dig_left) dig_left--;
        for (; i < COLNO; i++) {
            left_ptrs[y][i] = dig_left;
            right_ptrs[y][i] = COLNO - 1;
            viz_clear[y][i] = block ? 0 : 1;
        }
    }
    // Clear stale rmin/rmax so the next vision_recalc(0) newsym loop
    // doesn't cross-compare against the previous level's visibility.
    game._viz_rmin = null;
    game._viz_rmax = null;
}
 
// Bresenham line-of-sight check for quadrant I (step<0, dx>0, dy<0)
// C ref: _q1_path(scol, srow, y2, x2) — C's naming is transposed:
// "scol" receives start_row and "srow" receives start_col.
// Match C by assigning x = first param (row), y = second param (col).
function q1_path(srow, scol, y2, x2) {
    let x = scol, y = srow;
    const dx = x2 - x, dy = y - y2;
    const dxs = dx << 1, dys = dy << 1;
    if (dy > dx) {
        let err = dxs - dy;
        for (let k = dy - 1; k; k--) {
            if (err >= 0) { x++; err -= dys; }
            y--;
            err += dxs;
            if (!viz_clear[y][x]) return 0;
        }
    } else {
        let err = dys - dx;
        for (let k = dx - 1; k; k--) {
            if (err >= 0) { y--; err -= dxs; }
            x++;
            err += dys;
            if (!viz_clear[y][x]) return 0;
        }
    }
    return 1;
}
 
// Quadrant II (step<0, dx<0, dy<0)
function q2_path(srow, scol, y2, x2) {
    let x = scol, y = srow;
    const dx = x - x2, dy = y - y2;
    const dxs = dx << 1, dys = dy << 1;
    if (dy > dx) {
        let err = dxs - dy;
        for (let k = dy - 1; k; k--) {
            if (err >= 0) { x--; err -= dys; }
            y--;
            err += dxs;
            if (!viz_clear[y][x]) return 0;
        }
    } else {
        let err = dys - dx;
        for (let k = dx - 1; k; k--) {
            if (err >= 0) { y--; err -= dxs; }
            x--;
            err += dys;
            if (!viz_clear[y][x]) return 0;
        }
    }
    return 1;
}
 
// Quadrant III (step>0, dx<0, dy>0)
function q3_path(srow, scol, y2, x2) {
    let x = scol, y = srow;
    const dx = x - x2, dy = y2 - y;
    const dxs = dx << 1, dys = dy << 1;
    if (dy > dx) {
        let err = dxs - dy;
        for (let k = dy - 1; k; k--) {
            if (err >= 0) { x--; err -= dys; }
            y++;
            err += dxs;
            if (!viz_clear[y][x]) return 0;
        }
    } else {
        let err = dys - dx;
        for (let k = dx - 1; k; k--) {
            if (err >= 0) { y++; err -= dxs; }
            x--;
            err += dys;
            if (!viz_clear[y][x]) return 0;
        }
    }
    return 1;
}
 
// Quadrant IV (step>0, dx>0, dy>0)
function q4_path(srow, scol, y2, x2) {
    let x = scol, y = srow;
    const dx = x2 - x, dy = y2 - y;
    const dxs = dx << 1, dys = dy << 1;
    if (dy > dx) {
        let err = dxs - dy;
        for (let k = dy - 1; k; k--) {
            if (err >= 0) { x++; err -= dys; }
            y++;
            err += dxs;
            if (!viz_clear[y][x]) return 0;
        }
    } else {
        let err = dys - dx;
        for (let k = dx - 1; k; k--) {
            if (err >= 0) { y++; err -= dxs; }
            x++;
            err += dys;
            if (!viz_clear[y][x]) return 0;
        }
    }
    return 1;
}
 
// C ref: vision.c right_side() — scan right side of visibility cone
function right_side(row, left, right_mark, limitsIdx) {
    const nrow = row + game.vis_step;
    const deeper = nrow >= 0 && nrow < ROWNO
        && (limitsIdx < 0 || circle_data[limitsIdx] >= circle_data[limitsIdx + 1]);
    const lim_max = limitsIdx >= 0
        ? Math.min(COLNO - 1, game.vis_start_col + circle_data[limitsIdx])
        : COLNO - 1;
    if (right_mark > lim_max) right_mark = lim_max;
    const nextLimIdx = limitsIdx >= 0 ? limitsIdx + 1 : -1;
 
    while (left <= right_mark) {
        let right_edge = right_ptrs[row][left];
        if (right_edge > lim_max) right_edge = lim_max;
 
        if (!viz_clear[row][left]) {
            // Stone wall — see it, jump to far side
            if (right_edge > right_mark) {
                right_edge = (row - game.vis_step >= 0 && row - game.vis_step < ROWNO && viz_clear[row - game.vis_step][right_mark])
                    ? right_mark + 1 : right_mark;
            }
            mark_visible_range(row, left, right_edge);
            left = right_edge + 1;
            continue;
        }
 
        // Clear area — find visible bounds
        if (left !== game.vis_start_col) {
            for (; left <= right_edge; left++) {
                const result = game.vis_step < 0
                    ? q1_path(game.vis_start_row, game.vis_start_col, row, left)
                    : q4_path(game.vis_start_row, game.vis_start_col, row, left);
                if (result) break;
            }
            if (left > lim_max) return;
            if (left === lim_max) {
                mark_visible_range(row, lim_max, lim_max);
                return;
            }
            if (left >= right_edge) { left = right_edge; continue; }
        }
 
        let right;
        if (right_mark < right_edge) {
            for (right = right_mark; right <= right_edge; right++) {
                const result = game.vis_step < 0
                    ? q1_path(game.vis_start_row, game.vis_start_col, row, right)
                    : q4_path(game.vis_start_row, game.vis_start_col, row, right);
                if (!result) break;
            }
            right--;
        } else {
            right = right_edge;
        }
 
        if (left <= right) {
            if (left === right && left === game.vis_start_col && game.vis_start_col < COLNO - 1
                && !viz_clear[row][game.vis_start_col + 1]) {
                right = game.vis_start_col + 1;
            }
            if (right > lim_max) right = lim_max;
            mark_visible_range(row, left, right);
            if (deeper) right_side(nrow, left, right, nextLimIdx);
            left = right + 1;
        }
    }
}
 
// C ref: vision.c left_side() — mirror of right_side
function left_side(row, left_mark, right, limitsIdx) {
    const nrow = row + game.vis_step;
    const deeper = nrow >= 0 && nrow < ROWNO
        && (limitsIdx < 0 || circle_data[limitsIdx] >= circle_data[limitsIdx + 1]);
    const lim_min = limitsIdx >= 0
        ? Math.max(0, game.vis_start_col - circle_data[limitsIdx])
        : 0;
    if (left_mark < lim_min) left_mark = lim_min;
    const nextLimIdx = limitsIdx >= 0 ? limitsIdx + 1 : -1;
 
    while (right >= left_mark) {
        let left_edge = left_ptrs[row][right];
        if (left_edge < lim_min) left_edge = lim_min;
 
        if (!viz_clear[row][right]) {
            if (left_edge < left_mark) {
                left_edge = (row - game.vis_step >= 0 && row - game.vis_step < ROWNO && viz_clear[row - game.vis_step][left_mark])
                    ? left_mark - 1 : left_mark;
            }
            mark_visible_range(row, left_edge, right);
            right = left_edge - 1;
            continue;
        }
 
        if (right !== game.vis_start_col) {
            for (; right >= left_edge; right--) {
                const result = game.vis_step < 0
                    ? q2_path(game.vis_start_row, game.vis_start_col, row, right)
                    : q3_path(game.vis_start_row, game.vis_start_col, row, right);
                if (result) break;
            }
            if (right < lim_min) return;
            if (right === lim_min) {
                mark_visible_range(row, lim_min, lim_min);
                return;
            }
            if (right <= left_edge) { right = left_edge; continue; }
        }
 
        let left;
        if (left_mark > left_edge) {
            for (left = left_mark; left >= left_edge; left--) {
                const result = game.vis_step < 0
                    ? q2_path(game.vis_start_row, game.vis_start_col, row, left)
                    : q3_path(game.vis_start_row, game.vis_start_col, row, left);
                if (!result) break;
            }
            left++;
        } else {
            left = left_edge;
        }
 
        if (left <= right) {
            if (left === right && right === game.vis_start_col && game.vis_start_col > 0
                && !viz_clear[row][game.vis_start_col - 1]) {
                left = game.vis_start_col - 1;
            }
            if (left < lim_min) left = lim_min;
            mark_visible_range(row, left, right);
            if (deeper) left_side(nrow, left, right, nextLimIdx);
            right = left - 1;
        }
    }
}
 
// C ref: vision.c view_from() — compute COULD_SEE bitmap from a position
function view_from(srow, scol, cs_rows, cs_left, cs_right, range = 0, func = null, arg = null) {
    game.vis_start_col = scol;
    game.vis_start_row = srow;
    game.cs_rows = cs_rows;
    game.cs_left = cs_left;
    game.cs_right = cs_right;
    vis_func = (typeof func === 'function') ? func : null;
    vis_arg = arg;
 
    // Determine extent of sight on starting row
    let left, right;
    if (viz_clear[srow][scol]) {
        left = left_ptrs[srow][scol];
        right = right_ptrs[srow][scol];
    } else {
        left = !scol ? 0
            : (viz_clear[srow][scol - 1] ? left_ptrs[srow][scol - 1] : scol - 1);
        right = scol === COLNO - 1 ? COLNO - 1
            : (viz_clear[srow][scol + 1] ? right_ptrs[srow][scol + 1] : scol + 1);
    }
 
    let limitsIdx = -1;
    if (range) {
        if (range < 1 || range > 15) {
            throw new Error(`view_from: illegal range ${range}`);
        }
        if (left < scol - range) left = scol - range;
        if (right > scol + range) right = scol + range;
        limitsIdx = circle_start[range] + 1;
    }
 
    // Mark starting row as visible / emit callback.
    mark_visible_range(srow, left, right);
 
    // Scan downward (step=1) and upward (step=-1)
    const nrow_down = srow + 1;
    if (nrow_down < ROWNO) {
        game.vis_step = 1;
        if (scol < COLNO - 1) right_side(nrow_down, scol, right, limitsIdx);
        if (scol) left_side(nrow_down, left, scol, limitsIdx);
    }
    const nrow_up = srow - 1;
    if (nrow_up >= 0) {
        game.vis_step = -1;
        if (scol < COLNO - 1) right_side(nrow_up, scol, right, limitsIdx);
        if (scol) left_side(nrow_up, left, scol, limitsIdx);
    }
    vis_func = null;
    vis_arg = null;
}
 
// Recompute the visibility bitmap from the hero's current position
// C ref: vision_recalc() simplified — only COULD_SEE, no light sources
// C ref: vision_recalc(control)
// control: 0 = full recalc, 1 = hero moved, 2 = docrt (skip view_from)
export function vision_recalc(control = 0) {
    const u = game.u;
    if (!u || !game.level) return;
    // C ref: vision.c — clear the flag so callers know recalc has been done
    game.vision_full_recalc = 0;
 
    // C ref: skip if in level generation or getlev
    if (game.in_mklev) return;
 
    // Swap to unused buffer
    const next = game.active_buf === 0 ? cs_buf1 : cs_buf0;
    const next_rmin = game.active_buf === 0 ? cs_rmin1 : cs_rmin0;
    const next_rmax = game.active_buf === 0 ? cs_rmax1 : cs_rmax0;
 
    // Clear the new buffer
    for (let y = 0; y < ROWNO; y++) {
        next[y].fill(0);
        next_rmin[y] = COLNO;
        next_rmax[y] = 0;
    }
 
    // C ref: vision.c:545 — control==2 (docrt) skips view_from entirely.
    // The hero sees nothing; only the newsym remembered-glyph path renders.
    if (control === 2) {
        // docrt refresh — skip view_from (blank vision)
    } else if (Blind()) {
        // C ref: vision.c blind branch — compute COULD_SEE so monsters can
        // still see the hero, but do not grant IN_SIGHT to the hero.
        view_from(u.uy, u.ux, next, next_rmin, next_rmax);
    } else if (game.u?.utrap && game.u?.utraptype === TT_PIT) {
        // C ref: vision.c:609 — hero in pit, only see immediate 3x3 area
        const uy = u.uy, ux = u.ux;
        for (let row = Math.max(0, uy - 1); row <= Math.min(ROWNO - 1, uy + 1); row++) {
            next_rmin[row] = Math.max(1, ux - 1);
            next_rmax[row] = Math.min(COLNO - 1, ux + 1);
            for (let col = next_rmin[row]; col <= next_rmax[row]; col++)
                next[row][col] = IN_SIGHT | COULD_SEE;
        }
    } else {
        // Full visibility from hero position
        view_from(u.uy, u.ux, next, next_rmin, next_rmax);
    }
 
    // C ref: vision.c:700 — apply light sources (TEMP_LIT)
    do_light_sources(next);
 
    if (Blind()) {
        game.viz_array = next;
        game.active_buf = game.active_buf === 0 ? 1 : 0;
        return;
    }
 
    // C ref: vision.c:711-795 — compute IN_SIGHT from COULD_SEE + lighting
    // IN_SIGHT = COULD_SEE AND (lit OR TEMP_LIT OR night_vision)
    const level = game.level;
    const ux = u.ux, uy = u.uy;
 
    for (let row = 0; row < ROWNO; row++) {
        const dy = Math.sign(uy - row);
        for (let col = next_rmin[row]; col <= next_rmax[row]; col++) {
            if (!(next[row][col] & COULD_SEE)) continue;
 
            const loc = level?.at(col, row);
            if (!loc) continue;
 
            // Night vision: hero's position and adjacent cells always IN_SIGHT
            if (Math.abs(col - ux) <= 1 && Math.abs(row - uy) <= 1) {
                next[row][col] |= IN_SIGHT;
                continue;
            }
 
            // C ref: vision.c:755-795 — lit or TEMP_LIT cells are IN_SIGHT
            if (loc.lit || (next[row][col] & TEMP_LIT)) {
                // Doors/walls: check adjacent cell toward hero is also lit
                // C ref: vision.c:760-784
                if ((loc.typ === DOOR || loc.typ === SDOOR || IS_WALL(loc.typ))
                    && !viz_clear[row]?.[col]) {
                    const dx = Math.sign(ux - col);
                    const fy = row + dy, fx = col + dx;
                    const flev = level?.at(fx, fy);
                    if (flev?.lit || (fy >= 0 && fy < ROWNO && fx >= 0 && fx < COLNO && (next[fy]?.[fx] & TEMP_LIT))) {
                        next[row][col] |= IN_SIGHT;
                    }
                    // else: door/wall at end of dark hallway — not in sight
                } else {
                    next[row][col] |= IN_SIGHT;
                }
            }
        }
    }
 
    // C ref: vision.c:708-709 — swap viz_array before newsym loop
    const old_array = game.viz_array;
    game.viz_array = next;
    game.active_buf = game.active_buf === 0 ? 1 : 0;
 
    // C ref: vision.c:727-830 — main update loop.
    // Update seenv (wall seen-angle) for visible cells, then call newsym
    // for cells where visibility or seenv changed. With gnew tracking,
    // newsym only marks cells dirty — flush_screen paints them later.
    const old_rmin = game._viz_rmin;
    const old_rmax = game._viz_rmax;
    if (old_array && control !== 2 && game.level) {
        const ux = game.u?.ux ?? 0;
        const uy = game.u?.uy ?? 0;
        for (let row = 0; row < ROWNO; row++) {
            const old_row = old_array[row];
            const next_row = next[row];
            // When old_rmin is null (after vision_reset), use only new
            // bounds. All cells gaining IN_SIGHT from a blank old buffer
            // need newsym — matching C's behavior after docrt's
            // vision_recalc(2) blanks the old array.
            const start = old_rmin
                ? Math.min(old_rmin[row], next_rmin[row])
                : next_rmin[row];
            const stop = old_rmax
                ? Math.max(old_rmax[row], next_rmax[row])
                : next_rmax[row];
            if (start > stop) continue;
            const dy = Math.sign(uy - row);
            for (let col = start; col <= stop; col++) {
                const nv = next_row[col];
                const ov = old_row[col];
                const loc = game.level.at(col, row);
                if (!loc) continue;
 
                if (nv & IN_SIGHT) {
                    // C ref: vision.c:743-753 — cell is IN_SIGHT.
                    // Update seenv, newsym if newly visible or angle changed.
                    const oldseenv = loc.seenv || 0;
                    const sv = seenv_matrix[dy + 1][(col < ux) ? 0 : (col > ux ? 2 : 1)];
                    loc.seenv = (loc.seenv || 0) | sv;
                    if (!(ov & IN_SIGHT) || oldseenv !== loc.seenv) {
                        newsym(col, row);
                    }
                } else if ((nv & COULD_SEE)
                           && (loc.lit || (nv & TEMP_LIT))) {
                    // C ref: vision.c:755-793 — cell not in direct sight
                    // but is lit (room lighting). For walls/doors, check
                    // adjacent cell toward hero is also lit before showing.
                    if ((IS_WALL(loc.typ) || loc.typ === DOOR || loc.typ === SDOOR)
                        && !viz_clear[row][col]) {
                        const dx = Math.sign(ux - col);
                        const adjLoc = game.level.at(col + dx, row + dy);
                        if (adjLoc && (adjLoc.lit || (next[row + dy]?.[col + dx] & TEMP_LIT))) {
                            next_row[col] |= IN_SIGHT;
                            const oldseenv = loc.seenv || 0;
                            const sv = seenv_matrix[dy + 1][(col < ux) ? 0 : (col > ux ? 2 : 1)];
                            loc.seenv = (loc.seenv || 0) | sv;
                            if (!(ov & IN_SIGHT) || oldseenv !== loc.seenv)
                                newsym(col, row);
                        }
                    } else {
                        // Non-wall lit cell — mark IN_SIGHT and update
                        next_row[col] |= IN_SIGHT;
                        const oldseenv = loc.seenv || 0;
                        const sv = seenv_matrix[dy + 1][(col < ux) ? 0 : (col > ux ? 2 : 1)];
                        loc.seenv = (loc.seenv || 0) | sv;
                        if (!(ov & IN_SIGHT) || oldseenv !== loc.seenv)
                            newsym(col, row);
                    }
                } else if ((nv & COULD_SEE) && loc.waslit) {
                    // C ref: vision.c:796-805 — was lit, now dark
                    loc.waslit = 0;
                    newsym(col, row);
                } else {
                    // C ref: vision.c:820-825 — not in sight
                    if ((ov & IN_SIGHT)
                        || ((nv & COULD_SEE) ^ (ov & COULD_SEE))) {
                        newsym(col, row);
                    }
                }
            }
        }
        // C ref: vision.c:839 — always update hero position
        if (ux > 0) newsym(ux, uy);
    }
 
    // Save rmin/rmax for next call's comparison bounds
    game._viz_rmin = next_rmin;
    game._viz_rmax = next_rmax;
}
 
// C ref: vision.c:1602 clear_path — line-of-sight test between two points.
// Uses quadrant path functions for accurate LOS through map geometry.
// TODO: port the actual q1/q2/q3/q4_path algorithms for full fidelity.
// C ref: vision.c:1602 clear_path — Bresenham line trace checking viz_clear
export function clear_path(col1, row1, col2, row2) {
    if (col1 === col2 && row1 === row2) return true;
    if (col1 < col2) {
        if (row1 > row2) {
            return !!q1_path(row1, col1, row2, col2);
        } else {
            return !!q4_path(row1, col1, row2, col2);
        }
    } else {
        if (row1 > row2) {
            return !!q2_path(row1, col1, row2, col2);
        } else {
            return !!q3_path(row1, col1, row2, col2);
        }
    }
}
 
// C ref: couldsee(x, y) macro — check if position has line-of-sight
export function couldsee(x, y) {
    if (y < 0 || y >= ROWNO || x < 0 || x >= COLNO) return false;
    if (!game.viz_array?.[y]) return false;
    return !!(game.viz_array[y][x] & COULD_SEE);
}
 
// C ref: cansee(x, y) macro — check if position is visible to hero
// cansee = couldsee AND IN_SIGHT (lit, or within night vision range)
export function cansee(x, y) {
    if (y < 0 || y >= ROWNO || x < 0 || x >= COLNO) return false;
    return !!(game.viz_array[y][x] & IN_SIGHT);
}
 
function circle_ptr(range) {
    if (range < 1 || range > 15) return null;
    // C ref: #define circle_ptr(z) (&circle_data[(int) circle_start[z]])
    // C returns a raw pointer into circle_data; callers index it by offset.
    // circle_start[7] == 38 in C (an intentional quirk where range-7 data is
    // reused from range-8's table); using slice(start, end) would produce
    // [] for range=7 because circle_start[8]==36 < 38. Match C's pointer
    // semantics by slicing from start to the end of the array.
    return circle_data.slice(circle_start[range]);
}
 
// C ref: vision.c do_clear_area() — hero-centered callback walk using
// current couldsee() state. This is the common path used by litroom().
// Must be async: callback may call pline -> more -> nhgetch. See #297.
export async function do_clear_area(scol, srow, range, func, arg) {
    if (typeof func !== 'function') return;
    if (range < 1 || range > 15) {
        throw new Error(`do_clear_area: illegal range ${range}`);
    }
    if (scol !== (game.u?.ux ?? scol) || srow !== (game.u?.uy ?? srow)) {
        // C ref: vision.c do_clear_area() non-hero center forwards to view_from().
        view_from(srow, scol, null, null, null, range, func, arg);
        return;
    }
    const limits = circle_ptr(range);
    if (!limits) return;
    const maxY = Math.min(ROWNO - 1, srow + range);
    let y = Math.max(0, srow - range);
    for (; y <= maxY; y++) {
        const offset = limits[Math.abs(y - srow)];
        const minX = Math.max(1, scol - offset);
        const maxX = Math.min(COLNO - 1, scol + offset);
        for (let x = minX; x <= maxX; x++) {
            if (couldsee(x, y)) {
                await func(x, y, arg);
            }
        }
    }
}
 
export function init_vision_globals() {
    game.viz_array = cs_buf0;
    game.active_buf = 0;
    game.vis_step = 0;
    game.vis_start_col = 0;
    game.vis_start_row = 0;
    game.cs_rows = null;
    game.cs_left = null;
    game.cs_right = null;
}