@henols/c64-re-tools 2.4.0 → 2.5.0

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.
@@ -7,12 +7,18 @@
7
7
  // overwrites the packed bytes of a copy that has not run yet. The plan is
8
8
  // simulated here before the emulator runs it. An image too large for one
9
9
  // loader file gets the packed form: Exomizer unpacks the program and the
10
- // copier, and the copier writes only pages $0002-$03ff.
10
+ // copier, and the copier writes only pages $0002-$03ff. With a start
11
+ // screen in the knowledge, the copier shows it after the copies and waits for
12
+ // a key or a fire button: the code is start-screen.asm, the same for each program.
13
+
14
+ import { readFileSync } from "node:fs";
15
+ import { fileURLToPath } from "node:url";
11
16
 
12
17
  import { type AddressRange, formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
13
18
  import { compareBuild, mergedPrograms } from "#src/compare.ts";
14
19
  import { Refusal } from "#src/errors.ts";
15
20
  import { parseEntryState } from "#src/host-client/entry-state.ts";
21
+ import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
16
22
  import { WireFailure } from "#src/host-client/tools.ts";
17
23
  import { pack } from "#src/native/exomizer.ts";
18
24
  import type { ToolContext } from "#src/native/run.ts";
@@ -111,6 +117,8 @@ export interface LoaderPlan {
111
117
  cia?: CiaPlan;
112
118
  /** The packed form: loader.asm holds only the copier and pages 0-3 from `start` to `end`, and Exomizer packs it with the build of main.asm. */
113
119
  packed?: { start: number };
120
+ /** The VIC-II values that the start screen sets, when the knowledge has one. */
121
+ startScreen?: StartScreenPlan;
114
122
  }
115
123
 
116
124
  /**
@@ -126,6 +134,65 @@ export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
126
134
 
127
135
  /** The label of the loader's jump to the entry, in ACME's symbol list. */
128
136
  export const LOADER_JUMP = "c64_source_loader_jump";
137
+ /** The labels of the start screen: its wait for a key or a fire button, and the code after the wait. */
138
+ export const START_SCREEN_WAIT = "loader_start_screen_wait";
139
+ export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
140
+ /** The file of the start screen in the generated source. */
141
+ export const START_SCREEN_FILE = "start_screen.asm";
142
+ /** The code of the start screen: the same for each program. loader.asm sets its values. */
143
+ export const START_SCREEN_CODE = readFileSync(fileURLToPath(new URL("./start-screen.asm", import.meta.url)), "utf8");
144
+ /** The bytes of the start screen code for each colour mode: none, one colour, a copy of 1000 bytes. */
145
+ export const START_SCREEN_SIZES = [197, 216, 226] as const;
146
+
147
+ /** The VIC-II values of a start screen, as the start screen code sets them. */
148
+ export interface StartScreenPlan {
149
+ d011: number;
150
+ d016: number;
151
+ d018: number;
152
+ /** The VIC bank: 0 for $0000-$3fff to 3 for $c000-$ffff. */
153
+ bank: number;
154
+ border: number;
155
+ background: number;
156
+ /** 0: no colour RAM (hires), 1: one colour, 2: a copy of 1000 bytes. */
157
+ colourMode: 0 | 1 | 2;
158
+ }
159
+
160
+ /** The VIC-II values that show a start screen of the knowledge. */
161
+ export function startScreenPlan(row: StartScreenRow): StartScreenPlan {
162
+ const bank = row.screen >> 14;
163
+ const base = (row.bitmap === undefined ? ((row.charset! & 0x3fff) >> 11) << 1 : ((row.bitmap & 0x3fff) >> 13) << 3) | 0x01;
164
+ return {
165
+ d011: row.mode === "text" ? 0x1b : 0x3b,
166
+ d016: row.mode === "multicolour" ? 0x18 : 0x08,
167
+ d018: (((row.screen & 0x3fff) >> 10) << 4) | base,
168
+ bank,
169
+ border: row.border,
170
+ background: row.background,
171
+ colourMode: row.colours !== undefined ? 2 : row.colour !== undefined ? 1 : 0,
172
+ };
173
+ }
174
+
175
+ /** The lines of loader.asm that give the start screen code its values. */
176
+ function startScreenValues(row: StartScreenRow, plan: StartScreenPlan): string[] {
177
+ const value = (name: string, number: number, comment?: string) => `c64_source_ss_${name} = ${formatC64Byte(number)}${comment === undefined ? "" : ` ; ${comment}`}`;
178
+ const font = row.charset !== undefined && isRomFont(row.charset) ? " (the character ROM)" : "";
179
+ const what = [`screen ${formatC64Address(row.screen)}`, ...(row.bitmap === undefined ? [] : [`bitmap ${formatC64Address(row.bitmap)}`]), ...(row.charset === undefined ? [] : [`charset ${formatC64Address(row.charset)}${font}`])];
180
+ return [
181
+ `; The start screen: ${row.mode}, ${what.join(", ")}.${row.comment === undefined ? "" : ` ${row.comment.replace(/\s*\r?\n\s*/g, " ")}`}`,
182
+ value("d011", plan.d011),
183
+ value("d016", plan.d016),
184
+ value("d018", plan.d018),
185
+ value("bank", 3 - plan.bank, `VIC bank ${formatC64Address(plan.bank << 14)}-${formatC64Address((plan.bank << 14) + 0x3fff)}`),
186
+ value("border", plan.border),
187
+ value("background", plan.background),
188
+ value("colour_mode", plan.colourMode),
189
+ value("colour", row.colour ?? 0),
190
+ `c64_source_ss_colours = ${formatC64Address(row.colours ?? 0)}`,
191
+ ];
192
+ }
193
+
194
+ /** The copier lines that include the start screen code, in a zone of its own. */
195
+ const START_SCREEN_LINES = ["!zone c64_source_start_screen {", `!source "${START_SCREEN_FILE}"`, "}"];
129
196
 
130
197
  const LOAD = 0x0801;
131
198
  const STUB = 0x080d;
@@ -136,14 +203,21 @@ const COPIER_CODE_SIZE = 167;
136
203
  /** The VIC-II code of the copier, without its two tables of one byte per register. */
137
204
  const VIC_CODE_SIZE = 44;
138
205
  const VIC_SIZE = VIC_CODE_SIZE + 2 * VIC_DISPLAY_REGISTERS.length;
139
- /** The copier and the stub's move of it: two pages. */
206
+ /** The copier and the stub's move of it: two pages, or three with a start screen. */
140
207
  const COPIER_LIMIT = 0x200;
208
+ /** The bytes that the stub adds for each more page of the copier: lda and sta. */
209
+ const STUB_PAGE_SIZE = 6;
141
210
  const COPY_ENTRY = 7;
142
- /** X indexes the table, so the table fits in 256 bytes, and the copier with the VIC-II code fits in two pages. */
143
- export const MAX_COPIES = Math.min(Math.floor((256 - 2) / COPY_ENTRY), Math.floor((COPIER_LIMIT - COPIER_CODE_SIZE - VIC_SIZE - 2) / COPY_ENTRY));
211
+ /** X indexes the table, so the table holds at most this many copies in 256 bytes. */
212
+ const TABLE_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
144
213
  /** A loader that loads into $d000 or higher would write the I/O area. */
145
214
  const LOAD_LIMIT = 0xcfff;
146
215
  const COPIER_PAGES = [...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100), ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100)];
