All files / js getpos.js

96.2% Statements 634/659
79.33% Branches 238/300
88.88% Functions 16/18
96.2% Lines 634/659

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 66073x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 101x 101x 101x 73x 73x 73x     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 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 357x 357x 357x 357x 205x 9x 357x 73x 73x 73x 73x 73x 73x 73x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 24870x 3316x 3316x 24870x 4974x 4974x 4974x 11x 11x 3316x 4974x 4974x 24870x 4974x 4974x 24870x 6632x 6632x 6632x 6632x 6632x 781x 6632x 6632x 24870x 24870x 24870x 4974x 4974x 4974x 4974x 4974x 4942x 4942x 4974x 4942x 4974x 4938x 4974x 4974x 4934x 4974x 734x 4974x 4974x 4974x 4974x 4974x 4974x 4974x 24870x 24870x 73x 73x 73x 73x 3124x 3124x 3124x 3124x 3124x 26x 26x 3124x 3124x 73x 73x 73x 12x 12x 12x 948x 19908x 19908x 108x 108x 19908x 948x 12x 12x 12x 73x 73x 73x     73x 73x 73x 35x 35x 73x 73x 73x 850x 850x 850x 850x 850x 19x 19x 19x 850x 66x 66x 850x 850x 850x 850x 850x 850x 850x 850x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 5x 5x 2x 2x 2x 2x 2x 3x 3x 3x 5x 21x 21x 21x 21x 21x 21x 21x 21x 21x 5x 5x 5x 3x 5x 3x 3x 3x 3x 3x   5x 73x 73x 73x 736x 736x 736x 73x 73x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 73x 66x 66x 66x 66x 66x 6930x 6930x 6930x 1386x 1386x 5544x 6930x 6930x 6930x 193x 193x 6930x 66x 66x 73x 60x 60x 60x 60x 6300x 6300x 6300x 1260x 1260x 5040x 6300x 6300x 6300x 193x 193x 6300x 60x 60x 73x 68354x 68354x 68354x 68354x 68354x 68354x 40043x 40043x 40043x 31x 31x 40043x 68323x 68323x 68354x 68354x 68323x 68323x 68323x 68354x 40131x 40131x 40131x 40131x 6x 6x 40131x 68317x 68317x 68354x           68317x 68317x 68354x 40239x 40239x 40239x 40239x 40239x 9x 9x 40239x 68308x 68308x 68354x 73x 60x 60x 60x 60x 60x 60x 60x 103x 103x 103x 922x 922x 922x 68354x 46x 46x 68354x 876x 57x 14x 60x 73x 73x 73x 73x 73x 73x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 22x 22x 22x 97x 97x 98x 68x 68x 68x 97x 97x 97x 97x 97x 98x 98x 97x 97x 97x 97x 97x 971x 971x 24x 24x 24x 24x 24x 970x 850x 850x 971x 971x 971x 971x 971x 971x 971x 971x 970x 970x 970x 970x 971x 5x 5x 5x 5x 5x 5x 965x 965x 970x 970x 970x 970x 875x 875x 971x 971x 736x 736x 736x 736x 736x 736x 736x 736x 736x 736x 736x 736x 139x 139x 885x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 137x 137x 885x                 137x 137x 137x 971x 1x 1x 1x 1x 1x 1x 1x 136x 136x 885x 2x 2x 2x 2x 2x 2x 134x 971x 971x 27x 27x 27x 5x 5x 3x 3x 3x 5x 5x 24x 7x 7x 7x 27x 27x 22x 22x 22x     22x 22x 22x 22x 22x 107x 107x 107x 107x 971x 66x 60x 60x 46x 46x 46x       46x 46x 14x 66x 6x 6x 6x 6x 6x 20x 20x 20x 971x 971x 971x 96x 96x 96x 5x 5x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 98x  
// getpos.js — Position selection routines (port of getpos.c)
// Handles cursor-based position picking for targeting, looking, etc.
// No RNG consumed in any function.
 
