@henols/c64-re-tools 2.7.0-rc.1 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.7.0-rc.1",
3
+ "version": "2.7.1",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -258,15 +258,16 @@ The loader does these steps:
258
258
 
259
259
  1. `10 SYS 2061` starts it.
260
260
  2. It stops the interrupts and makes all RAM visible. It moves its copier to two free pages.
261
- 3. It copies each segment without the leftovers, and the pages $0002-$03ff of the entry state, into place. No copy writes over the packed bytes of a copy that has not run yet.
261
+ 3. It copies each segment without the leftovers, and the pages $0002-$03ff of the entry state, into place. It also copies the 1000 colours of the colour RAM of the entry state to free RAM. No copy writes over the packed bytes of a copy that has not run yet.
262
262
  4. When the knowledge has a start screen and `START_SCREEN` is 1, it shows the start screen. It waits until the user releases all keys and fire buttons. Then it waits for a key, or for a fire button on joystick port 1 or 2, and for its release. A move of a joystick is not a key.
263
- 5. It sets the screen registers of the VIC-II and the VIC bank from the entry state. Then it waits for the raster line of the entry.
264
- 6. It sets the CIA timers, their latches and the interrupt masks from the entry state. A running timer gets the value that counts down to the timer value at the entry.
265
- 7. It sets $00/$01, the stack pointer, A, X, Y and the flags. Then it jumps to the entry.
263
+ 5. It sets the colour RAM from the entry state. The start screen writes the colour RAM, thus this step comes after it.
264
+ 6. It sets the screen registers of the VIC-II and the VIC bank from the entry state. Then it waits for the raster line of the entry.
265
+ 7. It sets the CIA timers, their latches and the interrupt masks from the entry state. A running timer gets the value that counts down to the timer value at the entry.
266
+ 8. It sets $00/$01, the stack pointer, A, X, Y and the flags. Then it jumps to the entry.
266
267
 
267
268
  The copy table, the copier and the jump use labels, not numbers. `loader_from_xxxx` and `loader_end_xxxx` are around each packed segment. `loader_to_xxxx` is its first address in place. Thus a segment can change its length, and the loader still works.
268
269
 
269
- The loader changes the free stack byte below the stack pointer (`stackByte`). It does not set the SID, the time of day of the CIAs, the CIA interrupt flags or the interrupt registers of the VIC-II. A program that reads SID voice 3 for random numbers can thus give a different result. A start screen writes the colour RAM, and the loader does not set it again. When you compare the reference and the rebuild, observe after the program sets its own random numbers.
270
+ The loader changes the free stack byte below the stack pointer (`stackByte`). It does not set the SID, the time of day of the CIAs, the CIA interrupt flags or the interrupt registers of the VIC-II. A program that reads SID voice 3 for random numbers can thus give a different result. When you compare the reference and the rebuild, observe after the program sets its own random numbers.
270
271
 
271
272
  The script builds and checks the loader program with the values of `config.asm`. With the defaults, the loader program is the clean program: no copy protection, all corrections and no leftovers. The entry state is the state of the base release. For a loader of a release, build `loader.asm` with the build option `--release <label>`. That loader also does not have the leftovers.
272
273
 
@@ -281,8 +282,9 @@ The start screen:
281
282
  `loader` holds these fields:
282
283
 
283
284
  - `program`, the `copies` in their order, `copier` and `stackByte`.
284
- - `verified: true`: the check ran the loader program to its jump to the entry. There, the memory, $00/$01, the registers and the VIC-II are equal to the entry state. The raster line and the CIA values are also equal. An interrupt can run right at the entry, as in the program of the base release.
285
- - `limits`: each CIA value that the loader cannot set as it was at the entry. An old capture has no CIA values. Then capture the program again at its entry point.
285
+ - `verified: true`: the check ran the loader program to its jump to the entry. There, the memory, $00/$01, the registers, the VIC-II and the colour RAM are equal to the entry state. The raster line and the CIA values are also equal. An interrupt can run right at the entry, as in the program of the base release.
286
+ - `limits`: each CIA value that the loader cannot set as it was at the entry. An old capture has no CIA values or no colour RAM. Then capture the program again at its entry point.
287
+ When no free RAM outside the segments has room for the 1000 colours, the loader does not set the colour RAM, and `limits` tells this. Then the program starts with other colours where it does not write them.
286
288
  - `startScreen`: with a start screen, `shown: true` when the VIC-II had the values of the start screen, and `waits: true` when the start screen waited without a key. `wait` and `continue` are the addresses of the wait and of the code after it. The check sets the PC to `continue`, and then runs the loader to its jump.
287
289
  - `packed`: `packedBytes` and `unpackedBytes` of the packed form. With a start screen of a captured stage, this is the packed program in the loader program.
288
290
  - `stage`: the show stage of a start screen of a captured stage. It has the `space` of the stage and the address of the show `code`. It also has the `bytes` of the stage in the loader program, the `stash` copies, `packedBytes` and `unpackedBytes`. `startScreen.stage` names the space.