216
+ /** The areas where the copier can run: RAM that no ROM and no I/O hides when $01 is $34 or $35, above the screen at $0400. */
217
+ const COPIER_AREAS: readonly AddressRange[] = [
218
+ { start: 0x0400, end: 0x9fff },
219
+ { start: 0xc000, end: 0xcfff },
220
+ ];
147
221
 
148
222
  const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
149
223
  const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
@@ -383,6 +457,30 @@ export interface LoaderInput {
383
457
  switches?: boolean;
384
458
  /** The source has macros.asm: the loader includes it after the constants. */
385
459
  macros?: boolean;
460
+ /** The source has config.asm but no switches.asm: the loader includes config.asm for START_SCREEN. */
461
+ config?: boolean;
462
+ /** The start screen of the knowledge: the copier shows it after the copies. */
463
+ startScreen?: StartScreenRow;
464
+ }
465
+
466
+ /** The checks of a start screen against the program and the entry state. Refuses by name. */
467
+ function checkStartScreen(input: LoaderInput): StartScreenPlan | undefined {
468
+ const row = input.startScreen;
469
+ if (row === undefined) return undefined;
470
+ if (input.state.vic === undefined) {
471
+ throw new WireFailure("invalid-input", "The entry state has no VIC-II values, so the loader cannot set the display of the program after the start screen. Capture the program again at its entry point, or remove the start screen (unstart-screen).");
472
+ }
473
+ for (const { what, range } of startScreenRanges(row)) {
474
+ const inside = input.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
475
+ if (!inside) throw new WireFailure("invalid-input", `The start screen part ${what} (${show(range)}) is not in one segment of the program. The start screen must be in memory at the entry: capture it with the program, or correct the start screen in the knowledge.`);
476
+ }
477
+ return startScreenPlan(row);
478
+ }
479
+
480
+ /** The settings that loader.asm includes: switches.asm, else config.asm for a start screen, else none. */
481
+ function settingsLines(input: LoaderInput): string[] {
482
+ if (input.switches === true) return ['!source "switches.asm"'];
483
+ return input.config === true ? ['!source "config.asm"'] : [];
386
484
  }