import { game } from './gstate.js';
import { bot, docrt, flush_screen, glyph_at, terrain_sym_color, tty_clear_nhwindow } from './display.js';
import { glyph_is_cmap, glyph_is_object, glyph_to_cmap, cmap_to_glyph } from './glyph.js';
import { nhgetch } from './input.js';
import { COLNO, DOOR, ROWNO, SDOOR, VIBRATING_SQUARE, GFILTER_VIEW, TER_DETECT, TER_MAP, TER_MON, TER_OBJ, isok, NO_CURS_ON_U, OVERRIDE_MSGTYPE, SUPPRESS_HISTORY } from './const.js';
import { custompline, pline } from './pline.js';
import { lookat, do_screen_description_async } from './pager.js';
import { add_menu, add_menu_str, create_nhwindow_menu, destroy_nhwindow_menu, end_menu, select_menu } from './menu.js';
import { defsyms, S_air, S_bars, S_cloud, S_engroom, S_ice, S_ndoor, S_stone, S_tree } from './symbols.js';
import { is_cmap_corr, is_cmap_door, is_cmap_drawbridge, is_cmap_engraving, is_cmap_room, is_cmap_trap, is_cmap_wall, is_cmap_lava, is_cmap_water, pchar_sym } from './drawing.js';
import { t_at, obj_at } from './map_access.js';
import { cansee } from './vision.js';
import { is_valid_travelpt } from './hack.js';
import { GLOC_DOOR, GLOC_EXPLORE, GLOC_INTERESTING, GLOC_MONS, GLOC_OBJS, GLOC_VALID, GFILTER_AREA } from './const.js';
import { BOULDER, ROCK } from './objects.js';
 
let getpos_hilite = null;
let getpos_valid = null;
// C ref: getpos.c:40 getpos_sethilite
export function getpos_sethilite(f, g) {
    getpos_hilite = f || null;
    getpos_valid = g || null;
}
 
// C ref: getpos.c:93 mapxy_valid
export function mapxy_valid(x, y) {
    return x >= 1 && x < COLNO && y >= 0 && y < ROWNO;
}
 
// C ref: getpos.c:166 getpos_help — async (putstr)
// Displays a text window with targeting instructions, waits for dismiss.
export async function getpos_help(force, goal) {
    // C ref: getpos.c:getpos_help() — creates NHW_MENU and writes a
    // substantial putstr help block whose exact geometry affects tty
    // menu placement/dismiss events (offx/maxrow/docorner shape).
    const win = create_nhwindow_menu();
    win.textLikePrompt = true;
    win.putstrLikeWidth = true;
 
    const targetGoal = goal || 'desired location';
    const moveSkip = game.iflags?.getloc_moveskip ? 'skipping same glyphs' : '8 units at a time';
    const terrainmode = game.iflags?.terrainmode || 0;
 
    add_menu_str(win, `Use 'h', 'j', 'k', 'l' to move the cursor to ${targetGoal}.`);
    add_menu_str(win, `Use 'H', 'J', 'K', 'L' to fast-move the cursor, ${moveSkip}.`);
    add_menu_str(win, "(or prefix normal move with 'G' or 'g' to fast-move)");
    add_menu_str(win, "Or enter a background symbol (ex. '<').");
    add_menu_str(win, "Use '@' to move the cursor on yourself.");
 
    if (!terrainmode || (terrainmode & TER_MON) !== 0) {
        add_menu_str(win, "Use 'm'/'M' to move the cursor to next/previous monster.");
    }
    if (targetGoal !== 'a monster') {
        if (!terrainmode || (terrainmode & TER_OBJ) !== 0) {
            add_menu_str(win, "Use 'o'/'O' to move the cursor to next/previous object.");
        }
        if (!terrainmode || (terrainmode & TER_MAP) !== 0) {
            add_menu_str(win, "Use 'd'/'D' to move the cursor to next/previous door or doorway.");
            add_menu_str(win, "Use 'x'/'X' to move the cursor next to an unexplored location.");
            add_menu_str(win, "Use 'a'/'A' to move the cursor to anything interesting.");
        }
    }
    add_menu_str(win, "Use '*' to change fast-move mode to skipping same glyphs.");
    if (!terrainmode || (terrainmode & TER_DETECT) === 0) {
        add_menu_str(win, "Use '!' to toggle menu listing for possible targets.");
        add_menu_str(win, "Use '\"' to change the mode of limiting possible targets.");
    }
    if (!terrainmode) {
        add_menu_str(win, "Use '#' to toggle automatic description.");
        add_menu_str(win, "Type a '.' when you are at the right place.");
    }
    if (!force) {
        add_menu_str(win, "Type Space or Escape when you're done.");
    }
    add_menu_str(win, '');
    end_menu(win, '');
    await select_menu(win, 0); // PICK_NONE — just display and wait for dismiss
    destroy_nhwindow_menu(win);
}
 