@@ -10,6 +10,8 @@
10
10
  // copier, and the copier writes only pages $0002-$03ff. With a start
11
11
  // screen in the knowledge, the copier shows it after the copies and waits for
12
12
  // a key or a fire button: the code is start-screen.asm, the same for each program.
13
+ // After the start screen, which writes the colour RAM, the copier sets the
14
+ // colour RAM of the entry from a free range where the copies or the unpack put it.
13
15
  // The loader loads the segments without the leftovers: the ranges of the
14
16
  // source that nothing uses are not in the loader program.
15
17
 
@@ -22,7 +24,7 @@ import { compareBuild, mergedPrograms } from "#src/compare.ts";
22
24
  import { Refusal } from "#src/errors.ts";
23
25
  import { parseEntryState } from "#src/host-client/entry-state.ts";
24
26
  import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
25
- import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
27
+ import { capturedColourRam, LOADER_JUMP } from "#src/knowledge/start-screen.ts";
26
28
  import { romUseOfPort } from "#src/platform.ts";
27
29
  import { WireFailure } from "#src/host-client/tools.ts";
28
30
  import { pack } from "#src/native/exomizer.ts";
@@ -44,6 +46,8 @@ export interface EntryState {
44
46
  vic?: { registers: Uint8Array; bank: number };
45
47
  /** CIA 1 and CIA 2 at the entry. */
46
48
  cia?: [EntryCia, EntryCia];
49
+ /** The colour RAM at the entry: 1000 colours from $d800. */
50
+ colourRam?: Uint8Array;
47
51
  }
48
52
 
49
53
  /** A CIA at the entry: $xx00-$xx0f as a read without side effects gives them, and what no read gives. */
@@ -81,7 +85,8 @@ const FLAG_BITS = { n: 0x80, v: 0x40, d: 0x08, i: 0x04, z: 0x02, c: 0x01 } as co
81
85
 
82
86
  /**
83
87
  * The entry state that the loader recreates: the shared entry state of the
84
- * program capture, with the flags as PLP reads them, the VIC-II and the CIAs.
88
+ * program capture, with the flags as PLP reads them, the VIC-II, the CIAs and
89
+ * the colour RAM.
85
90
  */
86
91
  export function loaderState(value: unknown, where: string): EntryState {
87
92
  const state = parseEntryState(value, where);
@@ -90,7 +95,8 @@ export function loaderState(value: unknown, where: string): EntryState {
90
95
  };
91
96
  let flags = 0x20;
92
97
  for (const [name, bit] of Object.entries(FLAG_BITS)) if (state.flags[name as keyof typeof FLAG_BITS]) flags |= bit;
93
- return { pc: state.pc, a: state.a, x: state.x, y: state.y, sp: state.sp, flags, port: state.port, pages: state.pages, ...readVic(state.raw.io as Record<string, any> | undefined, fail), ...readCia(state.raw, fail) };
98
+ const colourRam = capturedColourRam(state.raw);
99
+ return { pc: state.pc, a: state.a, x: state.x, y: state.y, sp: state.sp, flags, port: state.port, pages: state.pages, ...readVic(state.raw.io as Record<string, any> | undefined, fail), ...readCia(state.raw, fail), ...(colourRam === undefined ? {} : { colourRam }) };
94
100
  }
95
101
 