387
485
 
388
486
  /** The label of a block: its first byte and the byte after it in the loader file, and its first address where it runs. */
@@ -416,6 +514,9 @@ function byteLines(range: AddressRange, bytes: (address: number) => number): str
416
514
  */
417
515
  export function planLoader(input: LoaderInput): LoaderPlan {
418
516
  const { state } = input;
517
+ const screen = checkStartScreen(input);
518
+ const copierBytes = screen === undefined ? COPIER_LIMIT : COPIER_LIMIT + 0x100;
519
+ const copierPages = copierBytes >> 8;
419
520
  // What the copies write: each segment without $00/$01, which the loader sets last, and pages $0002-$03ff where no segment is.
420
521
  const blocks: Block[] = [];
421
522
  for (const segment of input.segments) blocks.push({ what: `segment ${show(segment)}`, range: segment, files: segment.files, pseudo: segment.start, bytes: input.byteAt });
@@ -424,7 +525,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
424
525
  }
425
526
  blocks.sort((a, b) => a.range.start - b.range.start);
426
527
 
427
- let at = STUB + STUB_SIZE;
528
+ let at = STUB + STUB_SIZE + (copierPages - 2) * STUB_PAGE_SIZE;
428
529
  const plain: Array<Omit<Copy, "backward">> = [];
429
530
  const packedAt: number[] = [];
430
531
  /** The block start of each copy in `plain`, which names its labels. */
@@ -441,13 +542,13 @@ export function planLoader(input: LoaderInput): LoaderPlan {
441
542
  }
442
543
  const cia = ciaSection(state);
443
544
  const ciaSize = cia === undefined ? 0 : cia.ops.reduce((sum, op) => sum + op.bytes, 0);
444
- const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize;
545
+ const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize + (screen === undefined ? 0 : START_SCREEN_SIZES[screen.colourMode]);
445
546
  const copierImage = at;
446
547
  const end = copierImage + codeSize + COPY_ENTRY * plain.length + 2 - 1;
447
548
  // The end can be past $ffff, which is no address.