// C ref: getpos.c:312 cmp_coord_distu — Chebyshev distance from hero, with
// (y then x) lexical tiebreak. NOT Euclidean — getpos picks nearest in
// king-move steps (max of |dx|,|dy|).
export function cmp_coord_distu(a, b) {
    const u = game.u;
    const d1 = Math.max(Math.abs(u.ux - a.x), Math.abs(u.uy - a.y));
    const d2 = Math.max(Math.abs(u.ux - b.x), Math.abs(u.uy - b.y));
    if (d1 !== d2) return d1 - d2;
    if (a.y !== b.y) return a.y - b.y;
    return a.x - b.x;
}
 
// C ref: getpos.c:438 gather_locs_interesting
// Returns true if (x,y) is an interesting location for the given gloc category.
// Uses the remembered glyph at (x,y). C: levl[x][y].glyph; JS: loc.glyph
// (canonical int, gbuf-cleanup Phase 6a) — cmap cells decode to an S_*
// symbol index via glyph_to_cmap.
export function gather_locs_interesting(x, y, gloc) {
    const level = game.level;
    const loc = level?.at?.(x, y);
    if (!loc) return false;
 
    // C ref: getpos.c:444 — GFILTER_VIEW only includes currently-visible cells
    const filter = game.iflags?.getloc_filter ?? 0;
    if (filter === GFILTER_VIEW && !cansee(x, y)) return false;
    // GFILTER_AREA check (gloc_filter_map): not yet ported; treat as no-op
 
    // Figure out the remembered glyph and its cmap symbol
    const mon = level.monsterAt?.(x, y) || null;
    const memG = loc.glyph;
    const isCmapMem = glyph_is_cmap(memG);
    const symidx = isCmapMem ? glyph_to_cmap(memG) : -1;
    const hasCmap = isCmapMem && symidx !== S_stone;
    const isObjMem = glyph_is_object(memG);
 
    switch (gloc) {
        default:
        case GLOC_MONS:
            // visible monster (not hero, not worm-tail)
            return !!mon && !mon.worm_tail;
        case GLOC_OBJS:
            // C checks the currently shown glyph (glyph_is_object), excluding
            // boulders/rocks.
            if (!isObjMem) return false;
            {
                const otmp = obj_at(x, y);
                if (!otmp) return false;
                return otmp.otyp !== BOULDER && otmp.otyp !== ROCK;
            }
        case GLOC_DOOR:
            if (!hasCmap) return false;
            return is_cmap_door(symidx) || is_cmap_drawbridge(symidx) || symidx === S_ndoor;
        case GLOC_EXPLORE: {
            // Walkable terrain cell (room/corr/door) adjacent to an unexplored cell
            if (!hasCmap) return false;
            const isWalkable = is_cmap_door(symidx) || is_cmap_drawbridge(symidx)
                || symidx === S_ndoor || is_cmap_room(symidx) || is_cmap_corr(symidx);
            if (!isWalkable) return false;
            return IS_UNEXPLORED_LOC(x + 1, y) || IS_UNEXPLORED_LOC(x - 1, y)
                || IS_UNEXPLORED_LOC(x, y + 1) || IS_UNEXPLORED_LOC(x, y - 1);
        }
        case GLOC_VALID:
            // No getpos_getvalid callback in JS yet; fall through
        case GLOC_INTERESTING: {
            // C ref: a cell is "interesting" if:
            //  - it's a door/drawbridge (GLOC_DOOR), OR
            //  - the shown glyph is NOT boring terrain/nothing/unexplored, OR
            //  - it's the known vibrating square.
            if (gather_locs_interesting(x, y, GLOC_DOOR)) return true;
            // Vibrating square
            const trap = t_at(x, y);
            if (trap && trap.ttyp === VIBRATING_SQUARE && trap.tseen) return true;
            // Visible monster → interesting
            if (mon) return true;
            // Object memory at this cell counts
            if (isObjMem) return true;
            if (obj_at(x, y) && loc.seenv) return true;
            // Terrain-only cell: interesting unless it's plain walkable/wall/etc
            if (!hasCmap) return false;
            const boring = is_cmap_wall(symidx)
                || symidx === S_tree || symidx === S_bars
                || symidx === S_ice || symidx === S_air || symidx === S_cloud
                || is_cmap_lava(symidx) || is_cmap_water(symidx)
                || symidx === S_ndoor
                || is_cmap_room(symidx) || is_cmap_corr(symidx);
            return !boring;
        }
    }
}
 
