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 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 | 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 59x 59x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 97683x 97683x 97683x 97683x 97683x 23x 2x 2x 2x 23x 97683x 43679x 43679x 23063x 23063x 14409x 14409x 16532x 16532x 97683x 149x 48x 44x 44x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 43679x 10830x 43679x 43679x 43679x 43679x 43679x 16577x 43679x 43679x 23063x 23063x 23063x 23063x 3531x 23063x 14409x 14409x 14409x 7233x 7233x 3x 3x 1x 1x 5x 5x 1x 1x 1x 1x 3626x 3626x 3626x 3626x 3626x 3626x 3539x 3539x 3539x 3539x 3539x 3539x 16532x 8263x 8263x 8263x 8263x 8263x 8263x 8263x 8263x 8269x 16532x 26911x 26911x 430576x 430576x 430576x 52736x 430576x 546x 546x 546x 147x 48x 2x 2x 2x 119920x 59930x 59930x 199x 199x 199x 300x 300x 300x 300x 300x 300x 300x 300x 43784x 43784x 59990x 14x 11010048x 6657x 6657x 6657x 6657x 2219x 2219x 2219x 2219x 2219x 2219x 2219x 2219x 2219x 2219x 2219x 2219x 15691200x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 546x 139776x 139776x 2236416x 2236416x 2236416x 2236416x 2236416x 2236416x 2236416x 2236416x 139776x 2236416x 2236416x 2236416x 546x 546x 546x 546x 546x 10x 14487x 546x 546x 546x 147x 147x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 992x 992x 992x 992x 992x 992x 8x 1273x 1273x 1306x 1306x 167x 167x 52177x 1139x 1139x 1139x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1827x 1676x 1676x 151x 86x 86x 65x 65x 79700x 2219x 1627x 1537x 12x 9x 7x 7x 7x 7x 7x 7x 7x 147x 3087x 3087x 2219x 2219x 7x 7x 7x 7x 7x 7x 44274x 44274x 44274x 102344x 102344x 102344x 28621x 28621x 28621x 28621x 7667x 7667x 7667x 61336x 36288x 93040x 1816x 1816x 1176x 1176x 1176x 640x 91224x 93040x 1178x 18736x 1178x 1006x 15984x 5974503x 15048x 15048x 97683x 40039x 15219x 13232x 13232x 13232x 5565x 5565x 7667x 13232x 13232x 12013x 13232x 2x 76x 16407906x 307394x 307394x 291009x 16385x 307394x 16100512x 16100512x 16100512x 16100512x 33158x 16100512x 16100512x 960496x 960496x 960496x 960496x 1779x 1779x 1779x 1779x 960496x 10288x 10288x 10288x 1740x 1740x 960496x 960796x 960796x 3520x 3520x 3520x 3520x 24719x 24719x 24719x 24719x 24719x 24719x 24719x 24719x 85002x 85002x 85002x 85002x 85002x 85002x 85002x 244461x 244461x 244461x 244461x 244461x 60283x 244461x 77645x 166816x 244461x 196493x 196493x 40739x 155754x 244461x 60283x 244461x 462x 244461x 244461x 375x 244461x 25095x 25095x 671x 671x 24424x 244461x 24719x 24719x 24719x 24719x 24719x 24719x 244461x 244461x 244461x 244461x 16347492x 948015x 948015x 232444x 232444x 232444x 232444x 232444x 232444x 232444x 232444x 715571x 231647x 715571x 1217638x 1217638x 1217638x 754752x 754752x 462886x 462886x 13220956x 13220956x 33040115x 33040115x 33040115x 6136135x 26903980x 26903980x 33040115x 244516x 26903980x 26903980x 421554x 26903980x 231656x 231656x 26903980x 26903980x 26903980x 26903980x 8537842x 8537842x 8401096x 8401096x 26054x 8537842x 7877469x 7877469x 6937867x 964004x 964004x 964004x 770245x 770245x 964004x 5973863x 7877469x 93040x 26903980x 7738983x 26903980x 26903980x 231680x 231680x 25557x 24720x 25557x 25557x 26903980x 231680x 24736x 24736x 231680x 26903980x 244461x 244461x 244461x 26659519x 26903980x 26903980x 593x 593x 130x 130x 130x 768x 800080x 768x 768x 768x 768x 768x 768x 768x 768x 413x 43573014x 43573014x 43576273x 1632x 1632x 43574641x 1627x 1627x 1627x 43573014x 151511x 151511x 151511x 173x 159x 159x 130x 130x 130x 18x 18x 18x 18x 7x | import { PipelineLag, PipelineLength, Teletext } from "./teletext.js";
import { BbcDefaultPalette as NulaDefaultPalette } from "./bbc-palette.js";
import { Video6847 } from "./6847.js";
import { encodeLineGrid, texelsPerPixel } from "./video-filters/pixel-grid.js";
import { makeFast32 } from "./binary.js";
import {
CursorInvert,
OPAQUE_BLACK,
PendingCursor,
PendingOffsetShift,
PendingRowBias,
PreferredDrain,
VideoDrain,
} from "./video-drain.js";
const noop = () => {};
export const VDISPENABLE = 1 << 0;
export const HDISPENABLE = 1 << 1;
const SKEWDISPENABLE = 1 << 2;
const SCANLINEDISPENABLE = 1 << 3;
const USERDISPENABLE = 1 << 4;
const FRAMESKIPENABLE = 1 << 5;
export const EVERYTHINGENABLED =
VDISPENABLE | HDISPENABLE | SKEWDISPENABLE | SCANLINEDISPENABLE | USERDISPENABLE | FRAMESKIPENABLE;
export { OPAQUE_BLACK };
const OPAQUE_WHITE = 0xffffffff;
export const MinPaintedFrameRows = 64;
// How far off nominal (4433618.75 Hz) the subcarrier runs, as measured on Matt's
// BBC Master 128. Exactly nominal, a 312-line frame advances the subcarrier by
// half a cycle to four decimal places, so the cross-colour left by the decoder
// inverts every frame; an offset of this order makes it crawl instead (#962).
const PalSubcarrierOffsetHz = 239;
const PalNominalSubcarrierHz = 4433618.75;
const PalLineHz = 15625;
export const PalCyclesPerLine = (PalNominalSubcarrierHz + PalSubcarrierOffsetHz) / PalLineHz;
export const PalPhasePerLine = PalCyclesPerLine % 1;
// By the system VIA's IC32 screen size bits, in the 2K units of screen address bits 11-14.
export const HwScrollSubtract = [8, 4, 10, 5];
// The shader takes a line's parity from the hsync count; the modulus only keeps it bounded.
export const LineCountPeriod = 2500;
const BitmapXPerClock = 8;
/**
* @typedef {object} BeamPosition
* @property {number} line - the TV line, counted from the frame's start
* @property {number} frameCycle - the cycles run since the frame started
* @property {boolean} inVSync - whether vsync is asserted
* @property {{row: number, scanline: number, column: number} | null} crtc - the 6845's counters, on a machine with one
*/
// Three vsyncs finish the field under way and paint both of an interlaced picture's after it.
const TracedVSyncs = 3;
const TraceStepClocks = 1024;
// The TV flies back after 384 lines with or without a vsync, and a line is at most 256 1MHz characters of two clocks.
const MostTracedClocks = TracedVSyncs * 384 * 256 * 2;
////////////////////
// VideoNULA - programmable 12-bit RGB palette extension (RobC hardware mod).
// Reference: b-em src/video.c (stardot/b-em).
// Addresses &FE22 (control) and &FE23 (palette) via 2-byte write protocol.
////////////////////
// ULA interface (includes NULA programmable palette support)
class Ula {
constructor(video, hasVideoNula, onMissingVideoNula) {
this.video = video;
this.hasVideoNula = hasVideoNula;
this.onMissingVideoNula = hasVideoNula ? null : onMissingVideoNula;
// NULA state
this.collook = new Uint32Array(16);
this.flash = new Uint8Array(8);
this.paletteWriteFlag = false;
this.paletteFirstByte = 0;
this.paletteMode = 0;
this.horizontalOffset = 0;
this.leftBlank = 0;
// A stock ULA decodes only A0.
this.disabled = !hasVideoNula;
this.attributeMode = 0;
this.attributeText = 0;
this.reset();
}
powerOn() {
this.disabled = !this.hasVideoNula;
this.reset();
}
reset() {
this.collook.set(NulaDefaultPalette);
this.flash.fill(1);
this.paletteWriteFlag = false;
this.paletteFirstByte = 0;
this.paletteMode = 0;
this.horizontalOffset = 0;
this.leftBlank = 0;
this.attributeMode = 0;
this.attributeText = 0;
// Note: disabled is NOT cleared by reset (matches b-em behaviour).
// Recompute rendered palette so any custom NULA colours are flushed.
this._recomputeUlaPal(!!(this.video.ulactrl & 1));
// Rebuild MODE 7 teletext colours from the restored default palette.
this.video.teletext.rebuildColours(this.collook);
}
write(addr, val) {
addr |= 0;
val |= 0;
this.video.renderPending();
let reg = addr & 3;
// When NULA is disabled, mask off bit 1 so &FE22/&FE23 become &FE20/&FE21.
if (reg >= 2 && this.disabled) {
// Not the B's mirrors from &FE26 up, where a probe for the Master's 1770 would land.
if (this.onMissingVideoNula && (addr & 0xf) < 4) {
const notify = this.onMissingVideoNula;
this.onMissingVideoNula = null;
notify();
}
reg &= ~2;
}
switch (reg) {
case 0:
this._writeControl(val);
break;
case 1:
this._writePalette(val);
break;
case 2:
this._writeNulaControl(val);
break;
case 3:
this._writeNulaPalette(val);
break;
}
this.video.repaintSecondHalfOfCell();
}
snapshotState() {
return {
collook: this.collook.slice(),
flash: this.flash.slice(),
paletteWriteFlag: this.paletteWriteFlag,
paletteFirstByte: this.paletteFirstByte,
paletteMode: this.paletteMode,
horizontalOffset: this.horizontalOffset,
leftBlank: this.leftBlank,
disabled: this.disabled,
attributeMode: this.attributeMode,
attributeText: this.attributeText,
};
}
restoreState(state) {
if (!this.hasVideoNula) {
this._recomputeUlaPal(!!(this.video.ulactrl & 1));
return;
}
this.collook.set(state.collook);
this.flash.set(state.flash);
this.paletteWriteFlag = state.paletteWriteFlag;
this.paletteFirstByte = state.paletteFirstByte;
this.paletteMode = state.paletteMode;
this.horizontalOffset = state.horizontalOffset;
this.leftBlank = state.leftBlank;
this.disabled = state.disabled;
this.attributeMode = state.attributeMode;
this.attributeText = state.attributeText;
this._recomputeUlaPal(!!(this.video.ulactrl & 1));
this.video.teletext.rebuildColours(this.collook);
}
// ULA control register (&FE20).
_writeControl(val) {
if ((this.video.ulactrl ^ val) & 1) {
// Flash state has changed - recompute all palette entries.
this._recomputeUlaPal(!!(val & 1));
}
this.video.ulactrl = val;
this.video.pixelsPerChar = val & 0x10 ? 8 : 16;
this.video.halfClock = !(val & 0x10);
const newMode = (val >>> 2) & 3;
if (newMode !== this.video.ulaMode) {
this.video.ulaMode = newMode;
}
this.video.teletextMode = !!(val & 2);
this.video.updateLineGridUla();
}
// ULA palette register (&FE21).
_writePalette(val) {
const index = (val >>> 4) & 0xf;
this.video.actualPal[index] = val & 0xf;
// Default: XOR lower 3 bits with 7 for steady colour.
let colour = this.collook[(val & 0xf) ^ 7];
// Flash override: if flash bit set, flash globally enabled, and per-colour flash active.
if (val & 8 && this.video.ulactrl & 1 && this.flash[(val & 7) ^ 7]) {
colour = this.collook[val & 0xf];
}
this.video.ulaPal[index] = colour;
}
// NULA control register (&FE22).
_writeNulaControl(val) {
const reg = (val >>> 4) & 0xf;
const param = val & 0xf;
switch (reg) {
case 1:
this.paletteMode = param & 1;
break;
case 2:
this.horizontalOffset = param & 7;
break;
case 3:
this.leftBlank = param & 0xf;
break;
case 4:
this.reset();
break;
case 5:
this.disabled = true;
break;
case 6:
this.attributeMode = param & 3;
break;
case 7:
this.attributeText = param & 1;
break;
case 8:
this.flash[0] = param & 8 ? 1 : 0;
this.flash[1] = param & 4 ? 1 : 0;
this.flash[2] = param & 2 ? 1 : 0;
this.flash[3] = param & 1 ? 1 : 0;
this._recomputeUlaPal(!!(this.video.ulactrl & 1));
break;
case 9:
this.flash[4] = param & 8 ? 1 : 0;
this.flash[5] = param & 4 ? 1 : 0;
this.flash[6] = param & 2 ? 1 : 0;
this.flash[7] = param & 1 ? 1 : 0;
this._recomputeUlaPal(!!(this.video.ulactrl & 1));
break;
// Regs 14 (border colour) and 15 (blank colour) are stubbed - rendering not yet implemented.
}
}
// NULA palette register (&FE23) - 2-byte write protocol.
_writeNulaPalette(val) {
if (this.paletteWriteFlag) {
const c = (this.paletteFirstByte >>> 4) & 0xf;
const r = this.paletteFirstByte & 0x0f;
const g = (val >>> 4) & 0x0f;
const b = val & 0x0f;
// Expand 4-bit channels to 8-bit by duplicating the nibble.
// Store in ABGR format (Uint32Array on little-endian = canvas RGBA).
this.collook[c] = 0xff000000 | ((b | (b << 4)) << 16) | ((g | (g << 4)) << 8) | (r | (r << 4));
// Colours 8-15 default to solid (non-flashing) when programmed.
if (c >= 8) this.flash[c - 8] = 0;
// Recompute all rendered palette entries from current state.
this._recomputeUlaPal(!!(this.video.ulactrl & 1));
// MODE 7 teletext uses its own colour lookup; rebuild when a base colour changes.
if (c < 8) this.video.teletext.rebuildColours(this.collook);
} else {
this.paletteFirstByte = val;
}
this.paletteWriteFlag = !this.paletteWriteFlag;
}
// Recompute all 16 ulaPal entries from actualPal + NULA collook + flash state.
// Follows b-em's palette recomputation logic exactly.
_recomputeUlaPal(flashEnabled) {
const video = this.video;
for (let i = 0; i < 16; ++i) {
const palVal = video.actualPal[i];
let colour = this.collook[(palVal & 0xf) ^ 7];
if (palVal & 8 && flashEnabled && this.flash[(palVal & 7) ^ 7]) {
colour = this.collook[palVal & 0xf];
}
video.ulaPal[i] = colour;
}
}
}
////////////////////
// CRTC interface
class Crtc {
constructor(video) {
this.video = video;
this.curReg = 0;
this.crtcmask = new Uint8Array([
0xff, 0xff, 0xff, 0xff, 0x7f, 0x1f, 0x7f, 0x7f, 0xf3, 0x1f, 0x7f, 0x1f, 0x3f, 0xff, 0x3f, 0xff, 0x3f, 0xff,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
}
snapshotState() {
return { curReg: this.curReg };
}
restoreState(state) {
this.curReg = state.curReg;
}
read(addr) {
Iif (!(addr & 1)) return 0;
switch (this.curReg) {
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
return this.video.regs[this.curReg];
}
return 0;
}
write(addr, val) {
if (addr & 1) {
this.video.regs[this.curReg] = val & this.crtcmask[this.curReg];
switch (this.curReg) {
case 3:
this.video.hpulseWidth = val & 0x0f;
this.video.vpulseWidth = (val & 0xf0) >>> 4;
break;
case 8: {
this.video.renderPending();
this.video.interlacedSyncAndVideo = (val & 3) === 3;
this.video.updateVSync();
const skew = (val & 0x30) >>> 4;
if (skew < 3) {
this.video.displayEnableSkew = skew;
this.video.dispEnableSet(USERDISPENABLE);
} else E{
this.video.dispEnableClear(USERDISPENABLE);
}
break;
}
case 14:
case 15:
this.video.cursorPos = (this.video.regs[15] | (this.video.regs[14] << 8)) & 0x3fff;
break;
}
} else this.curReg = val & 31;
}
}
////////////////////
// Misc support functions
function debugCopyFb(dest, src) {
for (let i = 0; i < 1024 * 768; ++i) {
dest[i] = src[i];
}
}
function lerp1(a, b, alpha) {
let val = (b - a) * alpha + a;
Iif (val < 0) val = 0;
Iif (val > 255) val = 255;
return val;
}
function lerp(col1, col2, alpha) {
Iif (alpha < 0) alpha = 0;
Iif (alpha > 1) alpha = 1;
const r1 = (col1 >>> 16) & 0xff;
const g1 = (col1 >>> 8) & 0xff;
const b1 = (col1 >>> 0) & 0xff;
const r2 = (col2 >>> 16) & 0xff;
const g2 = (col2 >>> 8) & 0xff;
const b2 = (col2 >>> 0) & 0xff;
const red = lerp1(r1, r2, alpha);
const green = lerp1(g1, g2, alpha);
const blue = lerp1(b1, b2, alpha);
return (red << 16) | (green << 8) | blue;
}
function table4bppOffset(ulamode, byte) {
return (ulamode << 12) | (byte << 4);
}
////////////////////
// The video class
export class Video {
constructor(
isMaster,
framebufferPixels,
paint_ext_param,
{ isAtom = false, hasVideoNula = false, onMissingVideoNula = null, drainKind } = {},
) {
this.isMaster = isMaster;
this.drain = new VideoDrain(framebufferPixels, drainKind ?? PreferredDrain);
this.fb32 = this.drain.fb32;
this.collook = makeFast32(
new Uint32Array([
0xff000000, 0xff0000ff, 0xff00ff00, 0xff00ffff, 0xffff0000, 0xffff00ff, 0xffffff00, 0xffffffff,
]),
);
this.screenAddrSubtract = new Uint8Array(HwScrollSubtract);
this.cursorTable = new Uint8Array([0x00, 0x00, 0x00, 0x80, 0x40, 0x20, 0x20]);
this.cursorFlashMask = new Uint8Array([0x00, 0x00, 0x08, 0x10]);
this.regs = new Uint8Array(32);
this.bitmapX = 0;
this.bitmapY = 0;
// The bitmapX the beam would be at had no hsync since the last flyback sent it back.
this.frameStartX = 0;
this.oddClock = false;
this.frameCount = 0;
this.hsyncCount = 0;
// Where the subcarrier is, in cycles, at the start of the current line.
this.subcarrierPhase = 0;
// The hsyncCount and subcarrier phase in effect while framebuffer rows 0 and 1 were
// drawn: row r was drawn during line lineBase[r & 1] + (r >> 1), and its phase is
// phaseBase[r & 1] plus PalPhasePerLine per line after it.
this.lineBaseEven = 0;
this.lineBaseOdd = 0;
this.phaseBaseEven = 0;
this.phaseBaseOdd = 0;
this.paintsAfresh = false;
this.doEvenFrameLogic = true;
this.isEvenRender = true;
this.lastRenderWasEven = false;
this.firstScanline = true;
this.inHSync = false;
this.inVSync = false;
this.inLineVSync = false;
this.inHalfLineVSync = false;
this.hadVSyncThisRow = false;
this.hadHalfLineVSyncThisRow = false;
this.checkVertAdjust = false;
this.endOfMainLatched = false;
this.endOfVertAdjustLatched = false;
this.endOfFrameLatched = false;
this.inVertAdjust = false;
this.inDummyRaster = false;
this.hpulseWidth = 0;
this.vpulseWidth = 0;
this.hpulseCounter = 0;
this.vpulseCounter = 0;
this.dispEnabled = FRAMESKIPENABLE;
this.horizCounter = 0;
this.vertCounter = 0;
this.scanlineCounter = 0;
this.vertAdjustCounter = 0;
this.addr = 0;
this.lineStartAddr = 0;
this.nextLineStartAddr = 0;
this.ulactrl = 0;
this.pixelsPerChar = 8;
this.halfClock = false;
this.ulaMode = 0;
this.teletextMode = false;
this.displayEnableSkew = 0;
this.ulaPal = makeFast32(new Uint32Array(16));
this.actualPal = new Uint8Array(16);
this.teletext = new Teletext();
this.cursorOn = false;
this.cursorOff = false;
this.cursorOnThisFrame = false;
this.cursorDrawIndex = 0;
this.cursorInvertedOffset = -1;
this.cursorPos = 0;
this.cellData = 0;
this.interlacedSyncAndVideo = false;
this.doubledScanlines = true;
this.frameSkipCount = 0;
this.screenSubtract = 0;
// Describes the logical pixel grid of each framebuffer row: how many
// texels wide and tall one BBC pixel is on that line. Display filters
// need this to see the picture as pixels rather than as raster samples;
// see video-filters/pixel-grid.js. One byte per row, written as each
// character cell renders, so a mode change between rows is recorded
// faithfully. A row whose mode changes part way along keeps only the
// last mode on it — enough for a raster split, not for a mid-line one.
this.lineGrid = this.drain.lineGrid;
this.teletext.setOutput(this.drain);
this.lineGridUla = 0;
this.lineGridUlaDoubled = 0;
this.updateLineGridUla();
this.pendingCells = this.drain.records;
this.pendingCount = 0;
this.topBorder = 12;
this.bottomBorder = 13;
this.leftBorder = 5 * 16;
this.rightBorder = 3 * 16;
this.paint_ext = paint_ext_param;
this.debugPrevScreen = null;
this.table4bpp = (() => {
const t = this.drain.table4bpp;
let i, b, temp, left;
for (b = 0; b < 256; ++b) {
temp = b;
for (i = 0; i < 16; ++i) {
left = 0;
if (temp & 2) left |= 1;
if (temp & 8) left |= 2;
if (temp & 32) left |= 4;
if (temp & 128) left |= 8;
t[table4bppOffset(3, b) + i] = left;
temp <<= 1;
temp |= 1;
}
for (i = 0; i < 16; ++i) {
t[table4bppOffset(2, b) + i] = t[table4bppOffset(3, b) + (i >>> 1)];
t[table4bppOffset(1, b) + i] = t[table4bppOffset(3, b) + (i >>> 2)];
t[table4bppOffset(0, b) + i] = t[table4bppOffset(3, b) + (i >>> 3)];
}
}
return t;
})();
this.crtc = new Crtc(this);
this.ula = new Ula(this, hasVideoNula, onMissingVideoNula);
// Atom: attach the MC6847 VDG and use its polltime
this.video6847 = null;
if (isAtom) {
this.video6847 = new Video6847(this);
this.polltime = (clocks) => this.video6847.polltime(clocks);
}
this.reset(null);
this.clearPaintBuffer();
this.paint();
}
snapshotState() {
this.renderPending();
return {
regs: this.regs.slice(),
bitmapX: this.bitmapX,
bitmapY: this.bitmapY,
frameStartX: this.frameStartX,
oddClock: this.oddClock,
frameCount: this.frameCount,
hsyncCount: this.hsyncCount,
subcarrierPhase: this.subcarrierPhase,
lineBaseEven: this.lineBaseEven,
lineBaseOdd: this.lineBaseOdd,
phaseBaseEven: this.phaseBaseEven,
phaseBaseOdd: this.phaseBaseOdd,
doEvenFrameLogic: this.doEvenFrameLogic,
isEvenRender: this.isEvenRender,
lastRenderWasEven: this.lastRenderWasEven,
firstScanline: this.firstScanline,
inHSync: this.inHSync,
inVSync: this.inVSync,
inLineVSync: this.inLineVSync,
inHalfLineVSync: this.inHalfLineVSync,
hadVSyncThisRow: this.hadVSyncThisRow,
hadHalfLineVSyncThisRow: this.hadHalfLineVSyncThisRow,
checkVertAdjust: this.checkVertAdjust,
endOfMainLatched: this.endOfMainLatched,
endOfVertAdjustLatched: this.endOfVertAdjustLatched,
endOfFrameLatched: this.endOfFrameLatched,
inVertAdjust: this.inVertAdjust,
inDummyRaster: this.inDummyRaster,
hpulseWidth: this.hpulseWidth,
vpulseWidth: this.vpulseWidth,
hpulseCounter: this.hpulseCounter,
vpulseCounter: this.vpulseCounter,
dispEnabled: this.dispEnabled,
horizCounter: this.horizCounter,
vertCounter: this.vertCounter,
scanlineCounter: this.scanlineCounter,
vertAdjustCounter: this.vertAdjustCounter,
addr: this.addr,
lineStartAddr: this.lineStartAddr,
nextLineStartAddr: this.nextLineStartAddr,
ulactrl: this.ulactrl,
pixelsPerChar: this.pixelsPerChar,
halfClock: this.halfClock,
ulaMode: this.ulaMode,
teletextMode: this.teletextMode,
displayEnableSkew: this.displayEnableSkew,
ulaPal: this.ulaPal.slice(),
actualPal: this.actualPal.slice(),
cursorOn: this.cursorOn,
cursorOff: this.cursorOff,
cursorOnThisFrame: this.cursorOnThisFrame,
cursorDrawIndex: this.cursorDrawIndex,
cursorPos: this.cursorPos,
interlacedSyncAndVideo: this.interlacedSyncAndVideo,
screenSubtract: this.screenSubtract,
ula: this.ula.snapshotState(),
crtc: this.crtc.snapshotState(),
teletext: this.teletext.snapshotState(),
...(this.video6847 ? { video6847: this.video6847.snapshotState() } : {}),
};
}
restoreState(state) {
this.renderPending();
this.regs.set(state.regs);
this.bitmapX = state.bitmapX;
this.bitmapY = state.bitmapY;
this.frameStartX = state.frameStartX ?? state.bitmapX;
this.oddClock = state.oddClock;
this.frameCount = state.frameCount;
this.hsyncCount = state.hsyncCount ?? 0;
this.subcarrierPhase = state.subcarrierPhase ?? 0;
this.lineBaseEven = state.lineBaseEven ?? 0;
this.lineBaseOdd = state.lineBaseOdd ?? 0;
this.phaseBaseEven = state.phaseBaseEven ?? 0;
this.phaseBaseOdd = state.phaseBaseOdd ?? 0;
this.doEvenFrameLogic = state.doEvenFrameLogic;
this.isEvenRender = state.isEvenRender;
this.lastRenderWasEven = state.lastRenderWasEven;
this.firstScanline = state.firstScanline;
this.inHSync = state.inHSync;
this.inVSync = state.inVSync;
this.inLineVSync = state.inLineVSync ?? state.inVSync;
this.inHalfLineVSync = state.inHalfLineVSync ?? state.inVSync;
this.hadVSyncThisRow = state.hadVSyncThisRow;
this.hadHalfLineVSyncThisRow = state.hadHalfLineVSyncThisRow ?? state.hadVSyncThisRow;
// The next paint replaces the picture rather than following on from it.
this.paintsAfresh = true;
this.checkVertAdjust = state.checkVertAdjust;
this.endOfMainLatched = state.endOfMainLatched;
this.endOfVertAdjustLatched = state.endOfVertAdjustLatched;
this.endOfFrameLatched = state.endOfFrameLatched;
this.inVertAdjust = state.inVertAdjust;
this.inDummyRaster = state.inDummyRaster;
this.hpulseWidth = state.hpulseWidth;
this.vpulseWidth = state.vpulseWidth;
this.hpulseCounter = state.hpulseCounter;
this.vpulseCounter = state.vpulseCounter;
this.dispEnabled = state.dispEnabled;
this.horizCounter = state.horizCounter;
this.vertCounter = state.vertCounter;
this.scanlineCounter = state.scanlineCounter;
this.vertAdjustCounter = state.vertAdjustCounter;
this.addr = state.addr;
this.lineStartAddr = state.lineStartAddr;
this.nextLineStartAddr = state.nextLineStartAddr;
this.ulactrl = state.ulactrl;
this.pixelsPerChar = state.pixelsPerChar;
this.halfClock = state.halfClock;
this.ulaMode = state.ulaMode;
this.teletextMode = state.teletextMode;
// Derived from the above, so it is recomputed rather than snapshotted.
this.updateLineGridUla();
this.displayEnableSkew = state.displayEnableSkew;
this.actualPal.set(state.actualPal);
this.cursorOn = state.cursorOn;
this.cursorOff = state.cursorOff;
this.cursorOnThisFrame = state.cursorOnThisFrame;
this.cursorInvertedOffset = -1;
this.cellData = 0;
this.cursorDrawIndex = state.cursorDrawIndex;
this.cursorPos = state.cursorPos;
this.interlacedSyncAndVideo = state.interlacedSyncAndVideo;
this.screenSubtract = state.screenSubtract;
this.ula.restoreState(state.ula);
this.crtc.restoreState(state.crtc);
this.teletext.restoreState(state.teletext);
if (this.video6847 && state.video6847) this.video6847.restoreState(state.video6847);
// Restore ulaPal after ULA restore, since ULA recomputation may overwrite it. A stock ULA keeps
// its recomputation, as one saved with a NULA fitted may hold NULA colours.
if (this.ula.hasVideoNula) this.ulaPal.set(state.ulaPal);
}
reset(cpu, via, hard) {
this.renderPending();
this.cpu = cpu;
this.sysvia = via;
if (via) via.cb2changecallback = this.cb2changed.bind(this);
if (hard) this.ula.powerOn();
if (this.video6847 && cpu) {
this.video6847.reset(cpu, cpu.atomppia);
}
}
paint() {
this.renderPending();
this.paint_ext(this.leftBorder, this.topBorder, 1024 - this.rightBorder, 625 - this.bottomBorder);
}
clearPaintBuffer() {
if (this.video6847) this.drain.markAllDrawn();
// The line grid is cleared exactly where the next field's pixels go: when it
// does not double lines, the other field's rows survive, and so must their grid.
if (!this.doublesLines()) {
const parity = this.frameCount & 1;
this.drain.clearDrawn(parity);
for (let line = parity; line < 625; line += 2) this.lineGrid[line] = 0;
} else {
this.drain.clearDrawn(0);
this.drain.clearDrawn(1);
this.lineGrid.fill(0);
}
}
flyback() {
this.renderPending();
const painting = this.bitmapY >= MinPaintedFrameRows && this.dispEnabled & FRAMESKIPENABLE;
if (painting) this.paint();
// The clock that brought the flyback is the frame's first.
this.frameStartX = this.bitmapX - BitmapXPerClock;
// Decided per field, before the clear: the CRTC frames of one field can
// alternate parity.
this.lastRenderWasEven = this.isEvenRender;
this.isEvenRender = !(this.frameCount & 1);
if (painting) this.clearPaintBuffer();
this.dispEnabled &= ~FRAMESKIPENABLE;
let enable = FRAMESKIPENABLE;
Iif (this.frameSkipCount > 1) {
if (this.frameCount % this.frameSkipCount) enable = 0;
}
this.dispEnabled |= enable;
this.cursorInvertedOffset = -1;
// Interlace even frame fires vsync midway through a scanline.
const oddField = !!(this.regs[8] & 1) && !!(this.frameCount & 1);
this.bitmapY = oddField ? -1 : 0;
// The even field draws the rest of the vsync line on row 0; the odd field's first row
// is the first hsync after it.
const firstRowLine = (this.hsyncCount + (oddField ? 1 : 0)) % LineCountPeriod;
const firstRowPhase = oddField ? (this.subcarrierPhase + PalPhasePerLine) % 1 : this.subcarrierPhase;
if (this.doublesLines()) {
this.lineBaseEven = this.lineBaseOdd = firstRowLine;
this.phaseBaseEven = this.phaseBaseOdd = firstRowPhase;
} else if (oddField) {
this.lineBaseOdd = firstRowLine;
this.phaseBaseOdd = firstRowPhase;
} else {
this.lineBaseEven = firstRowLine;
this.phaseBaseEven = firstRowPhase;
}
}
// In an interlace mode with R6>R4 we get stuck painting just an odd or even
// frame, so scanlines are doubled up to avoid a ghost half frame.
doublesLines() {
return (this.doubledScanlines && !this.interlacedSyncAndVideo) || this.isEvenRender === this.lastRenderWasEven;
}
debugOffset(x, y) {
if (x < 0 || x >= 1024) return -1;
if (y < 0 || y >= 768) return -1;
return y * 1024 + x;
}
/**
* Where the beam is in the TV's frame, which starts at vsync (or where the TV gives up waiting for one).
* @returns {BeamPosition}
*/
beamPosition() {
if (this.video6847) return this.video6847.beamPosition();
return {
// Each line moves the beam two framebuffer rows, and the odd interlace field starts a row up.
line: (this.bitmapY + 1) >> 1,
frameCycle: (this.bitmapX - this.frameStartX) / BitmapXPerClock,
inVSync: this.inVSync,
crtc: { row: this.vertCounter, scanline: this.scanlineCounter, column: this.horizCounter },
};
}
// Hands over the rows down to the beam only, so the canvas keeps the previous
// frame below it: this frame above the beam, the last one under it, as a
// camera would see.
debugPaint() {
this.renderPending();
Eif (!this.debugPrevScreen) {
this.debugPrevScreen = new Uint32Array(1024 * 768);
}
debugCopyFb(this.debugPrevScreen, this.fb32);
// The 6847 keeps its own beam and copies it here only at flyback.
const beam = this.video6847 ?? this;
const dotSize = 10;
for (let y = -dotSize; y <= dotSize; y++) {
for (let x = -dotSize; x <= dotSize; ++x) {
const dist = Math.sqrt(x * x + y * y) / dotSize;
if (dist > 1) continue;
const offset = this.debugOffset(beam.bitmapX + x, beam.bitmapY + y);
this.fb32[offset] = lerp(this.fb32[offset], OPAQUE_WHITE, Math.pow(1 - dist, 2));
}
}
const beamRows = this.video6847 || this.doublesLines() ? 2 : 1;
const top = this.topBorder;
const bottom = 625 - this.bottomBorder;
const paintedTo = Math.max(top, Math.min(bottom, beam.bitmapY + beamRows + dotSize));
this.paint_ext(this.leftBorder, top, 1024 - this.rightBorder, bottom, paintedTo);
debugCopyFb(this.fb32, this.debugPrevScreen);
}
/**
* The address of the screen memory byte drawn at a point of the picture, or null off it or in the border. It
* runs a copy of this chip on from where it is, so the answer follows the CRTC, the IC32 wrap, the ULA and
* teletext's pipeline exactly as drawing does; a split the program makes part way down the picture is not
* replayed.
* @param {number} x across the painted picture, 0 to 1
* @param {number} y down it, 0 to 1
* @returns {number | null}
*/
addressShownAt(x, y) {
if (this.video6847 || !(x >= 0 && x < 1 && y >= 0 && y < 1)) return null;
const pixelX = Math.floor(this.leftBorder + x * (1024 - this.leftBorder - this.rightBorder));
const pixelY = Math.floor(this.topBorder + y * (625 - this.topBorder - this.bottomBorder));
const tracer = new Video(this.isMaster, this.fb32.length, noop, { hasVideoNula: this.ula.hasVideoNula });
tracer.restoreState(this.snapshotState());
// The SAA5050 shows each byte PipelineLag reads after it is fetched.
const reads = new Int32Array(PipelineLength);
let readCount = 0;
let found = null;
let fieldsTraced = 0;
const videoRead = (address) => {
reads[readCount++ % PipelineLength] = address;
if ((tracer.dispEnabled & EVERYTHINGENABLED) !== EVERYTHINGENABLED) return 0;
const { bitmapX, bitmapY } = tracer;
if (bitmapX < 0 || bitmapX >= 1024 || bitmapY >= 625) return 0;
const doubled = tracer.doublesLines();
const row = doubled ? bitmapY & ~1 : bitmapY;
const inRows = pixelY === row || (doubled && pixelY === row + 1);
if (inRows && pixelX >= bitmapX && pixelX < bitmapX + tracer.pixelsPerChar) {
const shown = tracer.teletextMode ? readCount - 1 - PipelineLag : readCount - 1;
found = shown >= 0 ? reads[shown % PipelineLength] : null;
}
return 0;
};
const countField = (vsync) => {
if (vsync) fieldsTraced++;
};
tracer.reset({ videoRead }, { setVBlankInt: countField }, false);
for (let clocks = 0; fieldsTraced < TracedVSyncs && clocks < MostTracedClocks; clocks += TraceStepClocks)
tracer.polltime(TraceStepClocks);
return found;
}
/**
* Recompute the ULA-dependent half of the line grid descriptor: everything
* except whether this particular scanline was doubled. Called whenever the
* ULA control register changes, so the render loop only has to store it.
* Teletext cells carry their own, from the SAA5050.
*/
updateLineGridUla() {
const texelsWide = texelsPerPixel(this.ulaMode);
this.lineGridUla = encodeLineGrid(texelsWide, false);
this.lineGridUlaDoubled = encodeLineGrid(texelsWide, true);
}
/**
* Draws the cells the beam has passed into fb32. It reads the ULA's state as it is now, so it
* runs before anything changes that state or reads the framebuffer. With every ULA write
* draining, bitmap and teletext cells are never pending together.
*/
renderPending() {
this.teletext.catchUpShown();
const count = this.pendingCount;
if (count === 0) return;
this.pendingCount = 0;
const doubledLines = this.doublesLines();
this.drain.palette.set(this.pixelColours());
this.drain.drain(
count,
table4bppOffset(this.ulaMode, 0),
this.pixelsPerChar,
doubledLines,
doubledLines ? this.lineGridUlaDoubled : this.lineGridUla,
);
}
// The second half of a 16 pixel cell, for the 1MHz repaint.
blitFbSecondHalf(dat, destOffset) {
const offset = table4bppOffset(this.ulaMode, dat);
const colourLookup = this.pixelColours();
for (let i = 8; i < 16; ++i) {
this.fb32[destOffset + i] = colourLookup[this.table4bpp[offset + i]];
}
}
// In NULA palette mode, bypass the ULA palette (ulaPal) and look up
// pixel colours directly from the NULA 12-bit colour table (collook).
// This skips the XOR-7 logical↔physical colour mapping that the
// standard ULA applies. Reference: b-em src/video.c lines 1083, 1117.
pixelColours() {
return this.ula.paletteMode ? this.ula.collook : this.ulaPal;
}
handleCursor() {
if (this.cursorOnThisFrame && this.ulactrl & this.cursorTable[this.cursorDrawIndex]) {
this.cursorInvertedOffset = this.beamOffset();
if (this.teletextMode) {
this.teletext.catchUpShown();
this.drain.markAllDrawn();
this.invertForCursor(this.cursorInvertedOffset, 0);
} else {
this.pendingCells[this.pendingCount++] = this.pendingBeamOffset() | PendingCursor;
}
} else {
this.cursorInvertedOffset = -1;
}
if (++this.cursorDrawIndex === 7) this.cursorDrawIndex = 0;
}
invertForCursor(offset, fromPixel) {
for (let i = fromPixel; i < this.pixelsPerChar; ++i) {
this.fb32[offset + i] ^= CursorInvert;
}
if (this.doublesLines()) {
for (let i = fromPixel; i < this.pixelsPerChar; ++i) {
this.fb32[offset + 1024 + i] ^= CursorInvert;
}
}
}
pendingBeamOffset() {
return ((this.bitmapY + PendingRowBias) * 1024 + this.bitmapX) << PendingOffsetShift;
}
beamOffset() {
const bitmapRow = this.doublesLines() ? this.bitmapY & ~1 : this.bitmapY;
return bitmapRow * 1024 + this.bitmapX;
}
// The render loop paints a whole 1MHz cell on one 2MHz tick and skips the next, but the ULA
// output stage switches at 2MHz: a register write landing on the skipped tick changes the
// second half of the cell just painted. See https://github.com/mattgodbolt/jsbeeb/issues/766
repaintSecondHalfOfCell() {
if (!this.halfClock || !this.oddClock) return;
if ((this.dispEnabled & EVERYTHINGENABLED) !== EVERYTHINGENABLED) return;
if (this.bitmapX < 0 || this.bitmapX >= 1024 || this.bitmapY < 0 || this.bitmapY >= 625) return;
const offset = this.beamOffset();
const halfCell = this.pixelsPerChar >>> 1;
if (this.teletextMode) {
this.teletext.catchUp();
this.teletext.emitSecondHalf(this.fb32, offset);
} else {
this.blitFbSecondHalf(this.cellData, offset);
}
this.drain.markDrawn(offset, this.pixelsPerChar, this.doublesLines());
if (this.doublesLines()) {
this.fb32.copyWithin(offset + 1024 + halfCell, offset + halfCell, offset + this.pixelsPerChar);
}
if (this.cursorInvertedOffset === offset) {
this.invertForCursor(offset, halfCell);
}
}
setScreenHwScroll(viaScreenHwScroll) {
this.screenSubtract = this.screenAddrSubtract[viaScreenHwScroll];
}
readVideoMem() {
if (this.addr & 0x2000) {
// Mode 7 chunky addressing mode if MA13 set.
// Address offset by scanline is ignored.
// On model B only, there's a quirk for reading 0x3c00.
// See: http://www.retrosoftware.co.uk/forum/viewtopic.php?f=73&t=1011
let memAddr = this.addr & 0x3ff;
if (this.addr & 0x800 || this.isMaster) {
memAddr |= 0x7c00;
} else {
memAddr |= 0x3c00;
}
return this.cpu.videoRead(memAddr);
} else {
// Emulate IC32/IC39 address translation: adjust MA11..MA8 on overflow before composing the DRAM address.
const ma = this.addr & 0x1fff;
const raLow = this.externalRowAddress() & 0x07;
let adjustedHigh = (ma >>> 8) & 0x0f;
if (ma & 0x1000) {
adjustedHigh = (adjustedHigh - this.screenSubtract) & 0x0f;
}
const hiResAddr = ((adjustedHigh << 11) | ((ma & 0xff) << 3) | raLow) & 0x7fff;
return this.cpu.videoRead(hiResAddr);
}
}
clockVSync(r7Hit) {
// Half-line interlace timing is shown nicely in figure 13 here:
// http://bitsavers.trailing-edge.com/components/motorola/_dataSheets/6845.pdf
// Essentially, on even frames, vsync raise / lower triggers at
// the mid-scanline, and then a dummy scanline is also added
// at the end of vertical adjust.
// Without interlace, frames are 312 scanlines. With interlace,
// both odd and even frames are 312.5 scanlines.
// The chip runs both vsyncs all the time and muxes one to the pin,
// so changing R8 can switch between them mid-pulse:
// https://stardot.org.uk/forums/viewtopic.php?p=358225#p358225
const halfR0Hit = this.horizCounter === (this.regs[0] + 1) >>> 1;
// A vsync will initiate at any character and scanline position,
// provided there isn't one in progress and provided there
// wasn't already one in this character row.
// This is an interesting finding, on a real model B.
// One further emulated quirk is that in the corner case of a
// vsync ending and starting at the same time, the vsync
// pulse continues uninterrupted. The vsync pulse counter will
// continue counting up and wrap at 16.
const lineVSyncEnding = this.inLineVSync && this.vpulseCounter === this.vpulseWidth;
if (lineVSyncEnding) this.inLineVSync = false;
if (r7Hit && !this.inLineVSync && !this.hadVSyncThisRow) {
this.inLineVSync = true;
Eif (!lineVSyncEnding) {
this.hadVSyncThisRow = true;
this.vpulseCounter = 0;
}
}
if (halfR0Hit) {
const halfLineVSyncEnding = this.inHalfLineVSync && this.vpulseCounter === this.vpulseWidth;
if (halfLineVSyncEnding) this.inHalfLineVSync = false;
if (r7Hit && !this.inHalfLineVSync && !this.hadHalfLineVSyncThisRow) {
this.inHalfLineVSync = true;
Eif (!halfLineVSyncEnding) this.hadHalfLineVSyncThisRow = true;
}
}
// Also picks up a change of field, which can switch sources without either changing.
this.updateVSync();
}
updateVSync() {
const vsync = this.regs[8] & 1 && this.doEvenFrameLogic ? this.inHalfLineVSync : this.inLineVSync;
if (vsync === this.inVSync) return;
this.inVSync = vsync;
if (vsync) this.flyback();
this.sysvia.setVBlankInt(vsync);
this.teletext.setDEW(vsync);
}
endOfFrame() {
this.vertCounter = 0;
this.firstScanline = true;
this.nextLineStartAddr = (this.regs[13] | (this.regs[12] << 8)) & 0x3fff;
this.lineStartAddr = this.nextLineStartAddr;
this.dispEnableSet(VDISPENABLE);
const cursorFlash = (this.regs[10] & 0x60) >>> 5;
this.cursorOnThisFrame = cursorFlash === 0 || !!(this.frameCount & this.cursorFlashMask[cursorFlash]);
this.doEvenFrameLogic = !(this.frameCount & 1);
}
endOfCharacterLine() {
this.vertCounter = (this.vertCounter + 1) & 0x7f;
this.scanlineCounter = 0;
this.hadVSyncThisRow = false;
this.hadHalfLineVSyncThisRow = false;
this.dispEnableSet(SCANLINEDISPENABLE);
this.cursorOn = false;
this.cursorOff = false;
}
endOfScanline() {
// End of scanline is the most complicated and quirky area of the
// 6845. A lot of different states and outcomes are possible.
// From the start of the frame, we traverse various states
// linearly, with most optional:
// - Normal rendering.
// - Last scanline of normal rendering (vertical adjust pending).
// - Vertical adjust.
// - Last scanline of vertical adjust (dummy raster pending).
// - Dummy raster. (This is for interlace timing.)
this.firstScanline = false;
if (this.scanlineCounter === this.regs[11]) this.cursorOff = true;
this.vpulseCounter = (this.vpulseCounter + 1) & 0x0f;
// Pre-counter increment compares and logic.
const r9Hit = this.scanlineCounter === this.regs[9];
if (r9Hit) {
// An R9 hit always loads a new character row address, even if
// we're in vertical adjust!
// Note that an R9 hit inside vertical adjust does not further
// increment the vertical counter, but entry into vertical
// adjust does.
this.lineStartAddr = this.nextLineStartAddr;
}
// Increment scanline.
if (this.interlacedSyncAndVideo) {
this.scanlineCounter = (this.scanlineCounter + 2) & 0x1e;
} else {
this.scanlineCounter = (this.scanlineCounter + 1) & 0x1f;
}
if (!this.teletextMode) {
// Scanlines 8-15 are off but they display again at 16,
// mirroring 0-7, and it repeats.
const off = (this.scanlineCounter >>> 3) & 1;
if (off) {
this.dispEnableClear(SCANLINEDISPENABLE);
} else {
this.dispEnableSet(SCANLINEDISPENABLE);
}
}
// Reset scanline if necessary.
if (!this.inVertAdjust && r9Hit) {
this.endOfCharacterLine();
}
if (this.endOfMainLatched && !this.endOfVertAdjustLatched) {
this.inVertAdjust = true;
}
let endOfFrame = false;
if (this.endOfFrameLatched) {
endOfFrame = true;
}
if (this.endOfVertAdjustLatched) {
this.inVertAdjust = false;
// The "dummy raster" is inserted at the very end of frame,
// after vertical adjust, for even interlace frames.
// Testing indicates interlace is checked here, a clock before
// it is entered or not.
// Like vertical adjust, C4=R4+1.
// The frame counter itself is read here, not the parity latched
// at the start of the frame, so every frame ending on the even
// field gets one (beebjit 085ec88).
if (!!(this.regs[8] & 1) && !!(this.frameCount & 1)) {
this.inDummyRaster = true;
this.endOfFrameLatched = true;
} else {
endOfFrame = true;
}
}
if (endOfFrame) {
this.endOfMainLatched = false;
this.endOfVertAdjustLatched = false;
this.endOfFrameLatched = false;
this.inDummyRaster = false;
this.endOfCharacterLine();
this.endOfFrame();
}
this.addr = this.lineStartAddr;
const cursorStartLine = this.regs[10] & 0x1f;
if (this.scanlineCounter === cursorStartLine) this.cursorOn = true;
// The teletext SAA5050 chip has its CRS pin connected to RA0, so
// we need to update it.
this.teletext.setRA0(!!(this.externalRowAddress() & 1));
}
// In "interlace sync and video" mode the RA pins carry the odd
// scanlines on odd interlace frames.
externalRowAddress() {
return this.interlacedSyncAndVideo ? this.scanlineCounter | (this.frameCount & 1) : this.scanlineCounter;
}
handleHSync() {
this.hpulseCounter = (this.hpulseCounter + 1) & 0x0f;
if (this.hpulseCounter === this.hpulseWidth >>> 1) {
const lineEndX = this.bitmapX;
// Start at -8 because the +8 is added before the pixel render.
this.bitmapX = -8;
// Half-clock horizontal movement
Iif (this.hpulseWidth & 1) {
this.bitmapX -= 4;
}
this.frameStartX += this.bitmapX - lineEndX;
// The CRT vertical beam speed is constant, so this is actually
// an approximation that works if hsyncs are spaced evenly.
this.bitmapY += 2;
this.hsyncCount = (this.hsyncCount + 1) % LineCountPeriod;
this.subcarrierPhase = (this.subcarrierPhase + PalPhasePerLine) % 1;
// Arbitrary moment when TV will give up and start flyback in the absence of an explicit VSync signal
return this.bitmapY >= 768;
} else if (this.hpulseCounter === (this.regs[3] & 0x0f)) {
this.inHSync = false;
}
return false;
}
cb2changed(level, output) {
// Even with no light pen physically attached, the system VIA can
// configure CB2 as an output and make the CRTC think it sees a
// real light pen pulse.
// Triggers on the low -> high CB2 edge.
// Needed by Pharaoh's Curse to start.
if (level && output) {
this.regs[16] = (this.addr >> 8) & 0x3f;
this.regs[17] = this.addr & 0xff;
}
}
dispEnableChanged() {
// The DISPTMG output pin is wired to the SAA5050 teletext chip,
// for scanline tracking, so keep it apprised.
const mask = HDISPENABLE | VDISPENABLE | USERDISPENABLE;
const disptmg = (this.dispEnabled & mask) === mask;
this.teletext.setDISPTMG(disptmg);
}
dispEnableSet(flag) {
this.dispEnabled |= flag;
this.dispEnableChanged();
}
dispEnableClear(flag) {
this.dispEnabled &= ~flag;
this.dispEnableChanged();
}
////////////////////
// Main drawing routine
polltime(clocks) {
const regs = this.regs;
while (clocks--) {
this.oddClock = !this.oddClock;
// Advance CRT beam.
this.bitmapX += BitmapXPerClock;
if (this.halfClock && !this.oddClock) {
continue;
}
// This emulates the Hitachi 6845SP CRTC.
// Other variants have different quirks.
// Handle HSync
if (this.inHSync && this.handleHSync()) this.flyback();
// Handle delayed display enable due to skew
const displayEnablePos = this.displayEnableSkew + (this.teletextMode ? 2 : 0);
if (this.horizCounter === displayEnablePos) {
this.dispEnableSet(SKEWDISPENABLE);
}
// Latch next line screen address in case we are in the last line of a character row
if (this.horizCounter === regs[1]) this.nextLineStartAddr = this.addr;
// Handle end of horizontal displayed.
// Make sure to account for display enable skew.
// Also, the last scanline character never displays.
if (this.horizCounter === regs[1] + displayEnablePos || this.horizCounter === regs[0] + displayEnablePos) {
this.dispEnableClear(HDISPENABLE | SKEWDISPENABLE);
}
// Initiate HSync.
if (this.horizCounter === regs[2] && !this.inHSync) {
this.inHSync = true;
this.hpulseCounter = 0;
}
// Handle VSync.
const r7Hit = this.vertCounter === regs[7];
if (r7Hit || this.inLineVSync || this.inHalfLineVSync) this.clockVSync(r7Hit);
// TODO(#876) this will be cleaner if we rework skew to have fetch
// independent from render.
const insideBorder = (this.dispEnabled & (HDISPENABLE | VDISPENABLE)) === (HDISPENABLE | VDISPENABLE);
if ((insideBorder || this.cursorDrawIndex) && this.dispEnabled & FRAMESKIPENABLE) {
// Read data from address pointer if both horizontal and vertical display enabled.
const dat = this.readVideoMem();
if (insideBorder) {
// Always clock the SAA5050, whatever the ULA mode: IC15 latches the video bus
// into the chip and it is MA13, not the ULA's teletext bit, that gates it. We
// do not model the MA13 gate yet, so this feeds unconditionally. The chip is
// clocked here and painted later, so a control code seen while the ULA shows
// bitmap still takes effect. The chip logs the bytes and runs them when read.
// See https://github.com/mattgodbolt/jsbeeb/issues/546
// and https://github.com/mattgodbolt/jsbeeb/issues/832
this.teletext.logClocked(dat);
// Check cursor start.
if (
this.addr === this.cursorPos &&
this.cursorOn &&
!this.cursorOff &&
this.horizCounter < regs[1]
) {
this.cursorDrawIndex = 3 - ((regs[8] >>> 6) & 3);
}
}
// Render data depending on display enable state.
if (this.bitmapX >= 0 && this.bitmapX < 1024 && this.bitmapY < 625) {
this.cellData = dat;
if ((this.dispEnabled & EVERYTHINGENABLED) === EVERYTHINGENABLED) {
if (this.teletextMode) {
let doubledLines = false;
let bitmapRow = this.bitmapY;
// This is doublesLines(), inlined for speed.
if (
(this.doubledScanlines && !this.interlacedSyncAndVideo) ||
this.isEvenRender === this.lastRenderWasEven
) {
doubledLines = true;
bitmapRow &= ~1;
}
// With a 2MHz clock (the "TTX trick") the SAA5050 shows black. Behaviour
// confirmed by Rich Talbot-Watkins (RTW) at ABUG 2026-03-13; the mechanism
// is not established, as the Model B ULA has no connection to the SAA5050 at all.
// See https://github.com/mattgodbolt/jsbeeb/issues/546
this.teletext.showLatest(bitmapRow * 1024 + this.bitmapX, doubledLines, !this.halfClock);
} else {
this.pendingCells[this.pendingCount++] = this.pendingBeamOffset() | dat;
}
}
if (this.cursorDrawIndex) {
this.handleCursor();
}
}
}
// IC37/IC36: during H blanking with V display active, always feed
// the SAA5050 pipeline with the video bus data, forcing bit 6 high.
// On real hardware IC37/IC36 operates regardless of ULA mode —
// it is wired to the CRTC DISPEN signal, not the ULA teletext bit.
// Hardware also clocks the chip here, which we do not: our row reset fires
// too early relative to the pipeline for that to come out right, and clocking
// it here alone moves three of the hardware reference pages. See
// https://github.com/mattgodbolt/jsbeeb/issues/874
if (!(this.dispEnabled & HDISPENABLE) && this.dispEnabled & VDISPENABLE) {
this.teletext.logFed(this.readVideoMem() | 0x40);
}
// CRTC MA always increments, inside display border or not.
this.addr = (this.addr + 1) & 0x3fff;
// The Hitachi 6845 decides to end (or never enter) vertical
// adjust here, one clock after checking whether to enter
// vertical adjust.
// In a normal frame, this is C0=2.
if (this.checkVertAdjust) {
this.checkVertAdjust = false;
if (this.endOfMainLatched) {
if (this.vertAdjustCounter === regs[5]) {
this.endOfVertAdjustLatched = true;
}
this.vertAdjustCounter++;
this.vertAdjustCounter &= 0x1f;
}
}
// The Hitachi 6845 appears to latch some form of "last scanline
// of the frame" state. As shown by Twisted Brain, changing R9
// from 0 to 6 on the last scanline of the frame does not
// prevent a new frame from starting.
// Testing indicates that the latch is set here at exactly C0=1.
// See also: http://www.cpcwiki.eu/forum/programming/crtc-detailed-operation/msg177585/
if (this.horizCounter === 1) {
if (this.vertCounter === regs[4] && this.scanlineCounter === regs[9]) {
this.endOfMainLatched = true;
this.vertAdjustCounter = 0;
}
// The very next cycle (be it on this same scanline or the
// next) is used for checking the vertical adjust counter.
this.checkVertAdjust = true;
}
// Handle horizontal total.
if (this.horizCounter === regs[0]) {
this.endOfScanline();
this.horizCounter = 0;
this.dispEnableSet(HDISPENABLE);
} else {
this.horizCounter = (this.horizCounter + 1) & 0xff;
}
// Handle end of vertical displayed.
// The Hitachi 6845 will notice this equality at any character,
// including in the middle of a scanline.
// An exception is the very first scanline of a frame, where
// vertical display is always on.
// We do this after the render and various counter increments
// because there seems to be a 1 character delay between setting
// R6=C4 and display actually stopping.
const r6Hit = this.vertCounter === regs[6];
if (r6Hit && !this.firstScanline && this.dispEnabled & VDISPENABLE) {
this.dispEnableClear(VDISPENABLE);
// Perhaps surprisingly, this happens here. Both cursor
// blink and interlace cease if R6 > R4.
this.frameCount++;
}
} // matches while
}
}
// The MOS's default CRTC setup: 312.5 lines of 128 2MHz cycles per field, vsync two lines long.
const BbcLineCycles = 128;
const BbcFieldCycles = 312.5 * BbcLineCycles;
const BbcVSyncCycles = 2 * BbcLineCycles;
/** No picture, but the vsync pulse the System VIA sees once a field. */
export class FakeVideo {
constructor() {
this.crtc = {
read: function () {
return 0xff;
},
write: noop,
};
this.ula = {
read: function () {
return 0xff;
},
write: noop,
reset: noop,
disabled: false,
hasVideoNula: false,
};
this.regs = new Uint8Array(32);
this.fb32 = new Uint32Array(0);
this.fieldCycles = BbcFieldCycles;
this.syncCycles = BbcVSyncCycles;
this.lineCycles = BbcLineCycles;
this.cycles = 0;
this.inSync = false;
}
// Like the CRTC, the field runs on through a reset, as the VIA keeps the sync level it last saw.
reset(cpu, via) {
this.syncTarget = via;
}
polltime(cycles) {
this.cycles += cycles;
for (;;) {
if (!this.inSync && this.cycles >= this.fieldCycles - this.syncCycles) {
this.inSync = true;
this.syncTarget.setVBlankInt(true);
} else if (this.inSync && this.cycles >= this.fieldCycles) {
this.inSync = false;
this.cycles -= this.fieldCycles;
this.syncTarget.setVBlankInt(false);
} else {
return;
}
}
}
setScreenHwScroll() {}
/** @returns {BeamPosition} */
beamPosition() {
const sinceSync = this.cycles - (this.fieldCycles - this.syncCycles);
const frameCycle = sinceSync < 0 ? sinceSync + this.fieldCycles : sinceSync;
return { line: Math.floor(frameCycle / this.lineCycles), frameCycle, inVSync: this.inSync, crtc: null };
}
addressShownAt() {
return null;
}
snapshotState() {
return { cycles: this.cycles, inSync: this.inSync };
}
restoreState(state) {
this.cycles = state.cycles ?? 0;
this.inSync = state.inSync ?? false;
}
}
// The 6847's field as the PPIA sees it: 262 lines at 60Hz, with field sync low
// for the 32 lines of flyback (see 6847.js).
const AtomFieldCycles = 16667;
const AtomFieldLines = 262;
const AtomFlybackCycles = Math.round((AtomFieldCycles * 32) / AtomFieldLines);
/** No picture, but the field sync the Atom ROM waits on before each keyboard scan. */
export class FakeAtomVideo extends FakeVideo {
constructor() {
super();
this.fieldCycles = AtomFieldCycles;
this.syncCycles = AtomFlybackCycles;
this.lineCycles = AtomFieldCycles / AtomFieldLines;
}
reset(cpu) {
this.syncTarget = cpu.atomppia;
}
}
|