448
- if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`);
449
- // The CIA part takes room from the copy table in the copier's two pages.
450
- const maxCopies = Math.min(MAX_COPIES, Math.floor((COPIER_LIMIT - codeSize - 2) / COPY_ENTRY));
549
+ 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.`);
550
+ // The CIA part and the start screen take room from the copy table in the copier's pages.
551
+ const maxCopies = Math.max(0, Math.min(TABLE_COPIES, Math.floor((copierBytes - codeSize - 2) / COPY_ENTRY)));
451
552
  if (plain.length > maxCopies) throw new WireFailure("invalid-input", `The loader needs ${plain.length} copies; it can do at most ${maxCopies}. Capture the program again with fewer segments, or write the loader by hand.`);
452
553
 
453
554
  const order = copyOrder(plain);
@@ -457,10 +558,13 @@ export function planLoader(input: LoaderInput): LoaderPlan {
457
558
  }
458
559
  const loaded = { start: LOAD, end };
459
560
  const copier = COPIER_PAGES.find((page) => {
460
- const pages = { start: page, end: page + 0x1ff };
461
- return !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
561
+ const pages = { start: page, end: page + copierBytes - 1 };
562
+ return COPIER_AREAS.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
462
563
  });
463
- if (copier === undefined) throw new WireFailure("invalid-input", `No two free pages exist for the copier in $0400-$9fff or $c000-$cfff outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
564
+ if (copier === undefined) {
565
+ const count = copierPages === 2 ? "two" : "three";
566
+ throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in $0400-$9fff or $c000-$cfff outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
567
+ }
464
568
  const copies: Copy[] = order.map((index) => {
465
569
  const copy = plain[index]!;
466
570
  return { ...copy, backward: copy.target.start > copy.source.start && overlaps(copy.target, copy.source) };
@@ -468,7 +572,17 @@ export function planLoader(input: LoaderInput): LoaderPlan {
468
572
  const copyBlocks = order.map((index) => blockOf[index]!);
469
573
 
470
574
  const stackByte = 0x0100 + state.sp;
471
- const lines: string[] = [...input.header.map((line) => `; ${line}`), "", "!cpu 6510", ...(input.switches === true ? ['!source "switches.asm"'] : []), '!source "constants.asm"', ...(input.macros ? ['!source "macros.asm"'] : []), "", `* = ${formatC64Address(LOAD)}`];
575
+ const lines: string[] = [
576
+ ...input.header.map((line) => `; ${line}`),
577
+ "",
578
+ "!cpu 6510",
579
+ ...settingsLines(input),
580
+ '!source "constants.asm"',
581
+ ...(input.macros ? ['!source "macros.asm"'] : []),
582
+ ...(screen === undefined ? [] : ["", ...startScreenValues(input.startScreen!, screen)]),
583
+ "",
584
+ `* = ${formatC64Address(LOAD)}`,
585
+ ];
472
586
  lines.push(` !byte $0b,$08,$0a,$00,$9e,${[...String(STUB)].map((digit) => formatC64Byte(digit.charCodeAt(0))).join(",")},$00,$00,$00 ; 10 SYS ${STUB}`);
473
587
  lines.push(
474
588
  "!zone loader_stub {",
@@ -479,8 +593,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
479
593
  " ldx #0",
480
594
  `- lda ${COPIER_SOURCE},x`,
481
595
  ` sta ${formatC64Address(copier)},x`,
482
- ` lda ${COPIER_SOURCE}+$100,x`,
483
- ` sta ${formatC64Address(copier + 0x100)},x`,
596
+ ...Array.from({ length: copierPages - 1 }, (_, index) => [` lda ${COPIER_SOURCE}+$${((index + 1) * 0x100).toString(16)},x`, ` sta ${formatC64Address(copier + (index + 1) * 0x100)},x`]).flat(),
484
597
  " inx",
485
598
  " bne -",
486
599
  ` jmp ${formatC64Address(copier)}`,
@@ -494,7 +607,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
494
607
  lines.push("}", blockLabel(block.range.start, "end"));
495
608
  }
496
609
  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)} {`);