// C ref: getpos.c:331 IS_UNEXPLORED_LOC macro —
// cell is valid, glyph is unexplored (no remembered glyph or remembered as stone),
// and never been seen.
function IS_UNEXPLORED_LOC(x, y) {
    if (!(x >= 1 && x < COLNO && y >= 0 && y < ROWNO)) return false;
    const loc = game.level?.at?.(x, y);
    if (!loc) return true; // off-map counts as unexplored
    if (loc.seenv) return false;
    // C: IS_UNEXPLORED_LOC checks levl[x][y].glyph for stone/no-memory.
    const stoneG = cmap_to_glyph(S_stone);
    return loc.glyph == null || loc.glyph === stoneG;
}
 
// C ref: getpos.c:513 gather_locs — gather map positions matching gloc category
export function gather_locs(gloc) {
    const u = game.u;
    const points = [{ x: u.ux, y: u.uy }]; // C: garr[][0] is hero spot
    for (let x = 1; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            if (x === u.ux && y === u.uy) continue;
            if (gather_locs_interesting(x, y, gloc)) {
                points.push({ x, y });
            }
        }
    }
    points.sort(cmp_coord_distu);
    return points;
}
 
// C ref: getpos.c:557 dxdy_to_dist_descr
export function dxdy_to_dist_descr(dx, dy, cmode) {
    return '';
}
 
// C ref: getpos.c:595 coord_desc
export function coord_desc(x, y, outbuf, cmode) {
    return `<${x},${y}>`;
}
 
// C ref: getpos.c:640 auto_describe — async
export async function auto_describe(cx, cy) {
    // C ref: getpos.c:auto_describe() builds its message with
    // is_valid_travelpt() side effects before output.
    let msg = lookat(cx, cy);
    if (!msg) return;
    if (getpos_valid) {
        const ok = await getpos_valid(cx, cy);
        if (!ok) msg += ' (invalid target)';
    }
    if (game.iflags?.getloc_travelmode && !(await is_valid_travelpt(cx, cy))) {
        msg += ' (no travel path)';
    }
    await custompline(SUPPRESS_HISTORY | OVERRIDE_MSGTYPE | NO_CURS_ON_U, '%s', msg);
    game.getposx = cx;
    game.getposy = cy;
    // C ref: curs(WIN_MAP, cx, cy) before flush_screen(0)
    const disp = game?.nhDisplay;
    if (disp) disp.setCursor(cx - 1, cy + 1);
    await flush_screen(0);
}
 
// C ref: getpos.c:660 — gloc_descr[gloc] descriptions
const gloc_descr = [
    ['any monsters', 'a monster'],
    ['any objects', 'an object'],
    ['any doors or openings', 'a door or opening'],
    ['any unexplored areas', 'an unexplored area'],
];
 
// C ref: getpos.c:665 getpos_menu — show a selection menu for mMoOdDxX targets
export async function getpos_menu(ccp, gloc) {
    const garr = gather_locs(gloc);
    if (!garr || garr.length < 2) {
        // garr[0] is always the hero; need at least one non-hero target
        const filterVerb = (game.iflags?.getloc_filter === GFILTER_VIEW) ? 'see' : 'detect';
        await pline(`You cannot ${filterVerb} ${gloc_descr[gloc]?.[0] || 'anything'}.`);
        return false;
    }
 
    const tmpwin = create_nhwindow_menu();
    // Skip garr[0] (hero position)
    for (let i = 1; i < garr.length; i++) {
        const cc = { x: garr[i].x, y: garr[i].y };
        const out = {};
        const fm = { value: 'unknown' };
        await do_screen_description_async(cc, true, 0, out, fm, null);
        const firstmatch = fm.value || 'unknown';
        const coordStr = coord_desc(cc.x, cc.y, '', game.iflags?.getpos_coords || 0);
        const label = firstmatch + (coordStr ? ' ' + coordStr : '');
        add_menu(tmpwin, i + 1, 0, 0, 0, 8 /* NO_COLOR */, label);
    }
    const prompt = `Pick ${gloc_descr[gloc]?.[1] || 'a target'}${game.iflags?.getloc_travelmode ? ' for travel destination' : ''}`;
    end_menu(tmpwin, prompt);
    const picks = await select_menu(tmpwin, 1); // PICK_ONE
    destroy_nhwindow_menu(tmpwin);
    if ((picks?.count || 0) > 0 && (picks?.items?.length || 0) > 0) {
        const idx = (picks.items[0].identifier | 0) - 1;
        ccp.x = garr[idx].x;
        ccp.y = garr[idx].y;
        return true;
    }
    return false;
}
 