96
102
  export interface Copy {
@@ -127,17 +133,19 @@ export interface LoaderPlan {
127
133
  packed?: { start: number };
128
134
  /** The VIC-II values that the start screen sets, when the knowledge has one. */
129
135
  startScreen?: StartScreenPlan;
136
+ /** The range where the copier reads the colours of the entry state, when the loader sets the colour RAM. */
137
+ colours?: AddressRange;
138
+ /** Why the loader does not set the colour RAM, when it does not. */
139
+ colourLimit?: string;
130
140
  }
131
141
 
132
142
  /**
133
143
  * What the loader cannot set as it was at the entry. An entry state
134
144
  * without CIA values (from a capture of an older version) gives no timers at all.
135
145
  */
136
- export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
137
- if (plan.cia === undefined) {
138
- return ["The entry state has no CIA values, so the loader does not set the CIA timers. Capture the program again at its entry point to get them."];
139
- }
140
- return plan.cia.limits;
146
+ export function loaderLimits(plan: { cia?: CiaPlan; colourLimit?: string }): string[] {
147
+ const cia = plan.cia === undefined ? ["The entry state has no CIA values, so the loader does not set the CIA timers. Capture the program again at its entry point to get them."] : plan.cia.limits;
148
+ return [...cia, ...(plan.colourLimit === undefined ? [] : [plan.colourLimit])];
141
149
  }
142
150
 
143
151
  export { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
@@ -208,6 +216,10 @@ const COPIER_CODE_SIZE = 167;
208
216
  /** The VIC-II code of the copier, without its two tables of one byte per register. */
209
217
  const VIC_CODE_SIZE = 44;
210
218
  const VIC_SIZE = VIC_CODE_SIZE + 2 * VIC_DISPLAY_REGISTERS.length;
219
+ /** The colours of the colour RAM at $d800-$dbe7. */
220
+ const COLOURS = 1000;
221
+ /** The colour code of the copier: its copy of the colours into the colour RAM. */
222
+ const COLOUR_CODE_SIZE = 35;
211
223
  /** The copier and the stub's move of it: two pages, or three with a start screen. */
212
224
  const COPIER_LIMIT = 0x200;
213
225
  /** The bytes that the stub adds for each more page of the copier: lda and sta. */
@@ -521,6 +533,23 @@ function byteLines(range: AddressRange, bytes: (address: number) => number): str
521
533
  * An image too large for one loader file gets the packed form (see planPacked). Refuses by name when no plan exists.
522
534
  */
523
535
  export function planLoader(input: LoaderInput): LoaderPlan {
536
+ const { colourRam } = input.state;
537
+ if (colourRam === undefined) return { ...planForm(input, undefined)!, colourLimit: "The entry state has no colour RAM, so the loader does not set it. Capture the program again at its entry point to get it." };
538
+ // The colours take 1000 bytes of free RAM and make the loader larger: a plan that has no room for them is made without them.
539
+ try {
540
+ const plan = planForm(input, colourRam);
541
+ if (plan !== undefined) return plan;
542
+ } catch (error) {
543
+ if (!(error instanceof WireFailure)) throw error;
544
+ }
545
+ return {
546
+ ...planForm(input, undefined)!,
547
+ colourLimit: `The loader has no room for the ${COLOURS} colours of the colour RAM in ${COLOUR_AREAS.map(show).join(" or ")} outside the segments, the loader and its copier, so it does not set the colour RAM. The program starts with the colours that the loader leaves there.`,
548
+ };
549
+ }
550
+
551
+ /** The plain or the packed plan, with the colours of the colour RAM when they are given. Undefined when the colours have no room. */
552
+ function planForm(input: LoaderInput, colours: Uint8Array | undefined): LoaderPlan | undefined {
524
553
  const { state } = input;
525
554
  const screen = checkStartScreen(input);
526
555
  const copierBytes = screen === undefined ? COPIER_LIMIT : COPIER_LIMIT + 0x100;
@@ -550,15 +579,19 @@ export function planLoader(input: LoaderInput): LoaderPlan {
550
579
  }
551
580
  const cia = ciaSection(state);
552
581
  const ciaSize = cia === undefined ? 0 : cia.ops.reduce((sum, op) => sum + op.bytes, 0);
553
- const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize + (screen === undefined ? 0 : START_SCREEN_SIZES[screen.colourMode]);
582
+ const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize + (screen === undefined ? 0 : START_SCREEN_SIZES[screen.colourMode]) + (colours === undefined ? 0 : COLOUR_CODE_SIZE);
583
+ // The colours come after the blocks in the loader file. Their copy runs first, to a free range outside the loader file.
584
+ const colourSource = at;
585
+ if (colours !== undefined) at += COLOURS;
586
+ const copyCount = plain.length + (colours === undefined ? 0 : 1);
554
587
  const copierImage = at;
555
- const end = copierImage + codeSize + COPY_ENTRY * plain.length + 2 - 1;
556
- if (input.packed === true) return planPacked(input, blocks, cia, codeSize, screen, "The start screen of a captured stage shows while the program is still packed.");
588
+ const end = copierImage + codeSize + COPY_ENTRY * copyCount + 2 - 1;
589
+ if (input.packed === true) return planPacked(input, blocks, cia, codeSize, screen, "The start screen of a captured stage shows while the program is still packed.", colours);
557
590
  // The end can be past $ffff, which is no address.
558
- if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`);
591
+ if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`, colours);
559
592
  // The CIA part and the start screen take room from the copy table in the copier's pages.
560
593
  const maxCopies = Math.max(0, Math.min(TABLE_COPIES, Math.floor((copierBytes - codeSize - 2) / COPY_ENTRY)));
561
- if (plain.length > maxCopies) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader needs ${plain.length} copies, and its copier can do at most ${maxCopies}.`);
594
+ if (copyCount > maxCopies) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader needs ${copyCount} copies, and its copier can do at most ${maxCopies}.`, colours);
562
595
 
563
596
  const order = copyOrder(plain);
564
597
  if (order === undefined) {
@@ -572,9 +605,22 @@ export function planLoader(input: LoaderInput): LoaderPlan {
572
605
  return areas.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
573
606
  });
574
607
  if (copier === undefined) {
608
+ if (colours !== undefined) return undefined;
575
609
  const count = copierPages === 2 ? "two" : "three";
576
610
  throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in ${areas.map(show).join(" or ")} outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
577
611
  }
612
+ let colourRange: AddressRange | undefined;
613
+ if (colours !== undefined) {
614
+ // Outside the loader file, the copy of the colours writes over no source: it runs first, before a copy writes over its own source.
615
+ colourRange = freeColourRange([...input.segments, loaded, { start: copier, end: copier + copierBytes - 1 }]);
616
+ if (colourRange === undefined) return undefined;
617
+ const block = { what: "entry state colour RAM", range: colourRange, pseudo: colourRange.start, bytes: (address: number) => colours[address - colourRange!.start]! };
618
+ blocks.push(block);
619
+ packedAt.push(colourSource);
620
+ order.unshift(plain.length);
621
+ plain.push({ what: block.what, target: colourRange, source: { start: colourSource, end: colourSource + COLOURS - 1 } });
622
+ blockOf.push(colourRange.start);
623
+ }
578
624
  const copies: Copy[] = order.map((index) => {
579
625
  const copy = plain[index]!;
580
626
  return { ...copy, backward: copy.target.start > copy.source.start && overlaps(copy.target, copy.source) };
@@ -617,7 +663,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
617
663
  lines.push("}", blockLabel(block.range.start, "end"));
618
664
  }
619
665
  lines.push("", `; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`, COPIER_SOURCE, `!pseudopc ${formatC64Address(copier)} {`);
620
- lines.push(...copierLines(state, cia, stackByte, input.entryName ?? formatC64Address(input.entry), screen !== undefined));
666
+ lines.push(...copierLines(state, cia, stackByte, input.entryName ?? formatC64Address(input.entry), screen !== undefined, colourRange?.start));
621
667
  copies.forEach((copy, index) => {
622
668
  // A block that starts at $0000 skips $00/$01, which the loader sets last.
623
669
  const start = copyBlocks[index]!;
@@ -640,6 +686,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
640
686
  text: `${lines.join("\n")}\n`,
641
687
  ...(cia === undefined ? {} : { cia: cia.plan }),
642
688
  ...(screen === undefined ? {} : { startScreen: screen }),
689
+ ...(colourRange === undefined ? {} : { colours: colourRange }),
643
690
  };
644
691
  }
645
692
 
@@ -647,6 +694,23 @@ export function planLoader(input: LoaderInput): LoaderPlan {
647
694
  const BELOW_VECTORS = 0xfff9;
648
695
  /** Where the packed form puts the bytes of pages 0-3: the copier reads them with all RAM visible ($01 = $34). */
649
696
  const PIECE_AREA: AddressRange = { start: 0x0400, end: BELOW_VECTORS };
697
+ /** Where the colours of the colour RAM wait for the copier, which reads them with $01 = $35: RAM outside the I/O area, below the vectors. */
698
+ const COLOUR_AREAS: readonly AddressRange[] = [
699
+ { start: 0x0400, end: 0xcfff },
700
+ { start: 0xe000, end: BELOW_VECTORS },
701
+ ];
702
+
703
+ /**
704
+ * The first free range of the 1000 colours outside the taken ranges, or
705
+ * undefined when none holds them. The screen at $0400 comes last: the colours
706
+ * there show while the loader runs.
707
+ */
708
+ function freeColourRange(taken: AddressRange[]): AddressRange | undefined {
709
+ const free = COLOUR_AREAS.flatMap((area) => subtract(area, taken))
710
+ .sort((a, b) => Number(a.start < 0x0800) - Number(b.start < 0x0800))
711
+ .find((range) => range.end - range.start + 1 >= COLOURS);
712
+ return free === undefined ? undefined : { start: free.start, end: free.start + COLOURS - 1 };
713
+ }
650
714
 
651
715
  /**
652
716
  * Where a loader puts its copier: the copier sets $01 to $35 and then to the
@@ -669,9 +733,11 @@ const SHOWN_FREE = 8;
669
733
  * and the bytes of pages $0002-$03ff, in pieces in the free ranges: the
670
734
  * unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier
671
735
  * writes them after the unpack. Between its ranges, loader.asm holds the
672
- * bytes of the image, so its build does not change a segment.
736
+ * bytes of the image, so its build does not change a segment. The colours of
737
+ * the colour RAM are in one more free range, where the unpack puts them.
738
+ * Undefined when the colours have no room.
673
739
  */
674
- function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, copierCode: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
740
+ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, copierCode: number, screen: StartScreenPlan | undefined, tooLarge: string, colours: Uint8Array | undefined): LoaderPlan | undefined {
675
741
  const { state } = input;
676
742
  // The packed copier starts with SEI, as the stub of the plain form does: an interrupt in the copies would go through the vectors in RAM.
677
743
  const codeSize = copierCode + 1;
@@ -703,8 +769,11 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
703
769
  const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
704
770
  // The sources are at $0400 or higher and the targets below: any order works.
705
771
  const copies: Copy[] = pieces.map((piece) => ({ what: piece.what, target: piece.target, source: { start: piece.at, end: piece.at + piece.target.end - piece.target.start }, backward: false }));
706
- const start = Math.min(copier, ...pieces.map((piece) => piece.at));
707
- const end = Math.max(copierEnd, ...copies.map((copy) => copy.source.end));
772
+ const colourRange = colours === undefined ? undefined : freeColourRange([...input.segments, { start: copier, end: copierEnd }, ...copies.map((copy) => copy.source)]);
773
+ if (colours !== undefined && colourRange === undefined) return undefined;
774
+ const colourBytes = (address: number) => colours![address - colourRange!.start]!;
775
+ const start = Math.min(copier, ...pieces.map((piece) => piece.at), ...(colourRange === undefined ? [] : [colourRange.start]));
776
+ const end = Math.max(copierEnd, ...copies.map((copy) => copy.source.end), ...(colourRange === undefined ? [] : [colourRange.end]));
708
777
  const stackByte = 0x0100 + state.sp;
709
778
  const lines: string[] = [
710
779
  ...input.header.map((line) => `; ${line}`),
@@ -725,7 +794,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
725
794
  COPIER_SOURCE,
726
795
  " sei",
727
796
  // The entry by its address: main.asm, which has its label, is not in this build.
728
- ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined),
797
+ ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined, colourRange?.start),
729
798
  ];
730
799
  for (const copy of copies) {
731
800
  const [from, to] = [blockLabel(copy.target.start, "from"), blockLabel(copy.target.start, "end")];
@@ -738,6 +807,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
738
807
  const text = [`; ${piece.what}`, `* = ${formatC64Address(piece.at)}`, blockLabel(piece.target.start, "from"), ...byteLines(piece.target, piece.bytes), blockLabel(piece.target.start, "end")];
739
808
  parts.push({ range, text });
740
809
  }
810
+ if (colourRange !== undefined) parts.push({ range: colourRange, text: ["; The colour RAM of the entry state: the copier puts it into $d800-$dbe7", `* = ${formatC64Address(colourRange.start)}`, ...byteLines(colourRange, colourBytes)] });
741
811
  const used = parts.map((part) => part.range);
742
812
  for (const segment of input.segments) {
743
813
  const within = { start: Math.max(segment.start, start), end: Math.min(segment.end, end) };
@@ -750,7 +820,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
750
820
  for (const part of parts) lines.push("", ...part.text);
751
821
  return {
752
822
  loaded: input.segments.map(({ start, end }) => ({ start, end })),
753
- blocks: pieces.map((piece) => ({ what: piece.what, range: piece.target, packedAt: piece.at, bytes: piece.bytes })),
823
+ blocks: [...pieces.map((piece) => ({ what: piece.what, range: piece.target, packedAt: piece.at, bytes: piece.bytes })), ...(colourRange === undefined ? [] : [{ what: "entry state colour RAM", range: colourRange, packedAt: colourRange.start, bytes: colourBytes }])],
754
824
  copies,
755
825
  copier,
756
826
  stackByte,
@@ -758,6 +828,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
758
828
  text: `${lines.join("\n")}\n`,
759
829
  ...(cia === undefined ? {} : { cia: cia.plan }),
760
830
  ...(screen === undefined ? {} : { startScreen: screen }),
831
+ ...(colourRange === undefined ? {} : { colours: colourRange }),
761
832
  packed: { start },
762
833
  };
763
834
  }
@@ -893,9 +964,10 @@ export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint
893
964
  * the stack pointer, the flags and A/X/Y, and the jump to the entry. It ends
894
965
  * with the label of the table; the caller writes the table and closes the zone.
895
966
  * A start screen comes after the copies, which put its bytes in place, and
896
- * before the VIC-II part, which sets the display of the entry again.
967
+ * before the VIC-II part, which sets the display of the entry again. The
968
+ * colours come after the start screen, which writes the colour RAM.
897
969
  */
898
- function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stackByte: number, jumpTarget: string, startScreen: boolean): string[] {
970
+ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stackByte: number, jumpTarget: string, startScreen: boolean, colours: number | undefined): string[] {
899
971
  const [port0, port1] = state.port;
900
972
  return [
901
973
  "!zone loader_copier {",
@@ -953,6 +1025,7 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
953
1025
  " jmp .next",
954
1026
  ".done",
955
1027
  ...(startScreen ? START_SCREEN_LINES : []),
1028
+ ...(colours === undefined ? [] : colourLines(colours)),
956
1029
  // The CIA part runs after the raster wait: the wait ends its whole lines earlier, so the entry comes in its line.
957
1030
  ...vicLines(state, Math.floor((cia?.ops.reduce((sum, op) => sum + op.cycles, 0) ?? 0) / LINE_CYCLES)),
958
1031
  ...(cia === undefined ? [] : cia.ops.map((op) => ` ${op.text}`)),
@@ -984,6 +1057,23 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
984
1057
  ];
985
1058
  }