497
- lines.push(...copierLines(state, cia, stackByte, input.entryName ?? formatC64Address(input.entry)));
610
+ lines.push(...copierLines(state, cia, stackByte, input.entryName ?? formatC64Address(input.entry), screen !== undefined));
498
611
  copies.forEach((copy, index) => {
499
612
  // A block that starts at $0000 skips $00/$01, which the loader sets last.
500
613
  const start = copyBlocks[index]!;
@@ -515,6 +628,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
515
628
  end,
516
629
  text: `${lines.join("\n")}\n`,
517
630
  ...(cia === undefined ? {} : { cia: cia.plan }),
631
+ ...(screen === undefined ? {} : { startScreen: screen }),
518
632
  };
519
633
  }
520
634
 
@@ -536,7 +650,7 @@ const SHOWN_FREE = 8;
536
650
  * writes them after the unpack. Between its ranges, loader.asm holds the
537
651
  * bytes of the image, so its build does not change a segment.
538
652
  */
539
- function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, codeSize: number, tooLarge: string): LoaderPlan {
653
+ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, codeSize: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
540
654
  const { state } = input;
541
655
  // The parts below $0400 without $00/$01, which the loader sets last.
542
656
  const low = blocks.flatMap((block) => {
@@ -554,7 +668,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
554
668
  const why =
555
669
  placed.refusal === "copies"
556
670
  ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
557
- : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier, and ${lowBytes} more free bytes for pages 0-3, in $0400-$9fff or $c000-$cfff outside the segments.`;
671
+ : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier, and ${lowBytes} more free bytes for pages 0-3, in $0400-$9fff or $c000-$cfff outside the segments.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
558
672
  throw new WireFailure("invalid-input", `${tooLarge} ${why} The largest free ranges there: ${ranges}. Write the loader by hand.`);
559
673
  }
560
674
  const { copier, pieces } = placed;
@@ -571,6 +685,8 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
571
685
  "; The unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier writes pages $0002-$03ff after the unpack.",
572
686
  "",
573
687
  "!cpu 6510",
688
+ ...settingsLines(input),
689
+ ...(screen === undefined ? [] : ["", ...startScreenValues(input.startScreen!, screen)]),
574
690
  ];
575
691
  // The parts in address order: the copier, the pieces of pages 0-3, and the bytes of the image between them.
576
692
  const parts: Array<{ range: AddressRange; text: string[] }> = [];
@@ -579,7 +695,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
579
695
  `* = ${formatC64Address(copier)}`,
580
696
  COPIER_SOURCE,
581
697
  // The entry by its address: main.asm, which has its label, is not in this build.
582
- ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`),
698
+ ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined),
583
699
  ];
584
700
  for (const copy of copies) {
585
701
  const [from, to] = [blockLabel(copy.target.start, "from"), blockLabel(copy.target.start, "end")];
@@ -610,6 +726,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
610
726
  end,
611
727
  text: `${lines.join("\n")}\n`,
612
728
  ...(cia === undefined ? {} : { cia: cia.plan }),
729
+ ...(screen === undefined ? {} : { startScreen: screen }),
613
730
  packed: { start },
614
731
  };
615
732
  }