// C ref: getpos.c:729 truncate_to_map
export function truncate_to_map(cc, dx, dy) {
    cc.x = Math.max(1, Math.min(cc.x + dx, COLNO - 2));
    cc.y = Math.max(0, Math.min(cc.y + dy, ROWNO - 1));
}
 
// Direction key to dx,dy mapping for getpos cursor movement
function getpos_direction(ch) {
    switch (ch) {
    case 'h': case 4: return { dx: -1, dy: 0, fast: false };
    case 'j': case 2: return { dx: 0, dy: 1, fast: false };
    case 'k': case 8: return { dx: 0, dy: -1, fast: false };
    case 'l': case 6: return { dx: 1, dy: 0, fast: false };
    case 'y': case 7: return { dx: -1, dy: -1, fast: false };
    case 'u': case 9: return { dx: 1, dy: -1, fast: false };
    case 'b': case 1: return { dx: -1, dy: 1, fast: false };
    case 'n': case 3: return { dx: 1, dy: 1, fast: false };
    case 'H': return { dx: -1, dy: 0, fast: true };
    case 'J': return { dx: 0, dy: 1, fast: true };
    case 'K': return { dx: 0, dy: -1, fast: true };
    case 'L': return { dx: 1, dy: 0, fast: true };
    case 'Y': return { dx: -1, dy: -1, fast: true };
    case 'U': return { dx: 1, dy: -1, fast: true };
    case 'B': return { dx: -1, dy: 1, fast: true };
    case 'N': return { dx: 1, dy: 1, fast: true };
    // Ctrl+direction rush keys (C movecmd(..., MV_RUSH))
    case 0x08: return { dx: -1, dy: 0, fast: true };  // Ctrl-H
    case 0x0a: return { dx: 0, dy: 1, fast: true };   // Ctrl-J / LF
    case 0x0b: return { dx: 0, dy: -1, fast: true };  // Ctrl-K
    case 0x0c: return { dx: 1, dy: 0, fast: true };   // Ctrl-L
    case 0x19: return { dx: -1, dy: -1, fast: true }; // Ctrl-Y
    case 0x15: return { dx: 1, dy: -1, fast: true };  // Ctrl-U
    case 0x02: return { dx: -1, dy: 1, fast: true };  // Ctrl-B
    case 0x0e: return { dx: 1, dy: 1, fast: true };   // Ctrl-N
    default: return null;
    }
}
 
function has_matching_feature_symbol(c) {
    if (!c) return false;
    const roomEngraving = pchar_sym(S_engroom).ch;
    let k = 0;
    for (let sidx = 0; sidx < defsyms.length; sidx++) {
        // C ref: getpos.c:1048-1051
        if (is_cmap_wall(sidx) || is_cmap_room(sidx) || is_cmap_corr(sidx)
            || is_cmap_door(sidx) || sidx === S_ndoor) {
            continue;
        }
        if (c === defsyms[sidx].ch
            || c === pchar_sym(sidx).ch
            || (c === '^' && is_cmap_trap(sidx))
            || (c === roomEngraving && is_cmap_engraving(sidx))) {
            k++;
        }
    }
    return k > 0;
}
 
function matching_feature_table(c) {
    const matching = new Array(defsyms.length).fill(false);
    const roomEngraving = pchar_sym(S_engroom).ch;
    for (let sidx = 0; sidx < defsyms.length; sidx++) {
        // C ref: getpos.c:1048-1051
        if (is_cmap_wall(sidx) || is_cmap_room(sidx) || is_cmap_corr(sidx)
            || is_cmap_door(sidx) || sidx === S_ndoor) {
            continue;
        }
        if (c === defsyms[sidx].ch
            || c === pchar_sym(sidx).ch
            || (c === '^' && is_cmap_trap(sidx))
            || (c === roomEngraving && is_cmap_engraving(sidx))) {
            matching[sidx] = true;
        }
    }
    return matching;
}
 