986
1059
 
1060
+ /**
1061
+ * The copier's colour part: with the I/O area visible, it copies the 1000
1062
+ * colours of the entry state from `at` into the colour RAM, in four parts of 250.
1063
+ */
1064
+ function colourLines(at: number): string[] {
1065
+ const parts = [0, 250, 500, 750];
1066
+ return [
1067
+ " lda #$35",
1068
+ " sta $01",
1069
+ " ldx #0",
1070
+ ...parts.flatMap((offset, index) => [`${index === 0 ? ".colour " : " "}lda ${formatC64Address(at + offset)},x`, ` sta ${formatC64Address(0xd800 + offset)},x`]),
1071
+ " inx",
1072
+ ` cpx #${formatC64Byte(250)}`,
1073
+ " bne .colour",
1074
+ ];
1075
+ }
1076
+
987
1077
  /**
988
1078
  * The copier's VIC-II part: with the I/O area visible it sets the
989
1079
  * display registers and the VIC bank of the entry state, then waits for the
@@ -651,6 +651,12 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
651
651
  const wanted = rasterLine(state.vic.registers);
652
652
  if (line !== wanted && line !== wanted + 1) differences.push(`the raster line is ${line}, not ${wanted}`);
653
653
  }
654
+ if (plan.colours !== undefined && state.colourRam !== undefined) {
655
+ // The colour RAM: the first wrong colour.
656
+ const colours = Buffer.from((await client.ioRead(0xd800, state.colourRam.length)).data, "hex");
657
+ const wrong = state.colourRam.findIndex((value, offset) => (colours[offset]! & 0x0f) !== value);
658
+ if (wrong >= 0) differences.push(`the colour RAM has ${colours[wrong]! & 0x0f} at ${formatC64Address(0xd800 + wrong)}, not ${state.colourRam[wrong]}`);
659
+ }
654
660
  if (plan.cia !== undefined) {
655
661
  // The CIA timers: at the jump a running timer is 3 cycles, the JMP, before its value at the entry.
656
662
  const chips = (await client.cia("both")).chips;
@@ -987,7 +993,14 @@ async function buildLoader(
987
993
  const program = loaderBuilt.program;
988
994
  const memory = new Int16Array(0x10000).fill(-1);
989
995
  program.subarray(2).forEach((byte, offset) => (memory[loaderBuilt.start! + offset] = byte));
990
- const expected = (address: number) => (loader.loaded.some((part) => address >= part.start && address <= part.end) ? main.program[2 + address - main.start]! : state.pages[address]!);
996
+ // The plain form also copies the colours of the colour RAM to a free range, where the copier reads them.
997
+ const colours = loader.colours;
998
+ const expected = (address: number) =>
999
+ loader.loaded.some((part) => address >= part.start && address <= part.end)
1000
+ ? main.program[2 + address - main.start]!
1001
+ : colours !== undefined && address >= colours.start && address <= colours.end
1002
+ ? state.colourRam![address - colours.start]!
1003
+ : state.pages[address]!;
991
1004
  const wrongPacking = loader.blocks.find((block) => {
992
1005
  for (let address = block.range.start; address <= block.range.end; address++) if (memory[block.packedAt + address - block.range.start] !== block.bytes(address)) return true;
993
1006
  return false;
@@ -30,6 +30,7 @@ To get the command list, run the script with no arguments.
30
30
  | Record a play session of a person on the reference | `record tests/record/start.json --out tests/recordings/play1 --play --joystick 1` |
31
31
  | Record a session from steps only | `record tests/record/rooms.json --out tests/recordings/rooms` |
32
32
  | Make sure that a recording replays on the reference | `replay tests/recordings/rooms` |
33
+ | Keep the screen at the end of a recorded session | `replay tests/recordings/final --screen .c64-re-tools/local/results/final.png` |
33
34
  | Compare the rebuild with a recording | `replay tests/recordings/rooms --checkpoint main_loop --state room --state lives --pin random_ptr:2 --rebuild build/clean.prg --symbols build/symbols/clean.json --out .c64-re-tools/local/results/rooms` |
34
35
  | Find what changed between two snapshot files | `diff .c64-re-tools/local/runs/rooms/before.vsf .c64-re-tools/local/runs/rooms/after.vsf` |
35
36
  | Find what changed between two observations of runs | `diff .c64-re-tools/local/runs/rooms/results.json:room0 .c64-re-tools/local/runs/rooms/results.json:room3` |
@@ -88,6 +89,7 @@ Each flag applies only to the commands in the table. On another command, the scr
88
89
  | `--rebuild <prg>` | `replay` | The rebuild to compare with the reference. Without it, the script replays only on the reference. |
89
90
  | `--symbols <file>` | `replay` | The symbol file of the rebuild. The default is the symbols of the recording. |
90
91
  | `--out <dir>` | `replay` | With a FAIL, write the RAM of each side at the first different checkpoint into this folder. |
92
+ | `--screen <png>` | `replay` | Write the screen of the reference at the end of the session into this PNG file. |
91
93
  | `--gap <n>` | `diff` | Join changed ranges across at most n equal bytes. The default is 0. |
92
94
  | `--max-listed <n>` | `diff` | List at most n items of each list. The default is 50. |
93
95
  | `--ntsc` | `diff` | The snapshot files are of an NTSC machine. The default is PAL. |
@@ -185,7 +187,7 @@ A recording keeps a session of the reference program, for example a play through
185
187
  - Commit the recording folder with the scenarios. Do not put a recording into the project knowledge. Do not put test results, screenshots or playtest results into it.
186
188
  - A finding that a recording shows can go into the project knowledge. Give the `recording.json` of the recording as its test evidence.
187
189
  - The C64 of a recording has no disk drive. For a program that loads more files from a disk, use a scenario with `test`.
188
- - The emulator cannot examine the C64 of a recording or a replay.
190
+ - The emulator cannot examine the C64 of a recording or a replay. To keep the screen at the end of a recorded session, use `--screen` of `replay`.
189
191
 
190
192
  A replay is deterministic. The same recording gives the same session, to the cycle. The n-th read of an input at each instruction gets the value of the n-th read in the recording. Thus a rebuild with different timing gets the same input, also the same random values from the SID.
191
193
 
@@ -239,6 +241,7 @@ The script first replays the recording on the reference. The reference must end
239
241
 
240
242
  `--checkpoint` and `--state` go together. `--pin` needs both of them. `--symbols` needs `--rebuild`. Give at most 16 `--state` and `--pin` items. Without `--checkpoint`, the script uses the comparison of the record file.
241
243
  A `$` address is an address of the reference. On the rebuild, it moves with the name before it.
244
+ `--screen` writes the screen of the reference at the end of the session into a PNG file. The screen is the same on each replay. The script writes it only when the reference ends the session with the recorded state.
242
245
 
243
246
  A rebuild can be a loader with a start screen that RUN starts. If the symbols of the rebuild have `loader_start_screen_wait` and `loader_start_screen_continue`, the script runs the rebuild to the wait. Then it sets the PC to `loader_start_screen_continue`. The cycles before the wait do not count.
244
247
 
@@ -259,6 +262,7 @@ Do this for each result:
259
262
 
260
263
  Traps:
261
264
 
265
+ - A run does not have the timing of a recording. The same steps in a run can give a different session, for example a lost fight. To show the screen of a recorded session, use `replay --screen`. Do not do the steps again in a run.
262
266
  - `idleReads` counts the input reads of the rebuild that the recording had no value for. On the reference, such a read makes the result INCONCLUSIVE. The rebuild can read input where the reference does not, for example in its loader before the start screen. Such reads do not change a PASS of the rebuild.
263
267
  - The script refuses a recording of an older version in an old form with `invalid-input`. Record the session again.
264
268
 
@@ -149,3 +149,4 @@ The body of the envelope of `replay` has these fields:
149
149
  - `startScreen`: `skipped` when the rebuild went past the wait of its start screen.
150
150
  - `idleReads`: the input reads of the rebuild that the recording had no value for. Such a read is at a site that the recording does not have, or after its end. Each got the fixed value `$FF` (joystick, keyboard, paddles) or `$00`. An input site that the site map did not find shows here.
151
151
  - `files`: with `--out`, the RAM of each side at the first different checkpoint, `reference-<n>.bin` and `rebuild-<n>.bin`.
152
+ - `screen`: with `--screen`, the PNG file of the screen of the reference at the end of the session.
@@ -894,4 +894,6 @@ export interface ReplayResult {
894
894
  /** Input reads of the rebuild that the recording had no value for: they got the idle value. */