@@ -725,8 +842,10 @@ export async function packLoader(main: Uint8Array, copier: Uint8Array, plan: Loa
725
842
  * The copier: its copies by the table, the VIC-II and CIA parts, then $00/$01,
726
843
  * the stack pointer, the flags and A/X/Y, and the jump to the entry. It ends
727
844
  * with the label of the table; the caller writes the table and closes the zone.
845
+ * A start screen comes after the copies, which put its bytes in place, and
846
+ * before the VIC-II part, which sets the display of the entry again.
728
847
  */
729
- function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stackByte: number, jumpTarget: string): string[] {
848
+ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stackByte: number, jumpTarget: string, startScreen: boolean): string[] {
730
849
  const [port0, port1] = state.port;
731
850
  return [
732
851
  "!zone loader_copier {",
@@ -783,6 +902,7 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
783
902
  " tax",
784
903
  " jmp .next",
785
904
  ".done",
905
+ ...(startScreen ? START_SCREEN_LINES : []),
786
906
  // The CIA part runs after the raster wait: the wait ends its whole lines earlier, so the entry comes in its line.
787
907
  ...vicLines(state, Math.floor((cia?.ops.reduce((sum, op) => sum + op.cycles, 0) ?? 0) / LINE_CYCLES)),
788
908
  ...(cia === undefined ? [] : cia.ops.map((op) => ` ${op.text}`)),
@@ -14,11 +14,13 @@
14
14
  import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
15
15
  import { WireFailure } from "#src/host-client/tools.ts";
16
16
  import { identifiers, operandText, replaceIdentifiers, type OperandExpression } from "#src/knowledge/expression.ts";
17
- import { type CommentPlacement, isAnalyzer, isGeneratedFile, RELEASE_DEFINE, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
17
+ import { type CommentPlacement, isAnalyzer, isGeneratedFile, RELEASE_DEFINE, START_SCREEN_SWITCH, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
18
18
  import type { Area } from "#src/platform.ts";
19
19
  import { hasZeroPageForm, instructionWith, labelProblem, MODE_LENGTH, OPCODES, takesAddress, USE_KINDS, useKind, type UseKind } from "#src/opcodes.ts";
20
20
 
21
21
  export interface SourceInput {
22
+ /** The knowledge has a start screen: config.asm gets START_SCREEN. */
23
+ startScreen?: boolean;
22
24
  /** In address order, without overlap. */
23
25
  segments: AddressRange[];
24
26
  /** The image byte at an address inside a segment. */
@@ -250,6 +252,8 @@ export interface Layout {
250
252
  /** The macro uses that the source can write, by start. */
251
253
  macroUses: Map<number, MacroUseBlock>;
252
254
  macrosAsInstructions: MacroAsInstructions[];
255
+ /** The knowledge has a start screen: config.asm gets START_SCREEN. */
256
+ startScreen: boolean;
253
257
  }
254
258
 
255
259
  /** ACME reads leading zeros as a 16-bit value, so a zero-page name gets two digits. */
@@ -653,6 +657,7 @@ export function layout(input: SourceInput): Layout {
653
657
  macros: [...(input.macros ?? [])].sort((a, b) => (a.name < b.name ? -1 : 1)),
654
658
  macroUses: usesWritten,
655
659
  macrosAsInstructions: macrosAsInstructions.sort((a, b) => a.start - b.start),
660
+ startScreen: input.startScreen === true,
656
661
  };
657
662
  }
658
663
 
@@ -899,6 +904,9 @@ const SWITCH_GROUPS: ReadonlyArray<{ kind: SwitchKind; title: string }> = [
899
904
  /** True when the source has switches.asm: the knowledge has switches or releases. */
900
905
  export const hasSwitchFile = (layout: Pick<Layout, "switches" | "releases">) => layout.switches.length > 0 || layout.releases.length > 0;
901
906
 
907
+ /** True when the source has config.asm: the knowledge has switches or a start screen. */
908
+ export const hasConfigFile = (layout: Pick<Layout, "switches" | "startScreen">) => layout.switches.length > 0 || layout.startScreen;
909
+
902
910
  /** The file with the value of each switch. The user edits it, and generate keeps the values. */
903
911
  export const CONFIG_FILE = "config.asm";
904
912
 
@@ -920,7 +928,7 @@ export function configValues(text: string): Map<string, 0 | 1> {
920
928
  * kind. Without a value, a switch has its default. A comment tells the
921
929
  * releases that have the switch on, and its patches.
922
930
  */
923
- export function configText(layout: Pick<Layout, "switches" | "patches">, values: ReadonlyMap<string, number> = new Map()): string {
931
+ export function configText(layout: Pick<Layout, "switches" | "patches" | "startScreen">, values: ReadonlyMap<string, number> = new Map()): string {
924
932
  const patches = switchesOf(layout);
925
933
  const out = [
926
934
  "; Generated by c64-source. Edit the values here: generate keeps them.",
@@ -945,6 +953,9 @@ export function configText(layout: Pick<Layout, "switches" | "patches">, values:
945
953
  out.push(`${row.name.padEnd(width)} = ${values.get(row.name) ?? row.default} ; ${parts.join(". ")}`);
946
954
  }
947
955
  }
956
+ if (layout.startScreen) {
957
+ out.push("", "; Start screen: on by default", `${START_SCREEN_SWITCH} = ${values.get(START_SCREEN_SWITCH) ?? 1} ; the loader shows the start screen and waits for a key or a fire button. 0 starts the program at once`);
958
+ }
948
959
  return `${out.join("\n")}\n`;
949
960
  }
950
961
 
@@ -965,7 +976,7 @@ function switchesText(layout: Layout): string {
965
976
  for (const row of layout.switches) out.push(`${INDENT}${row.name} = ${row.releases.includes(release.label) ? 1 : 0}`);
966
977
  out.push("}");
967
978
  }
968
- if (layout.switches.length > 0) {
979
+ if (hasConfigFile(layout)) {
969
980
  const include = `!source "${CONFIG_FILE}"`;
970
981
  out.push("", layout.releases.reduceRight((inner, release) => `!ifndef ${RELEASE_DEFINE}${release.label} { ${inner} }`, include));
971
982
  }
@@ -1287,7 +1298,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1287
1298
  }
1288
1299
 
1289
1300
  if (hasSwitchFile(layout)) result.files.push({ name: "switches.asm", text: switchesText(layout) });
1290
- if (layout.switches.length > 0) result.files.push({ name: CONFIG_FILE, text: configText(layout) });
1301
+ if (hasConfigFile(layout)) result.files.push({ name: CONFIG_FILE, text: configText(layout) });
1291
1302
  const constants = constantsText(layout);
1292
1303
  result.files.push({ name: "constants.asm", text: constants.text });
1293
1304
  result.labels.push(...constants.labels);
@@ -0,0 +1,139 @@
1
+ ; The start screen of the program: the loader shows it after its copies and
2
+ ; waits for a key or a fire button on joystick port 1 or 2. Then the loader
3
+ ; sets the entry state and starts the program.
4
+ ; The loader includes this file in its copier, with the interrupts off. The
5
+ ; code uses no stack and writes only the I/O area, the colour RAM and its own
6
+ ; bytes: the copies wrote pages 0-3 of the entry state already.
7
+ ; Set START_SCREEN = 0 in config.asm to start the program at once.
8
+ ; loader.asm sets these values from the start screen of the knowledge:
9
+ ; c64_source_ss_d011, c64_source_ss_d016, c64_source_ss_d018: the VIC-II mode
10
+ ; c64_source_ss_bank: the VIC bank, as bits 0-1 of $dd00
11
+ ; c64_source_ss_border, c64_source_ss_background: the colours
12
+ ; c64_source_ss_colour_mode: 0 no colour RAM, 1 one colour, 2 a copy of 1000 bytes
13
+ ; c64_source_ss_colour: the one colour (mode 1)
14
+ ; c64_source_ss_colours: the address of the 1000 bytes (mode 2)
15
+
16
+ !ifndef START_SCREEN { START_SCREEN = 1 }
17
+
18
+ lda #START_SCREEN
19
+ bne .on
20
+ jmp .end
21
+ .port !byte 0
22
+ .ddra !byte 0
23
+ .ddrb !byte 0
24
+ .joy !byte 0
25
+
26
+ .on lda #$35
27
+ sta $01
28
+ ; CIA 1: port A drives the keyboard rows, port B reads the columns.
29
+ lda $dc00
30
+ sta .port
31
+ lda $dc02
32
+ sta .ddra
33
+ lda $dc03
34
+ sta .ddrb
35
+ lda #$ff
36
+ sta $dc02
37
+ lda #$00
38
+ sta $dc03
39
+ ; The display is off until the colour RAM is set.
40
+ lda #$0b
41
+ sta $d011
42
+ lda #$00
43
+ sta $d015
44
+ lda $dd00
45
+ and #$fc
46
+ ora #c64_source_ss_bank
47
+ sta $dd00
48
+ lda #c64_source_ss_d018
49
+ sta $d018
50
+ lda #c64_source_ss_d016
51
+ sta $d016
52
+ lda #c64_source_ss_border
53
+ sta $d020
54
+ lda #c64_source_ss_background
55
+ sta $d021
56
+ !if c64_source_ss_colour_mode = 1 {
57
+ lda #c64_source_ss_colour
58
+ ldx #250
59
+ .fill sta $d7ff,x
60
+ sta $d8f9,x
61
+ sta $d9f3,x
62
+ sta $daed,x
63
+ dex
64
+ bne .fill
65
+ }
66
+ !if c64_source_ss_colour_mode = 2 {
67
+ ldx #250
68
+ .copy lda c64_source_ss_colours-1,x
69
+ sta $d7ff,x
70
+ lda c64_source_ss_colours+249,x
71
+ sta $d8f9,x
72
+ lda c64_source_ss_colours+499,x
73
+ sta $d9f3,x
74
+ lda c64_source_ss_colours+749,x
75
+ sta $daed,x
76
+ dex
77
+ bne .copy
78
+ }
79
+ lda #c64_source_ss_d011
80
+ sta $d011
81
+
82
+ ; Y is the phase: 0 waits until nothing is pressed, for example the
83
+ ; RETURN of RUN; 1 waits for a press; 2 waits until it is released.
84
+ loader_start_screen_wait
85
+ ldy #0
86
+ .poll lda #$ff
87
+ sta $dc00
88
+ ; No keyboard row is driven: $dc01 gives joystick 1 alone.
89
+ lda $dc01
90
+ sta .joy
91
+ and #$10
92
+ beq .down
93
+ lda $dc00
94
+ and #$10
95
+ beq .down
96
+ ; All keyboard rows are driven: a key pulls a column low. A column is a
97
+ ; key only when joystick 1 holds it high before and after this read,
98
+ ; so a move of joystick 1 between the reads is not a key.
99
+ lda #$00
100
+ sta $dc00
101
+ lda $dc01
102
+ eor #$ff
103
+ and .joy
104
+ sta .joy
105
+ lda #$ff
106
+ sta $dc00
107
+ lda $dc01
108
+ and .joy
109
+ bne .down
110
+ tya
111
+ beq .settle
112
+ cmp #2
113
+ beq loader_start_screen_continue
114
+ bne .poll
115
+ .down cpy #1
116
+ bne .poll
117
+ iny
118
+ bne .poll
119
+ ; Two frames after the release, a bounce of the key is not a press.
120
+ .settle ldx #2
121
+ .frame lda $d012
122
+ cmp #$80
123
+ bne .frame
124
+ .leave lda $d012
125
+ cmp #$80
126
+ beq .leave
127
+ dex
128
+ bne .frame
129
+ iny
130
+ bne .poll
131
+
132
+ loader_start_screen_continue
133
+ lda .port
134
+ sta $dc00
135
+ lda .ddra
136
+ sta $dc02
137
+ lda .ddrb
138
+ sta $dc03
139
+ .end