function cell_matches_feature_symbol(c, matching, tx, ty) {
    // C pass 1: currently shown glyph (might be monster-appearance cmap).
    // glyph_at now returns a canonical int; `matching` is indexed by the
    // cmap-subset S_* so we decode via glyph_to_cmap when applicable.
    const shown = glyph_at(tx, ty);
    if (glyph_is_cmap(shown)) {
        const sym = glyph_to_cmap(shown);
        if (Number.isInteger(sym) && sym >= 0 && sym < matching.length
            && matching[sym]) {
            return true;
        }
    }
 
    const level = game.level;
    const loc = level?.at?.(tx, ty);
    if (!loc) return false;
 
    // C pass 2: remembered glyph (if hero memory and not terrainmode).
    // gbuf-cleanup: decode loc.glyph (canonical int) to cmap symidx.
    if (level?.flags?.hero_memory && glyph_is_cmap(loc.glyph)) {
        const remembered = glyph_to_cmap(loc.glyph);
        if (Number.isInteger(remembered) && remembered >= 0
            && remembered < matching.length
            && matching[remembered]) {
            return true;
        }
    }
 
    // C pass 3 special case: known vibrating square keyed by '~'
    if (c === '~') {
        const trap = t_at(tx, ty);
        if (trap && trap.ttyp === VIBRATING_SQUARE && trap.tseen) {
            return true;
        }
    }
 
    // C pass 4: actual seen terrain (back_to_glyph equivalent)
    if (loc.seenv) {
        const terrain = terrain_sym_color(loc, tx, ty);
        const terrainSym = terrain?.symidx;
        if (Number.isInteger(terrainSym) && terrainSym >= 0
            && terrainSym < matching.length
            && matching[terrainSym]) {
            return true;
        }
    }
 
    return false;
}
 
function find_feature_symbol_target(c, cx, cy) {
    const level = game.level;
    if (!level) return null;
    const matching = matching_feature_table(c);
    if (!matching.some(Boolean)) return null;
 
    for (let pass = 0; pass <= 1; pass++) {
        const loY = pass === 0 ? cy : 0;
        const hiY = pass === 0 ? ROWNO - 1 : cy;
        for (let ty = loY; ty <= hiY; ty++) {
            const loX = (pass === 0 && ty === loY) ? (cx + 1) : 1;
            const hiX = (pass === 1 && ty === hiY) ? cx : (COLNO - 1);
            for (let tx = loX; tx <= hiX; tx++) {
                if (cell_matches_feature_symbol(c, matching, tx, ty)) {
                    return { x: tx, y: ty };
                }
            }
        }
    }
    return null;
}
 