895
895
  idleReads?: number;
896
896
  files?: Written[];
897
+ /** The screen of the reference at the end of the session (--screen). */
898
+ screen?: Written;
897
899
  }
@@ -10,6 +10,7 @@ import { isRefusal, Refusal } from "#src/errors.ts";
10
10
  import { readPrg } from "#src/host-client/image.ts";
11
11
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
12
12
  import { formatC64Address } from "#src/c64.ts";
13
+ import { encodePng } from "#src/graphics.ts";
13
14
  import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
14
15
  import { C64RunSession } from "#src/native/c64run.ts";
15
16
  import { localToolContext } from "#src/native/local.ts";
@@ -28,6 +29,8 @@ export interface ReplayOptions {
28
29
  rebuild?: string;
29
30
  symbols?: string;
30
31
  out?: string;
32
+ /** A PNG file for the screen of the reference at the end of the session. */
33
+ screen?: string;
31
34
  }
32
35
 
33
36
  /** Replays the recording on the reference, and with `rebuild` on the rebuild: PASS, FAIL or INCONCLUSIVE. */
@@ -41,6 +44,7 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
41
44
  const given: Comparison | undefined =
42
45
  values.checkpoint === undefined ? undefined : { checkpoint: values.checkpoint, state: values.state.map((item) => parseStateItem(item, "--state")), ...(values.pin.length === 0 ? {} : { pin: values.pin.map((item) => parseStateItem(item, "--pin")) }) };
