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 | 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 66x 66x 66x 66x 66x 55x 55x 5x 5x 6x 6x 66x 53x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 55x 55x 55x 55x 55x 55x 23x 55x 55x 5x 5x 5x 5x 5x 5x 6x 6x 6x 6x 6x 266x 266x 4256x 4256x 4256x 4256x 4114x 232x 232x 232x 53x 34x 5338x 2669x 2669x 27x 27x 27x 46x 46x 46x 46x 46x 46x 2669x 12x 9437184x 5706x 5706x 5706x 5706x 1902x 1902x 1902x 1902x 1902x 1902x 1902x 1902x 1902x 1902x 1902x 1902x 11645385x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 59392x 59392x 950272x 950272x 950272x 950272x 950272x 950272x 950272x 950272x 59392x 950272x 950272x 950272x 232x 232x 232x 232x 232x 2x 2x 232x 232x 232x 53x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 415x 415x 415x 415x 610x 607x 607x 65x 65x 20310x 20310x 20310x 20310x 542x 542x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1378x 1313x 1313x 65x 35x 35x 30x 30x 619245x 1902x 1310x 1220x 6x 6x 6x 6x 6x 6x 126x 2646x 2646x 1902x 1902x 6x 6x 6x 6x 6x 6x 322x 322x 322x 4993477x 4993477x 4993477x 4993477x 4993477x 4993477x 4993462x 39947696x 15x 240x 4x 4x 4x 32x 4993481x 86481x 1x 1x 86480x 86481x 2x 24x 2x 2x 24x 66x 6x 6x 5x 5x 66x 66x 66x 1x 4x 5x 5x 5x 1x 28x 9455942x 2x 2x 1x 1x 2x 9455940x 9455940x 9455940x 9455940x 3x 9455940x 9455940x 24430x 24430x 24430x 24430x 24430x 24430x 24430x 24430x 60238x 60238x 60238x 60238x 60238x 60238x 123324x 123324x 123324x 123324x 123324x 35808x 123324x 35093x 88231x 123324x 123321x 123321x 24112x 99209x 123324x 35808x 123324x 82x 123324x 123324x 324x 123324x 24754x 24754x 568x 568x 24186x 123324x 24430x 24430x 24430x 24430x 24430x 24430x 123324x 123324x 123324x 123324x 123324x 17563x 123324x 493240x 493240x 123307x 123307x 123307x 123307x 123307x 123307x 369933x 123307x 369933x 701683x 701683x 701683x 430577x 430577x 271106x 271106x 7514715x 15783658x 15783658x 15783658x 1x 15783657x 15783657x 15783658x 123332x 15783657x 15783657x 246628x 15783657x 123309x 123309x 15783657x 15783657x 15783657x 15783658x 15783658x 15783658x 1325x 1325x 15783657x 1338x 1338x 15783657x 1338x 1338x 1338x 15783657x 2663x 2663x 15783657x 15783657x 5960863x 5960863x 5825463x 5825463x 5825463x 24420x 5960863x 5598423x 5598423x 5598423x 4759061x 4759061x 5598423x 5598423x 5598423x 4993463x 4516341x 4516341x 477122x 4993463x 4x 3x 1x 4993459x 4993463x 4516341x 5598423x 86481x 15783657x 3495073x 15783657x 15783657x 123312x 123312x 24836x 24430x 24836x 24836x 15783657x 123313x 24430x 24430x 123313x 15783657x 123321x 123321x 123321x 15660336x 15783657x 15783657x 365x 365x 52x 52x 52x 1x 22x 22x 3x 3x 3x 743874x 743874x 69x 69x 743805x 68x 68x 68x | import { Teletext } from "./teletext.js";
import { BbcDefaultPalette as NulaDefaultPalette } from "./bbc-palette.js";
import { Video6847 } from "./6847.js";
import { encodeLineGrid, texelsPerPixel, LineGridRows } from "./video-filters/pixel-grid.js";
import { makeFast32 } from "./binary.js";
const noop = () => {};
export const VDISPENABLE = 1 << 0;
export const HDISPENABLE = 1 << 1;
export const SKEWDISPENABLE = 1 << 2;
export const SCANLINEDISPENABLE = 1 << 3;
export const USERDISPENABLE = 1 << 4;
export const FRAMESKIPENABLE = 1 << 5;
export const EVERYTHINGENABLED =
VDISPENABLE | HDISPENABLE | SKEWDISPENABLE | SCANLINEDISPENABLE | USERDISPENABLE | FRAMESKIPENABLE;
export const OPAQUE_BLACK = 0xff000000;
export 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).
export const PalSubcarrierOffsetHz = 239;
const PalNominalSubcarrierHz = 4433618.75;
const PalLineHz = 15625;
export const PalCyclesPerLine = (PalNominalSubcarrierHz + PalSubcarrierOffsetHz) / PalLineHz;
export const PalPhasePerLine = PalCyclesPerLine % 1;
// The shader takes a line's parity from the hsync count; the modulus only keeps it bounded.
export const LineCountPeriod = 2500;
////////////////////
// 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) {
this.video = video;
// 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;
this.disabled = false;
this.attributeMode = 0;
this.attributeText = 0;
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;
let reg = addr & 3;
// When NULA is disabled, mask off bit 1 so &FE22/&FE23 become &FE20/&FE21.
Iif (reg >= 2 && this.disabled) {
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) {
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) {
Iif ((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.
Iif (val & 8 && this.video.ulactrl & 1 && this.flash[(val & 7) ^ 7]) {
colour = this.collook[val & 0xf];
}
Eif (this.video.ulaPal[index] !== colour) {
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];
Iif (palVal & 8 && flashEnabled && this.flash[(palVal & 7) ^ 7]) {
colour = this.collook[palVal & 0xf];
}
if (video.ulaPal[i] !== colour) {
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) {
if (!(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.interlacedSyncAndVideo = (val & 3) === 3;
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, fb32_param, paint_ext_param, { isAtom = false } = {}) {
this.isMaster = isMaster;
this.fb32 = makeFast32(fb32_param);
this.collook = makeFast32(
new Uint32Array([
0xff000000, 0xff0000ff, 0xff00ff00, 0xff00ffff, 0xffff0000, 0xffff00ff, 0xffffff00, 0xffffffff,
]),
);
this.screenAddrSubtract = new Uint8Array([8, 4, 10, 5]);
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;
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.hadVSyncThisRow = 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 = new Uint8Array(LineGridRows);
this.lineGridUla = 0;
this.lineGridUlaDoubled = 0;
this.updateLineGridUla();
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 = new Uint8Array(4 * 256 * 16);
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);
// Atom: attach the MC6847 VDG and use its polltime
this.video6847 = null;
if (isAtom) {
this.video6847 = new Video6847(this);
this.polltime = this.video6847.polltimeFacade;
}
this.reset(null);
this.clearPaintBuffer();
this.paint();
}
snapshotState() {
return {
regs: this.regs.slice(),
bitmapX: this.bitmapX,
bitmapY: this.bitmapY,
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,
hadVSyncThisRow: this.hadVSyncThisRow,
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(),
};
}
restoreState(state) {
this.regs.set(state.regs);
this.bitmapX = state.bitmapX;
this.bitmapY = state.bitmapY;
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.hadVSyncThisRow = 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);
// Restore ulaPal after ULA restore, since ULA recomputation may overwrite it
this.ulaPal.set(state.ulaPal);
}
reset(cpu, via) {
this.cpu = cpu;
this.sysvia = via;
if (via) via.cb2changecallback = this.cb2changed.bind(this);
Iif (this.video6847 && cpu) {
this.video6847.reset(cpu, cpu.atomppia);
}
}
paint() {
this.paint_ext(this.leftBorder, this.topBorder, 1024 - this.rightBorder, 625 - this.bottomBorder);
}
clearPaintBuffer() {
const fb32 = this.fb32;
// 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()) {
let line = this.frameCount & 1;
while (line < 625) {
const start = line * 1024;
fb32.fill(OPAQUE_BLACK, start, start + 1024);
this.lineGrid[line] = 0;
line += 2;
}
} else {
fb32.fill(OPAQUE_BLACK);
this.lineGrid.fill(0);
}
}
flyback() {
const painting = this.bitmapY >= MinPaintedFrameRows && this.dispEnabled & FRAMESKIPENABLE;
if (painting) this.paint();
// 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;
}
}
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;
}
// 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() {
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);
}
/**
* 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.
*
* MODE 7 counts as one texel per pixel: the SAA5050 emulation writes each
* of its 16 texels per character individually, so its output is already at
* the framebuffer's own resolution.
*/
updateLineGridUla() {
const texelsWide = this.teletextMode ? 1 : texelsPerPixel(this.ulaMode);
this.lineGridUla = encodeLineGrid(texelsWide, false);
this.lineGridUlaDoubled = encodeLineGrid(texelsWide, true);
}
blitFb(dat, destOffset, numPixels) {
destOffset |= 0;
const offset = table4bppOffset(this.ulaMode, dat);
const fb32 = this.fb32;
const colourLookup = this.pixelColours();
const table4bpp = this.table4bpp;
// Take advantage of numPixels being either 8 or 16
if (numPixels === 8) {
for (let i = 0; i < 8; ++i) {
fb32[destOffset + i] = colourLookup[table4bpp[offset + i]];
}
} else {
for (let i = 0; i < 16; ++i) {
fb32[destOffset + i] = colourLookup[table4bpp[offset + i]];
}
}
}
// 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(offset) {
if (this.cursorOnThisFrame && this.ulactrl & this.cursorTable[this.cursorDrawIndex]) {
this.invertForCursor(offset, 0);
this.cursorInvertedOffset = offset;
} 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] ^= 0x00ffffff;
}
Eif (this.doubledScanlines && !this.interlacedSyncAndVideo) {
for (let i = fromPixel; i < this.pixelsPerChar; ++i) {
this.fb32[offset + 1024 + i] ^= 0x00ffffff;
}
}
}
// 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;
Iif ((this.dispEnabled & EVERYTHINGENABLED) !== EVERYTHINGENABLED) return;
if (this.bitmapX < 0 || this.bitmapX >= 1024 || this.bitmapY < 0 || this.bitmapY >= 625) return;
const doubledLines = this.doublesLines();
const bitmapRow = doubledLines ? this.bitmapY & ~1 : this.bitmapY;
const offset = bitmapRow * 1024 + this.bitmapX;
const halfCell = this.pixelsPerChar >>> 1;
if (this.teletextMode) {
this.teletext.emitSecondHalf(this.fb32, offset);
} else {
this.blitFbSecondHalf(this.cellData, offset);
}
Eif (doubledLines) {
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.scanlineCounter & 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);
}
}
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.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.
// The external RA0 value is modified in "interlace sync and video"
// mode to be odd for odd interlace frames.
let externalScanline = this.scanlineCounter;
if (this.interlacedSyncAndVideo && this.frameCount & 1) {
externalScanline++;
}
this.teletext.setRA0(!!(externalScanline & 1));
}
handleHSync() {
this.hpulseCounter = (this.hpulseCounter + 1) & 0x0f;
if (this.hpulseCounter === this.hpulseWidth >>> 1) {
// 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;
}
// 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) {
while (clocks--) {
this.oddClock = !this.oddClock;
// Advance CRT beam.
this.bitmapX += 8;
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 === this.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 === this.regs[1] + displayEnablePos ||
this.horizCounter === this.regs[0] + displayEnablePos
) {
this.dispEnableClear(HDISPENABLE | SKEWDISPENABLE);
}
// Initiate HSync.
if (this.horizCounter === this.regs[2] && !this.inHSync) {
this.inHSync = true;
this.hpulseCounter = 0;
}
// Handle VSync.
// 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.
const isInterlace = !!(this.regs[8] & 1);
const halfR0Hit = this.horizCounter === (this.regs[0] + 1) >>> 1;
const isVsyncPoint = !isInterlace || !this.doEvenFrameLogic || halfR0Hit;
let vSyncEnding = false;
let vSyncStarting = false;
if (this.inVSync && this.vpulseCounter === this.vpulseWidth && isVsyncPoint) {
vSyncEnding = true;
this.inVSync = false;
}
if (this.vertCounter === this.regs[7] && !this.inVSync && !this.hadVSyncThisRow && isVsyncPoint) {
vSyncStarting = true;
this.inVSync = true;
}
// 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.
if (vSyncStarting && !vSyncEnding) {
this.hadVSyncThisRow = true;
this.vpulseCounter = 0;
this.flyback();
}
if (vSyncStarting || vSyncEnding) {
this.sysvia.setVBlankInt(this.inVSync);
this.teletext.setDEW(this.inVSync);
}
// 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.
// See https://github.com/mattgodbolt/jsbeeb/issues/546
// and https://github.com/mattgodbolt/jsbeeb/issues/832
this.teletext.fetchData(dat);
this.teletext.advance();
// Check cursor start.
if (
this.addr === this.cursorPos &&
this.cursorOn &&
!this.cursorOff &&
this.horizCounter < this.regs[1]
) {
this.cursorDrawIndex = 3 - ((this.regs[8] >>> 6) & 3);
}
}
// Render data depending on display enable state.
if (this.bitmapX >= 0 && this.bitmapX < 1024 && this.bitmapY < 625) {
let doubledLines = false;
let bitmapRow = this.bitmapY;
// There's a painting subtlety here: if we're in an
// interlace mode but R6>R4 then we'll get stuck
// painting just an odd or even frame, so we double up
// scanlines to avoid a ghost half frame. This is
// doublesLines(), inlined for speed.
if (
(this.doubledScanlines && !this.interlacedSyncAndVideo) ||
this.isEvenRender === this.lastRenderWasEven
) {
doubledLines = true;
bitmapRow &= ~1;
}
const offset = bitmapRow * 1024 + this.bitmapX;
this.cellData = dat;
if ((this.dispEnabled & EVERYTHINGENABLED) === EVERYTHINGENABLED) {
// Note this row's logical pixel size for display
// filters; see video-filters/pixel-grid.js. The ULA half
// of the descriptor is precomputed on register writes so
// this stays a store or two in the hottest loop we have.
if (doubledLines) {
this.lineGrid[bitmapRow] = this.lineGridUlaDoubled;
this.lineGrid[bitmapRow + 1] = this.lineGridUlaDoubled;
} else {
this.lineGrid[bitmapRow] = this.lineGridUla;
}
if (this.teletextMode) {
if (this.halfClock) {
// Proper MODE 7 (1MHz clock + teletext): render SAA5050 output normally.
this.teletext.emit(this.fb32, offset);
} else {
// 2MHz clock + teletext bit set (the "TTX trick"): the SAA5050
// outputs 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.fb32.fill(OPAQUE_BLACK, offset, offset + this.pixelsPerChar);
}
} else {
this.blitFb(dat, offset, this.pixelsPerChar);
}
if (doubledLines) {
this.fb32.copyWithin(offset + 1024, offset, offset + this.pixelsPerChar);
}
}
if (this.cursorDrawIndex) {
this.handleCursor(offset);
}
}
}
// 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 adding
// `advance()` 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.fetchData(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 === this.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 === this.regs[4] && this.scanlineCounter === this.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 === this.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 === this.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
}
}
export class FakeVideo {
constructor() {
this.crtc = {
read: function () {
return 0xff;
},
write: noop,
};
this.ula = {
read: function () {
return 0xff;
},
write: noop,
reset: noop,
disabled: false,
};
this.regs = new Uint8Array(32);
}
reset() {}
polltime() {}
setScreenHwScroll() {}
snapshotState() {
return {};
}
restoreState() {}
}
// 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 AtomFlybackCycles = Math.round((AtomFieldCycles * 32) / 262);
/** No picture, but the field sync the Atom ROM waits on before each keyboard scan. */
export class FakeAtomVideo extends FakeVideo {
reset(cpu) {
this.ppia = cpu.atomppia;
this.cycles = 0;
this.inFlyback = false;
}
polltime(cycles) {
this.cycles += cycles;
if (!this.inFlyback && this.cycles >= AtomFieldCycles - AtomFlybackCycles) {
this.inFlyback = true;
this.ppia.setVBlankInt(1);
} else if (this.inFlyback && this.cycles >= AtomFieldCycles) {
this.inFlyback = false;
this.cycles -= AtomFieldCycles;
this.ppia.setVBlankInt(0);
}
}
}
|