// C ref: getpos.c:771 getpos — async (main position selection loop)
// Faithful port of C's getpos(). Reads keys in a loop for cursor-based
// position selection. Returns result code:
//   -1 = cancelled (ESC), 0+ = picked (LOOK_TRADITIONAL, etc.)
export async function getpos(ccp, force, goal) {
    if (!goal) goal = 'desired location';
 
    const u = game.u;
    let cx = ccp?.x ?? (u?.ux ?? 1);
    let cy = ccp?.y ?? (u?.uy ?? 1);
    let result = 0;
    let msg_given = true;
    // C ref: getpos.c:774 mMoOdDxX_def — order matches GLOC_MONS..GLOC_VALID.
    // Pair index k → gloc = k>>1. NEXT = even, PREV = odd.
    const mMoOdDxX = 'mMoOdDxXaAzZ';
    const garr = [null, null, null, null, null, null];
    const gidx = [0, 0, 0, 0, 0, 0];
 
    // C ref: getpos.c:838 — handle_tip(TIP_GETPOS) shows a tip on first use.
    // C calls l_nhcore_call(NHCORE_GETPOS_TIP) → Lua show_getpos_tip()
    // which uses nh.text() to display a multi-line text window.
    let show_goal_msg = false;
    if (game.flags?.tips !== false && !game.context?.tips_getpos) {
        game.context = game.context || {};
        game.context.tips_getpos = true;
        // C ref: nhcore.lua:108 show_getpos_tip() — nh.text([[...]])
        // Display a text window with the tip, wait for dismiss.
        const tipWin = create_nhwindow_menu();
        add_menu_str(tipWin, 'Tip: Farlooking or selecting a map location');
        add_menu_str(tipWin, '');
        add_menu_str(tipWin, 'You are now in a "farlook" mode - the movement keys move the cursor,');
        add_menu_str(tipWin, 'not your character.  Game time does not advance.  This mode is used');
        add_menu_str(tipWin, 'to look around the map, or to select a location on it.');
        add_menu_str(tipWin, '');
        add_menu_str(tipWin, 'When in this mode, you can press ESC to return to normal game mode,');
        add_menu_str(tipWin, 'and pressing ? will show the key help.');
        end_menu(tipWin, '');
        await select_menu(tipWin, 0); // PICK_NONE — display and wait
        destroy_nhwindow_menu(tipWin);
        show_goal_msg = true; // tip has overwritten prompt in mesg window
    }
 
    // C ref: getpos.c:843 — verbose mode shows instruction hint
    if (game.flags?.verbose) {
        await pline("(For instructions type a '?')");
        msg_given = true;
    }
 
    // C ref: getpos.c:853 — position cursor and flush
    game.getposx = cx;
    game.getposy = cy;
    // C ref: curs(WIN_MAP, cx, cy) — position cursor at target
    const display = game?.nhDisplay;
    if (display) display.setCursor(cx - 1, cy + 1);
    await flush_screen(0);
    if (getpos_hilite) await getpos_hilite(true);
 
    // C ref: getpos.c:859 — main input loop
    for (;;) {
        // C ref: getpos.c:860-864 — show goal message if tip was displayed
        if (show_goal_msg) {
            await pline(`Move cursor to ${goal}:`);
            // C ref: getpos.c:862 — curs(WIN_MAP, cx, cy) after pline
            if (display) display.setCursor(cx - 1, cy + 1);
            await flush_screen(0);
            show_goal_msg = false;
        } else if ((game.iflags?.autodescribe ?? true) && !msg_given) {
            await auto_describe(cx, cy);
        }
 
        // C ref: getpos.c:860 — curs(WIN_MAP, cx, cy) before nhgetch.
        // Ensures cursor is at target for every capture point.
        if (display) display.setCursor(cx - 1, cy + 1);
        const rawCh = await nhgetch();
        const ch = typeof rawCh === 'number' ? rawCh : (typeof rawCh === 'string' ? rawCh.charCodeAt(0) : rawCh);
        const charStr = (ch >= 32 && ch < 127) ? String.fromCharCode(ch) : null;
        if (game.iflags?.autodescribe ?? true) {
            msg_given = false;
        }
 
        // C ref: getpos.c:892 — ESC cancels
        if (ch === 0x1b || ch === 'q'.charCodeAt(0)) {
            cx = -10;
            cy = -10;
            msg_given = true;
            result = -1;
            break;
        }
 
        // C ref: getpos.c:910 — pick chars: '.', ',', ';', ':'
        if (charStr === '.') { result = 0; break; } // LOOK_TRADITIONAL
        if (charStr === ',') { result = 1; break; } // LOOK_QUICK
        if (charStr === ';') { result = 2; break; } // LOOK_ONCE
        if (charStr === ':') { result = 3; break; } // LOOK_VERBOSE
 
        // C ref: getpos.c:914 — direction keys move cursor
        const dir = getpos_direction(charStr || ch);
        if (dir) {
            const cc = { x: cx, y: cy };
            const mul = dir.fast ? 8 : 1;
            truncate_to_map(cc, dir.dx * mul, dir.dy * mul);
            cx = cc.x;
            cy = cc.y;
            game.getposx = cx;
            game.getposy = cy;
            // C ref: curs(WIN_MAP, cx, cy) before flush_screen(0)
            if (display) display.setCursor(cx - 1, cy + 1);
            await flush_screen(0);
            continue;
        }
 
        // C ref: getpos.c:945 — '?' shows help, then redraws
        if (charStr === '?') {
            await getpos_help(force, goal);
            // C ref: getpos.c '?' path calls getpos_refresh() after help:
            // getpos_help(); getpos_refresh(); curs(WIN_MAP,...)
            // where getpos_refresh() performs docrt_flags(docrtRefresh).
            await docrt();
            await bot();
            if (display) display.setCursor(cx - 1, cy + 1);
            // C ref: getpos_refresh() → docrt()
            // After help dismiss, set show_goal_msg to show "Move cursor..."
            show_goal_msg = true;
            continue;
        }
 
        // C ref: getpos.c:962-970 — NHKF_GETPOS_AUTODESC ('#' by default)
        if (charStr === '#') {
            game.iflags = game.iflags || {};
            const autodesc = (game.iflags.autodescribe !== false);
            game.iflags.autodescribe = !autodesc;
            await pline(`Automatic description ${game.flags?.verbose ? 'of features under cursor ' : ''}is ${game.iflags.autodescribe ? 'on' : 'off'}.`);
            if (!game.iflags.autodescribe) show_goal_msg = true;
            msg_given = true;
            continue;
        }
 
        // C ref: getpos.c:1136 — when not forced, space exits targeting with
        // "Done." and returns success code 0.
        if (!force && ch === 0x20) {
            await pline('Done.');
            msg_given = false; // C: suppress clear_nhwindow on exit
            cx = -1;
            cy = 0;
            result = 0;
            break;
        }
 
        // C ref: getpos.c:989 — NHKF_GETPOS_MENU ('!' by default)
        if (charStr === '!') {
            game.iflags = game.iflags || {};
            game.iflags.getloc_usemenu = !game.iflags.getloc_usemenu;
            await pline(`${game.iflags.getloc_usemenu ? 'Using' : 'Not using'} a menu to show possible targets${game.iflags.getloc_usemenu ? " for 'm|M', 'o|O', 'd|D', and 'x|X'" : ''}.`);
            msg_given = true;
            continue;
        }
 
        const cp = mMoOdDxX.indexOf(charStr || '');
        if (cp >= 0) {
            const gloc = cp >> 1; // 0:mon 1:obj 2:door 3:unexplored
            // C ref: getpos.c:1016 — menu mode shows a selection menu
            if (game.iflags?.getloc_usemenu) {
                const tmpcrd = { x: 0, y: 0 };
                if (await getpos_menu(tmpcrd, gloc)) {
                    cx = tmpcrd.x;
                    cy = tmpcrd.y;
                }
                continue;
            }
            if (!garr[gloc]) {
                garr[gloc] = gather_locs(gloc);
                gidx[gloc] = 0;
            }
            const count = garr[gloc]?.length || 0;
            if (count > 0) {
                if ((cp & 1) === 0) {
                    gidx[gloc] = (gidx[gloc] + 1) % count;
                } else {
                    gidx[gloc] = (gidx[gloc] - 1 + count) % count;
                }
                cx = garr[gloc][gidx[gloc]].x;
                cy = garr[gloc][gidx[gloc]].y;
            }
            continue;
        }
 
        // C ref: getpos.c:1040-1130 — non-direction key path.
        // If key is a recognized feature symbol, search map and report
        // not-found when no match exists. Otherwise report unknown direction.
        if (charStr && !'\x1b \r\n'.includes(charStr)) {
            if (has_matching_feature_symbol(charStr)) {
                const found = find_feature_symbol_target(charStr, cx, cy);
                if (found) {
                    cx = found.x;
                    cy = found.y;
                    if (msg_given) {
                        await tty_clear_nhwindow('message');
                        msg_given = false;
                    }
                    continue;
                }
                await pline(`Can't find dungeon feature '${charStr}'.`);
            } else {
                const note = !force
                    ? 'aborted'
                    : "use 'h', 'j', 'k', 'l' or '.'";
                await pline(`Unknown direction: '${charStr}' (${note}).`);
            }
            msg_given = true;
            continue;
        }
 
        // Unrecognized key — ignore and continue
    }
 
    // C ref: getpos.c:1156 — on exit, clear message if msg_given
    if (msg_given) {
        await tty_clear_nhwindow('message');
    }
 
    // C ref: getpos.c:1158-1159 — store result coordinates
    if (ccp) {
        ccp.x = cx;
        ccp.y = cy;
    }
 
    game.getposx = 0;
    game.getposy = 0;
    if (getpos_hilite) await getpos_hilite(false);
    getpos_sethilite(null, null);
    return result;
}