43
46
  const compare = given ?? recording.compare;
47
+ let screen: Written | undefined;
44
48
  if (values.rebuild !== undefined && compare === undefined) throw new UsageError("The recording has no checkpoint and state for --rebuild. Give --checkpoint and --state.");
45
49
  const result = (outcome: ReplayResult["result"], side: ReplayResult["side"], fields: Partial<ReplayResult> = {}): ReplayResult => ({
46
50
  result: outcome,
@@ -49,6 +53,7 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
49
53
  ...(compare === undefined ? {} : { checkpoint: compare.checkpoint }),
50
54
  checkpoints: 0,
51
55
  compared: 0,
56
+ ...(screen === undefined ? {} : { screen }),
52
57
  ...fields,
53
58
  });
54
59
  // The files of the rebuild are checked before the replay core starts.
@@ -88,6 +93,11 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
88
93
  if (self.end.tick !== recording.ticks || self.end.hash !== recording.hash) {
89
94
  return result("INCONCLUSIVE", "reference", { reason: "the recording does not reproduce on the reference: the state at its end is different; record the session again with this version of the toolkit" });
90
95
  }
96
+ // The core is still at the end of the session: the rebuild side starts it again.
97
+ if (values.screen !== undefined) {
98
+ const shot = await core.screen();
99
+ screen = writeReported(values.screen, encodePng(shot.frame, shot.palette), { what: "--screen" });
100
+ }
91
101
  const expected = self.samples;
92
102
  if (compare !== undefined && expected.length === 0) return result("INCONCLUSIVE", "reference", { reason: `the reference never came to the checkpoint ${compare.checkpoint} in the session` });
93
103
  if (values.rebuild === undefined) return result("PASS", "reference", { checkpoints: expected.length });
@@ -198,11 +198,12 @@ const COMMANDS: CommandSpec[] = [
198
198
  rebuild: { kind: "path", value: "<prg>", help: "the rebuild to compare with the reference" },
199
199
  symbols: { ...OPTIONS.symbols, help: "the names of the rebuild: the symbol file of its build (default: the symbols of the recording)" },
200
200
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "with a FAIL, write the RAM of both sides at the first different checkpoint into this folder" },
201
+ screen: { ...OPTIONS.out, output: "file", value: "<png>", help: "write the screen of the reference at the end of the session into this PNG file" },
201
202
  },
202
203
  notes: "A recording without names takes the names of the knowledge for the reference. A $ address is an address of the reference: on the rebuild it moves with the name before it.",
203
204
  run: async (call) => {
204
- const [checkpoint, rebuild, symbols, out] = [call.string("checkpoint"), call.string("rebuild"), call.string("symbols"), call.string("out")];
205
- const result = await replay({ folder: call.subject(0), state: call.strings("state"), pin: call.strings("pin"), ...(checkpoint === undefined ? {} : { checkpoint }), ...(rebuild === undefined ? {} : { rebuild }), ...(symbols === undefined ? {} : { symbols }), ...(out === undefined ? {} : { out }) });
205
+ const [checkpoint, rebuild, symbols, out, screen] = [call.string("checkpoint"), call.string("rebuild"), call.string("symbols"), call.string("out"), call.string("screen")];
206
+ const result = await replay({ folder: call.subject(0), state: call.strings("state"), pin: call.strings("pin"), ...(checkpoint === undefined ? {} : { checkpoint }), ...(rebuild === undefined ? {} : { rebuild }), ...(symbols === undefined ? {} : { symbols }), ...(out === undefined ? {} : { out }), ...(screen === undefined ? {} : { screen }) });
206
207
  if (result.result === "INCONCLUSIVE") return reply(result, { hint: INCONCLUSIVE_HINT });
207
208
  if (result.result !== "FAIL") return result;
208
209
  const [reference, rebuilt] = result.files ?? [];
@@ -184,6 +184,17 @@ export class C64RunSession {
184
184
  return Buffer.concat(parts);
185
185
  }
186
186
 
187
+ /** The visible screen now, as palette indices, with the 16 colours of the palette. */
188
+ async screen(): Promise<{ frame: { width: number; height: number; pixels: Uint8Array }; palette: Array<[number, number, number]> }> {
189
+ const [, width, height, pixels] = (await this.command("frame")).split(" ");
190
+ const byte = (hex: string, at: number) => Number.parseInt(hex.slice(at, at + 2), 16);
191
+ const palette = (await this.command("palette"))
192
+ .split(" ")
193
+ .slice(1)
194
+ .map((hex): [number, number, number] => [byte(hex, 0), byte(hex, 2), byte(hex, 4)]);
195
+ return { frame: { width: Number(width), height: Number(height), pixels: Buffer.from(pixels ?? "", "base64") }, palette };
196
+ }
197
+
187
198
  /** Ends c64run: quit, then the stop of its process group (at once when it ended, else after STOP_MS). */
188
199
  async close(): Promise<void> {
189
200
  if (this.#ended === undefined) {