浏览代码

Initial handoff from the C64/C128 Dev Foundry

Approved spec: Stonehold 64. Starter (milestone M0) plus implementation docs.
main
当前提交
9ca7ea31b6
共有 24 个文件被更改,包括 2411 次插入 和 0 次删除
  1. +10
    -0
      .gitattributes
  2. +21
    -0
      .gitignore
  3. +96
    -0
      AGENTS.md
  4. +3
    -0
      CLAUDE.md
  5. +74
    -0
      README.md
  6. +171
    -0
      docs/manual-tests.md
  7. +70
    -0
      docs/milestones.md
  8. +212
    -0
      docs/spec.md
  9. +92
    -0
      docs/toolchain.md
  10. +25
    -0
      docs/verification-status.md
  11. +3
    -0
      fixtures/README.md
  12. +828
    -0
      project.json
  13. +52
    -0
      src/charset.c
  14. +21
    -0
      src/charset.h
  15. +5
    -0
      src/frame.h
  16. +18
    -0
      src/frame.s
  17. +118
    -0
      src/main.c
  18. +48
    -0
      src/smoke.c
  19. +17
    -0
      src/smoke.h
  20. +31
    -0
      tools/build.ps1
  21. +48
    -0
      tools/check-prereqs.ps1
  22. +248
    -0
      tools/lib.ps1
  23. +42
    -0
      tools/run.ps1
  24. +158
    -0
      tools/smoke.ps1

+ 10
- 0
.gitattributes 查看文件

@@ -0,0 +1,10 @@
* text=auto
*.ps1 text eol=crlf
*.prg binary
*.d64 binary
*.d71 binary
*.d81 binary
*.bin binary
*.png binary
# Fixtures are test inputs: keep their bytes (line endings, encoding) exactly as committed.
fixtures/** -text

+ 21
- 0
.gitignore 查看文件

@@ -0,0 +1,21 @@
# Build outputs (tools/build.ps1, tools/smoke.ps1, tools/to-commodore.ps1)
build/
*.o
*.prg
*.lbl
*.map
*.d64
*.d71
*.d81
!fixtures/**

# Editor and machine-local settings
.vscode/
.idea/
*.swp
*~
.DS_Store
Thumbs.db
vicerc
vice.ini
sdl-vicerc

+ 96
- 0
AGENTS.md 查看文件

@@ -0,0 +1,96 @@
# AGENTS.md - implementation instructions for Stonehold 64

You are the implementation agent for **Stonehold 64**, a game for `c64`.
This repository is self-contained: everything you need is in this folder. Do not look for
the tool that generated it or the conversation that produced the spec.

## 1. Read first, in this order

1. `docs/spec.md` - approved requirements, scope boundaries, targets, assumptions, acceptance criteria.
2. `docs/toolchain.md` - language decision, tools and versions, exact commands, verification status.
3. `docs/milestones.md` - ordered tasks; each links to requirements and has a completion check.
4. `docs/manual-tests.md` - what the user does by hand to confirm each milestone, per target.
5. `docs/verification-status.md` - what has been checked so far, and what is still pending.
6. `project.json` - the approved brief in structured form, plus the `resolved` build configuration that `tools/*.ps1` read.

The spec is the contract. If the code and the spec disagree, stop and ask the user; do not
quietly change either one.

## 2. Project constraints

- Language and toolchain: C (cc65) with ca65 assembly modules via Windows cross-development with cc65 (C, ca65 assembly or mixed) and VICE. Do not switch languages or tools without the user's approval (see section 6).
- Build location: Windows cross-development.
- Targets: `c64`. Every target listed in `docs/spec.md` must keep building and passing its checks after each task.
- Tools: cl65, x64sc, PowerShell 7, git. Scripts find them via environment variables (`CC65_HOME`, `VICE_HOME`), `PATH`, or the usual install folders. Never hard-code a machine-specific path into source or scripts.
- Paths may contain spaces (including this repository's own path). Quote paths in every command you write or document.
- Keep the smoke hooks working: `tools/smoke.ps1` depends on them (see `docs/toolchain.md`). If you change the first screen, update `starter.smokeChecks` in `project.json` and the matching `resolved.targets[].smoke.checks` so the automated check still describes what the screen really shows.
- Generated outputs go in `build/` (ignored by Git). Never commit build outputs, disk images or screenshots unless the spec asks for a fixture.
- Fixtures in `fixtures/` are stored byte-for-byte. Do not let an editor change their line endings or encoding.


## 3. Start: build and verify the starter (milestone M0)

Before writing any feature code:

```powershell
pwsh -File tools/check-prereqs.ps1
pwsh -File tools/build.ps1
pwsh -File tools/smoke.ps1
```

- `check-prereqs.ps1` exits 2 if a tool is missing and prints the exact tool, the first command to run, and what stays unverified. Report that to the user and stop. Don't work around a missing tool.
- `smoke.ps1` exits 0 when every automated check passes. Results: `build/smoke/results.json`; screenshots: `build/smoke/<target>/`.
- Then ask the user to perform M0 in `docs/manual-tests.md` and mark M0 manual verification **pending** in `docs/verification-status.md` until they confirm.

## 4. Milestone workflow

Work through `docs/milestones.md` in order, **one reviewable task at a time**:

1. Pick the next task. Re-read its requirements and acceptance criteria in `docs/spec.md`.
2. Make the smallest change that delivers the task's buildable outcome.
3. Run the checks: `pwsh -File tools/build.ps1` and `pwsh -File tools/smoke.ps1` at minimum, plus any check the task names. Fix failures before you report.
4. Update `docs/verification-status.md`: automated result for the task, manual verification **pending**.
5. Report to the user using the template below, then stop and wait if the next task depends on their manual verification.

### Report template (after every task)

```
Task: <id> <title> (requirements: <R ids>)
What changed: <files and behavior, in a few lines>
Checks run: <command> -> <result> (one line each, with exit codes)
Please verify manually:
1. <exact command to start, e.g. pwsh -File tools/run.ps1 -Target <id>>
2. <exact keys to press / actions>
Expected: <exactly what should appear or happen>
Manual verification: PENDING until you confirm.
Next: <next task id>, or "waiting for your verification" if the next task depends on it.
```

### Pausing rules

- When a milestone ends, stop until the user confirms that milestone's manual tests.
- Stop sooner if the next task builds on behavior that only the user can confirm (feel, timing, visuals, sound, real hardware).
- When the user confirms, change the item from pending to `confirmed by user (<date>)` in `docs/verification-status.md`. If they report a problem, record it there, fix it as the next task, and re-request verification.
- Never mark manual verification as confirmed yourself.

## 5. Verification rules

- Never claim a check passed unless you ran it in this session and saw it pass. Quote the command and the result.
- If a check cannot run (missing tool, no hardware), say so, and record it as `not run - <reason>`.
- Real-hardware results are only recorded when the user reports them.
- Keep `docs/manual-tests.md` accurate. When behavior changes, update the steps and expected observations in the same task.
- Acceptance criteria are verified against the target(s) they name. Native 40-column and 80-column C128 behavior are separate targets and need separate checks.

## 6. Changes to requirements

If the user asks for a change, or you find that a requirement cannot be met as written:

1. Describe the change and its impact: which requirements, milestones, tests and targets it touches.
2. Wait for approval.
3. In one task, update `docs/spec.md`, `docs/milestones.md`, `docs/manual-tests.md`, `docs/verification-status.md` and `project.json` together, and then the code. Requirements, implementation and verification must stay in sync.
4. A change of language or toolchain also updates `docs/toolchain.md` and the `resolved` section of `project.json`, and must be re-verified from M0.

## 7. Git

- Work on `main` unless the user asks otherwise. Commit after each verified task with a message naming the task id, e.g. `M1.2: draw signal heads`.
- Don't add remotes or push unless the user asks.

+ 3
- 0
CLAUDE.md 查看文件

@@ -0,0 +1,3 @@
# Claude Code

Read and follow [AGENTS.md](AGENTS.md). It is the complete set of instructions for this repository.

+ 74
- 0
README.md 查看文件

@@ -0,0 +1,74 @@
# Stonehold 64

An original colony-simulation game for the Commodore 64 in the fortress-building genre. The player does not control dwarves directly: they designate tiles to dig and a small crew of dwarves walks over and mines them on their own, revealing a randomly generated underground map. The view is a top-down tile map, drawn with an original custom character set, that scrolls over a world much larger than the screen.

- Targets: `c64` (details in [docs/spec.md](docs/spec.md))
- Language/toolchain: C (cc65) with ca65 assembly modules - Windows cross-development with cc65 (C, ca65 assembly or mixed) and VICE ([docs/toolchain.md](docs/toolchain.md))
- Status: starter only (milestone M0). Next milestone: M1 - World and view.

## First run

All commands run from this folder in PowerShell 7 (`pwsh`). Paths with spaces are fine.

### 1. Check prerequisites

```powershell
pwsh -File tools/check-prereqs.ps1
```

You need cl65, x64sc, PowerShell 7, git. For any missing tool the script prints the first command to run.
If a tool is installed somewhere unusual, set `VICE_HOME` or `CC65_HOME` to its folder.

### 2. Build

```powershell
pwsh -File tools/build.ps1
```

Outputs go to `build/`. Per-target artifacts and commands: [docs/toolchain.md](docs/toolchain.md).

### 3. Automated smoke test

```powershell
pwsh -File tools/smoke.ps1
```

Expected output: one `[PASS] <target>` line per target, with the checks listed under it, and exit code 0.
VICE runs minimized for a few seconds per target with its own temporary settings; your VICE
configuration is not touched. Screenshots are saved to `build/smoke/<target>/`.

### 4. Run it yourself

```powershell
pwsh -File tools/run.ps1 -Target c64
```

Expected screen: Row 0: 'STONEHOLD 64'. Row 1: 'CHARSET OK' (or 'MEMORY CLASH' if the program has grown over the charset at $3800). Rows 3-21: a sample patch of map drawn with the custom glyphs: brown soft rock with grey hard-rock flecks, a dark-grey floor cave in the middle with three orange dwarves, two yellow marked rock tiles and a white cursor bracket. Row 23: a glyph legend (ROCK, HARD, FLOOR, DWARF, DIG). Row 24: 'STONE 000 FRAME nnn ANY KEY EXITS' with the frame counter changing every frame. Any key restores the normal character set and returns to BASIC.


## Start the implementation agent

Open a **fresh** coding-agent session in this folder and send:

> Read AGENTS.md and follow it. Build and verify the starter (milestone M0) first, then implement the next milestone one task at a time, reporting after each task what changed, which checks ran, and exactly how I should verify it.

The agent's instructions are in [AGENTS.md](AGENTS.md). It reports after every task, with
exact steps for you to verify by hand, and treats your verification as pending until you confirm.

## Layout

| Path | Contents |
|---|---|
| `AGENTS.md` | Implementation instructions for the coding agent |
| `docs/spec.md` | Approved requirements and acceptance criteria |
| `docs/toolchain.md` | Language decision, tools, commands, verification status |
| `docs/milestones.md` | Ordered tasks with completion checks |
| `docs/manual-tests.md` | Manual test steps and expected results per milestone and target |
| `docs/verification-status.md` | What has been verified, and what is pending |
| `project.json` | Approved structured brief and resolved build configuration |
| `src/` | Program source |
| `fixtures/` | Sample inputs (stored byte-for-byte) |
| `tools/` | Build, run, smoke-test and prerequisite scripts |
| `build/` | Generated outputs (not committed) |

Generated by the C64/C128 Dev Foundry on 2026-11-26 from a spec approved by Daniel Covington on 2026-11-26.

+ 171
- 0
docs/manual-tests.md 查看文件

@@ -0,0 +1,171 @@
# Stonehold 64 - Manual tests

Exact setup, actions and expected observations for each milestone and target. The agent asks
you to run the relevant section after each task; record results in docs/verification-status.md.

General setup for every test: run commands from the repository folder in PowerShell 7. VICE
keyboard mapping: letters, digits and Return map directly; RUN/STOP is Esc, RESTORE is
Page Up and the Commodore key is Left Ctrl. Reset from the VICE menu (Machine > Reset). To use a
joystick, assign a PC joystick or keyset to the port in VICE (Preferences > Settings > Input
devices > Joystick) before the test.

## M0 - Starter builds and runs

### MT0-c64: starter on c64 (Commodore 64, vicii-40)

Setup: prerequisites installed (`pwsh -File tools/check-prereqs.ps1` reports no missing tools).

Steps:
1. Run `pwsh -File tools/smoke.ps1 -Target c64` and note the result.
2. Run `pwsh -File tools/run.ps1 -Target c64` (VICE starts and autostarts `build/stonehold-64.prg`).

Expected:
- tools/smoke.ps1 prints `[PASS] c64`; screenshot in build/smoke/c64/.
- Row 0: 'STONEHOLD 64'. Row 1: 'CHARSET OK' (or 'MEMORY CLASH' if the program has grown over the charset at $3800). Rows 3-21: a sample patch of map drawn with the custom glyphs: brown soft rock with grey hard-rock flecks, a dark-grey floor cave in the middle with three orange dwarves, two yellow marked rock tiles and a white cursor bracket. Row 23: a glyph legend (ROCK, HARD, FLOOR, DWARF, DIG). Row 24: 'STONE 000 FRAME nnn ANY KEY EXITS' with the frame counter changing every frame. Any key restores the normal character set and returns to BASIC.
- Autostarts to the Stonehold screen drawn with the custom character set: title on row 0, a map view on rows 1-23, status line (stone counter, seed, RUN/PAUSED) on row 24. Three dwarves move on their own to mine tiles the player marks with the mouse, joystick or keyboard.

## M1 - World and view

### MT1.1: Random map and seed (c64)

Setup: VICE x64sc, PAL.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Start the game and note the seed on row 24.
2. Reset VICE and start the game again; note the seed.

Expected:
- Row 24 shows 'SEED nnnnn' each time
- The two seeds differ and the visible maps differ
- Three dwarves stand on floor tiles inside a cave

Verifies: R1, R2

### MT1.2: Scroll to all four edges (c64)

Setup: VICE x64sc, PAL.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Hold the right cursor key until the view stops moving.
2. Repeat for down, left and up (W/A/S/D as well).

Expected:
- The view scrolls one tile at a time without garbage characters
- Scrolling stops at each map edge and the cursor cannot leave the map

Verifies: R3

## M2 - Designation by keyboard, joystick and mouse

### MT2.1: Mark by keyboard and joystick (c64)

Setup: VICE x64sc, PAL, a joystick or keyset mapped to port 2.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Move the cursor onto a rock tile and press D, then D again.
2. Move onto a floor tile and press D.
3. Use the joystick to move to another rock tile and press fire.

Expected:
- D marks the rock tile (yellow marked glyph) and the second D unmarks it
- D on floor changes nothing
- The joystick moves the cursor and fire marks the tile

Verifies: R4

### MT2.2: Mark by mouse (c64)

Setup: VICE x64sc, PAL, control port 1 set to Mouse (1351), mouse grab enabled.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Move the mouse slowly across the map.
2. Left-click a rock tile, then click it again.
3. Hold the pointer at the right edge of the view.

Expected:
- The pointer moves smoothly and the highlighted cursor tile is always under the pointer tip
- The first click marks the tile, the second unmarks it
- The map scrolls right while the pointer stays at the edge

Verifies: R5

## M3 - Dwarves at work

### MT3.1: Dwarves mine marked tiles (c64)

Setup: VICE x64sc, PAL.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Mark three adjacent rock tiles at the edge of the starting cave.
2. Watch the dwarves.
3. Mark one soft and one hard rock tile and compare mining time.
4. Mark a rock tile that is completely enclosed by rock.

Expected:
- Within about 5 seconds dwarves walk to the marked tiles, each to a different one
- Each mined tile turns into floor
- Hard rock takes clearly longer (about 3x)
- The enclosed tile stays marked and no dwarf gets stuck

Verifies: R6

### MT3.2: Stone counter and pause (c64)

Setup: VICE x64sc, PAL.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Note 'STONE 000' and mark two tiles; wait until both are mined.
2. Press SPACE while a dwarf is walking; mark another tile.
3. Press SPACE again.

Expected:
- The counter reads 'STONE 002' after two tiles
- Row 24 shows 'PAUSED', the dwarves stop, and marking still works
- Row 24 shows 'RUN' and the dwarves continue

Verifies: R7, R8

### MT3.3: Same speed on PAL and NTSC (c64)

Setup: VICE x64sc started once with -pal and once with -ntsc.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Mark a tile 10 tiles away from a dwarf through open floor and time how long it takes to arrive.

Expected:
- The two times differ by less than 10%

Verifies: R10

## M4 - Sound

### MT4.1: Sound effects (c64)

Setup: VICE x64sc, PAL, sound on.
Start: `pwsh -File tools/run.ps1 -Target c64`

Steps:
1. Mark and unmark a tile.
2. Watch and listen while a dwarf mines; pause during mining.

Expected:
- A click on each mark and unmark
- Repeated pick strikes while mining, which stop when the tile is done or the game is paused

Verifies: R9

## Real hardware

Optional for this release. Use these steps when hardware is available.

1. Build: `pwsh -File tools/build.ps1`.
2. Get the program onto a disk the machine can read, for example: copy the .prg (or .d64) to an SD2IEC/Pi1541/1541 Ultimate SD card; or write the .d64 to a real floppy with a ZoomFloppy/XUM1541 and OpenCBM (`d64copy build\<image>.d64 8`).
3. On the machine: `LOAD"*",8` then `RUN` (a C128 in native mode can also use `RUN"name"`). For C64-mode targets on a C128, enter C64 mode first (`GO 64`, then `Y`).
4. Repeat the manual tests for the current milestone and note any difference from VICE (timing, colours, display artefacts, disk speed) in docs/verification-status.md.

+ 70
- 0
docs/milestones.md 查看文件

@@ -0,0 +1,70 @@
# Stonehold 64 - Milestones

Work top to bottom, one task at a time (AGENTS.md section 4). Every task must leave all targets
building. Requirement IDs refer to docs/spec.md.

## M0 - Starter builds and runs

Goal: Prove the toolchain, emulator configuration and smoke test work before any feature work.

Requirements: R1

| Task | Description | Requirements | Buildable outcome | Completion check |
|---|---|---|---|---|
| M0.1 | Run tools/check-prereqs.ps1, then tools/smoke.ps1 for every target. | R1 | Starter artifact(s) built: build/stonehold-64.prg | tools/smoke.ps1 exits 0 (or every target without automation is verified by hand), and the user confirms the M0 manual test. |

Manual verification: see docs/manual-tests.md section M0.

## M1 - World and view

Goal: A random 128x128 map exists and the player can scroll around it with the keyboard.

Requirements: R1, R2, R3, R7

| Task | Description | Requirements | Buildable outcome | Completion check |
|---|---|---|---|---|
| M1.1 | Settle the memory map (A3): where the 16 KB map, the charset and the program live. Add a check that fails the build or shows an error if they overlap. | R1, R2 | Documented memory map in docs/ and a PRG that still passes the smoke test | build/stonehold-64.map shows no overlap; smoke test passes |
| M1.2 | Map generator in C: seeded PRNG, soft rock, hard-rock veins, caverns, starting cave near the centre. Show the seed on row 24. | R2 | PRG that generates a map and shows 'SEED nnnnn' | Manual test MT1.1 |
| M1.3 | Assembly view redraw (draw_view(x, y), C prototype) copying a 40x23 window of the map to screen and colour RAM via a tile-to-glyph/colour table. | R3 | PRG with a full-view redraw inside one frame | Border-colour timing bar ends before the bottom of the screen on PAL and NTSC |
| M1.4 | Keyboard cursor (cursor keys and W/A/S/D) with edge scrolling and map-border clamping. Status line: 'STONE 000 SEED nnnnn RUN'. | R3, R7 | PRG in which the cursor moves and the view scrolls | Manual test MT1.2 |

Manual verification: see docs/manual-tests.md section M1.

## M2 - Designation by keyboard, joystick and mouse

Goal: The player can mark and unmark rock tiles with any of the three input devices.

Requirements: R4, R5

| Task | Description | Requirements | Buildable outcome | Completion check |
|---|---|---|---|---|
| M2.1 | Mark/unmark with D on rock tiles only; marked-rock glyph. Joystick port 2 cursor movement with key repeat and fire to mark. | R4 | PRG in which D and fire toggle marks | Manual test MT2.1 |
| M2.2 | 1351 mouse via cc65 c64_1351_mou: sprite 0 pointer, dig cursor = tile under the pointer tip, left button marks/unmarks, pointer at a view edge scrolls. Verify A1/A2 and record the exact VICE options in docs/. | R5 | PRG controllable by mouse | Manual test MT2.2 |

Manual verification: see docs/manual-tests.md section M2.

## M3 - Dwarves at work

Goal: Three dwarves mine marked tiles on their own; the stone counter and pause work, at the same speed on PAL and NTSC.

Requirements: R6, R7, R8, R10

| Task | Description | Requirements | Buildable outcome | Completion check |
|---|---|---|---|---|
| M3.1 | Dwarf job system: idle dwarves claim the nearest reachable marked tile via a windowed breadth-first search (one search per frame at most), walk there, mine for a time that depends on the rock type, turn it into floor. | R6 | PRG in which dwarves mine marked tiles | Manual test MT3.1; timing bar for the search (A4) |
| M3.2 | Stone counter increments per mined tile; SPACE pauses and resumes; marking still works while paused. | R7, R8 | PRG with a working counter and pause | Manual test MT3.2 |
| M3.3 | Frame-based timers scaled for PAL and NTSC using get_tv(). | R10 | PRG with matching speed on both standards | Manual test MT3.3 |

Manual verification: see docs/manual-tests.md section M3.

## M4 - Sound

Goal: The game gives audible feedback for marking and mining.

Requirements: R9

| Task | Description | Requirements | Buildable outcome | Completion check |
|---|---|---|---|---|
| M4.1 | SID effects (assembly or C): mark/unmark click on one voice, pick strike on another, silenced while paused. | R9 | PRG with sound effects | Manual test MT4.1 |

Manual verification: see docs/manual-tests.md section M4.

+ 212
- 0
docs/spec.md 查看文件

@@ -0,0 +1,212 @@
# Stonehold 64 - Specification

Approved by Daniel Covington on 2026-11-26. Changes to this file follow AGENTS.md section 6.

## Summary

An original colony-simulation game for the Commodore 64 in the fortress-building genre. The player does not control dwarves directly: they designate tiles to dig and a small crew of dwarves walks over and mines them on their own, revealing a randomly generated underground map. The view is a top-down tile map, drawn with an original custom character set, that scrolls over a world much larger than the screen.

Original idea, as given:

> Dwarf Fortress clone

Smallest useful version: One randomly generated 128x128 underground level, three dwarves, a cursor (mouse, joystick or keyboard) to mark rock for digging; dwarves path to marked tiles and mine them, each mined tile yields one stone shown in a counter; the game runs in real time and can be paused.

## First release

One randomly generated 128x128 underground level (soft rock, hard rock, a few caverns and a starting cave), shown through a scrolling 40x23 map view drawn with an original custom character set. The player marks rock tiles for digging with a Commodore 1351 mouse (the dig cursor sits under the pointer), a joystick in port 2 or the keyboard. Three autonomous dwarves pick marked tiles within about 32 tiles, walk there, and mine them; each mined tile becomes floor and adds one stone to a counter. Real-time with pause, SID sound effects, same game speed on PAL and NTSC.

### In scope

- Randomly generated 128x128 tile map with a visible seed, new layout each game
- Scrolling 40x23 map view
- Original custom character set for terrain, dwarves and cursor
- Dig designation with a 1351 mouse, a joystick or the keyboard
- Three autonomous dwarves with local pathfinding to designated tiles
- Mining turns rock into floor and adds stone to a counter; hard rock takes longer
- Real-time simulation with pause
- SID sound effects

### Out of scope

- Food, drink, needs and moods
- Building walls, doors or furniture
- Stockpiles and hauling
- Combat and enemies
- More than one z-level
- Saving and loading
- Music

## Targets

| Target | Machine / mode | Display | Video | Artifact | Expected behavior |
|---|---|---|---|---|---|
| `c64` | Commodore 64 | VIC-II 40x25 text/graphics screen (C64, or C128 40-column) | pal-ntsc | `build/stonehold-64.prg` | Autostarts to the Stonehold screen drawn with the custom character set: title on row 0, a map view on rows 1-23, status line (stone counter, seed, RUN/PAUSED) on row 24. Three dwarves move on their own to mine tiles the player marks with the mouse, joystick or keyboard. |

### Dual-target and mode notes

Single target.

### Display notes

- `c64`: VIC-II 40x25 screen. Screen RAM at $0400 by default.

### Testing environment

- Reference emulator: VICE (exact options in docs/toolchain.md).
- Real hardware: Not requested for this release. VICE is the reference environment; real-hardware steps in docs/manual-tests.md are optional.

## Requirements and acceptance criteria

Each criterion is observable. Criteria IDs (for example R1.2) are referenced by milestones and manual tests.

### R1 - Original character set and screen layout (must)

The game switches the VIC-II to an original custom character set: letters, digits and punctuation keep their usual shapes (copied from ROM at start), and new glyphs are defined for soft rock, hard rock, floor, marked rock, dwarf and cursor. Screen layout: row 0 title, rows 1-23 map view, row 24 status line.

Acceptance criteria:
- [R1.1] After autostart in VICE x64sc (PAL) the screen appears within 5 seconds and row 0 reads 'STONEHOLD 64'
- [R1.2] Rock, floor, dwarves and marked rock are drawn with the game's own glyphs, visibly different from stock PETSCII graphics
- [R1.3] Text on rows 0 and 24 is readable in the normal uppercase letter shapes

Capabilities: text-ui, custom-charset

### R2 - Random map generation (must)

At the start of each game a 128x128 map is generated from a 16-bit seed: mostly soft rock, veins of hard rock, several random caverns, and an open starting cave near the centre where the three dwarves start. The same seed always gives the same map. The seed is shown on the status line.

Acceptance criteria:
- [R2.1] Row 24 shows 'SEED nnnnn'
- [R2.2] Two new games (restart or reload) show different seeds and different map layouts
- [R2.3] A fixed seed set in the debug build gives an identical map in two runs (compare screenshots)
- [R2.4] The dwarves start on floor tiles inside an open cave

Capabilities: text-ui

### R3 - Scrolling map view (must)

The 40x23 map view shows part of the 128x128 map. Moving the cursor within 2 tiles of a view edge scrolls the view one tile in that direction, stopping at the map borders. The view is redrawn by an assembly routine callable from C.

Acceptance criteria:
- [R3.1] Holding a direction scrolls the map steadily until the map edge, where scrolling stops
- [R3.2] All four map edges can be reached
- [R3.3] A full-view redraw completes within one frame (border-colour timing bar check)

Capabilities: text-ui, custom-charset

### R4 - Dig designation by keyboard and joystick (must)

Cursor keys or W/A/S/D move the dig cursor one tile; D marks or unmarks the rock tile under the cursor. A joystick in port 2 moves the cursor (with key repeat), and fire marks or unmarks. Floor tiles cannot be marked.

Acceptance criteria:
- [R4.1] Pressing D on a rock tile changes it to the marked-rock glyph; pressing D again restores it
- [R4.2] Pressing D on a floor tile changes nothing
- [R4.3] The joystick in port 2 moves the cursor and fire marks/unmarks exactly like D

Capabilities: keyboard-input, joystick-input

### R5 - Commodore 1351 mouse (must)

A 1351 mouse in control port 1 (proportional mode) moves a sprite pointer. The dig cursor is always the map tile under the pointer. The left button marks or unmarks that tile. Holding the pointer at a view edge scrolls the map. The mouse can be used at the same time as the joystick and keyboard.

Acceptance criteria:
- [R5.1] With VICE 1351 mouse emulation on port 1, moving the mouse moves the pointer smoothly by the pixel
- [R5.2] The highlighted dig cursor tile is always the tile under the pointer tip
- [R5.3] Left click on a rock tile marks it; left click again unmarks it
- [R5.4] Holding the pointer at the right edge scrolls the map right

Capabilities: mouse-1351, sprites

### R6 - Autonomous dwarves (must)

Three dwarves act on their own. An idle dwarf searches (breadth-first, within about 32 tiles) for the nearest marked tile that has a walkable neighbour, walks there at 2-4 steps per second, and mines it: soft rock takes about 1 second, hard rock about 3 seconds. Two dwarves never claim the same tile. A marked tile no dwarf can reach stays marked.

Acceptance criteria:
- [R6.1] Marking a rock tile next to the starting cave makes a dwarf walk to it and mine it within about 5 seconds
- [R6.2] The mined tile changes to floor
- [R6.3] With three adjacent marked tiles, the three dwarves mine different tiles
- [R6.4] Hard rock visibly takes longer to mine than soft rock
- [R6.5] A marked tile with no path to it stays marked and no dwarf freezes

Capabilities: text-ui

### R7 - Stone counter (must)

Each mined tile adds one stone. The total is shown on row 24 as 'STONE nnn'.

Acceptance criteria:
- [R7.1] The game starts with 'STONE 000' on row 24
- [R7.2] Each mined tile increments the counter by exactly 1

Capabilities: text-ui

### R8 - Pause (must)

SPACE pauses and resumes the simulation. While paused, dwarves and mining stop, the status line shows 'PAUSED', and the player can still scroll and mark tiles.

Acceptance criteria:
- [R8.1] SPACE shows 'PAUSED' on row 24 and all dwarves stop
- [R8.2] Tiles can be marked while paused
- [R8.3] SPACE again shows 'RUN' and the dwarves continue

Capabilities: keyboard-input

### R9 - Sound effects (should)

SID effects: a short click when a tile is marked or unmarked, and a pick strike on each mining blow. No music.

Acceptance criteria:
- [R9.1] A click is heard on each mark or unmark
- [R9.2] Pick strikes are heard while a dwarf mines, and stop when mining ends or the game is paused

Capabilities: sid-sound

### R10 - PAL and NTSC (must)

The game detects PAL or NTSC at start and scales its timers so that dwarf speed and mining time are the same in seconds on both.

Acceptance criteria:
- [R10.1] In VICE with -pal and with -ntsc, a dwarf takes the same time (within 10%) to walk 10 tiles

Capabilities: text-ui

## Design decisions

"Practical default" means the Foundry proposed it and the user accepted it without a specific preference. It can be changed later through AGENTS.md section 6.

| Topic | Decision | Source |
|---|---|---|
| Controls | Commodore 1351 mouse in control port 1 (proportional mode): a sprite pointer, the dig cursor is the tile under the pointer, the left button marks/unmarks, the pointer at a view edge scrolls the map. Joystick in port 2: move the cursor, fire marks/unmarks. Keyboard: cursor keys or W/A/S/D move, D marks/unmarks, SPACE pauses/resumes. All three can be used together. | decided by user |
| Visuals | Character mode with an original custom character set at $3800 (VIC bank 0, screen at $0400): codes 0-63 copied from the uppercase ROM set so text stays readable, codes 64+ hold the game's own glyphs (soft rock, hard rock, floor, marked rock, dwarf, cursor). Colours: rock brown, hard rock grey, floor dark grey, marked rock yellow, dwarves orange, cursor white, on a black background. The mouse pointer is hardware sprite 0. | decided by user |
| Sound | SID effects only: a mark/unmark click and a pick strike while mining. No music. | decided by user |
| Persistence (save/load) | None. Nothing is saved in the first release. | not applicable |
| File formats | None. A single PRG. | not applicable |
| Peripherals | Commodore 1351 mouse in control port 1; joystick in control port 2 (optional; keyboard works alone). No disk access after loading. | decided by user |
| Timing and memory budgets | Map 128x128 at one byte per tile (16 KB: tile type plus marked/claimed flags in the same byte). Pathfinding is a breadth-first search limited to a 65x65 window around the dwarf (about 4.2 KB scratch, shared by all dwarves, one search per frame at most). Dwarves move 2-4 steps per second. View redraw (40x23 tiles) in assembly within one frame. Input polled every frame. Program plus data must fit below $D000 with the charset at $3800. | decided by user |
| Map generation | 128x128 tiles from a visible 16-bit seed: mostly soft rock, veins of hard rock, several random caverns, a starting cave near the centre. Hard rock takes about three times as long to mine. | decided by user |
| Language split | C for game logic, map generation and pathfinding; ca65 assembly functions with C prototypes for the speed-critical parts (view redraw, frame wait, later anything profiling shows is too slow). | decided by user |

## Required capabilities

- `text-ui`: Text screens, menus and status lines (PRINT / conio / KERNAL CHROUT).
- `keyboard-input`: Reading keys from the keyboard.
- `joystick-input`: Reading a joystick in control port 1 or 2.
- `custom-charset`: Redefined character sets.
- `sprites`: VIC-II hardware sprites.
- `sid-sound`: Sound effects or music through the SID.
- `mouse-1351`: Commodore 1351 mouse in proportional mode in control port 1 (cc65 drivers c64_1351_mou / c128_1351_mou, or POT reads in assembly). VICE emulates it on control port 1.

## Assumptions

| ID | Assumption | Status |
|---|---|---|
| A1 | cc65's statically linked 1351 driver (c64_1351_mou, mouse_install with mouse_def_callbacks) drives sprite 0 as the pointer and works alongside joystick reads on port 2. The Foundry verified (test brief mouse-1351-c) that the driver links and installs in VICE 3.10 with a 1351 on control port 1; pointer movement together with joystick and keyboard input is still to be checked by hand. | unverified |
| A2 | VICE emulates the 1351 on control port 1 with -controlport1device 3 (added to tools/run.ps1 and tools/smoke.ps1 automatically by the mouse-1351 capability). The host mouse must be grabbed with Alt+M (or -mouse) for the pointer to move. | confirmed |
| A3 | Memory map: screen $0400, custom charset $3800-$3FFF in VIC bank 0. Once the program (code, data, BSS including the 16 KB map) grows past $3800, the map or the charset must move (for example map at a fixed address above the program, or a custom ld65 config that reserves $3800-$3FFF and updating tools/build.ps1). The starter checks at run time that its BSS ends below $3800 and shows 'MEMORY CLASH' if not. | unverified |
| A4 | A breadth-first search over a 65x65 window, at most one search per frame, is fast enough that dwarves start walking within a second of a tile being marked. | unverified |
| A5 | Video standard is detected at start with get_tv(); timers are counted in frames and scaled for 50 Hz (PAL) and 60 Hz (NTSC). | default |
| A6 | VICE x64sc with default C64 model settings is a faithful reference for timing. | default |

## Unresolved decisions

- None. Every decision in this spec is settled.

+ 92
- 0
docs/toolchain.md 查看文件

@@ -0,0 +1,92 @@
# Stonehold 64 - Toolchain

## Decision

- Language: **C (cc65) with ca65 assembly modules**
- Recipe: **Windows cross-development with cc65 (C, ca65 assembly or mixed) and VICE** (`cc65`)
- Build location: Windows cross-development
- Foundry recommendation: `cc65` / `mixed-c-asm` (C (cc65) with ca65 assembly modules)

No user override. The recommended language is used.

### Why this language

- BASIC V2 is far too slow: generating a 16 KB map, running pathfinding for three dwarves and redrawing a scrolling 920-tile view every frame is beyond interpreted BASIC.
- C (cc65) keeps the game rules, map generator and pathfinding readable and easy to change, and cc65 ships a 1351 mouse driver.
- Small ca65 assembly functions with C prototypes handle the speed-critical parts: the map view redraw and the frame wait. More can be moved to assembly later if profiling shows a hot spot (for example the pathfinding inner loop).
- The user asked for exactly this split: C with assembly functions callable from C. It matches the Foundry recommendation, so no override is needed.
- Everything builds on Windows with one cc65 install and runs in VICE x64sc.

### Alternatives considered

| Alternative | Why not chosen |
|---|---|
| BASIC V2 | Too slow for map generation, pathfinding and per-frame view redraws. |
| C only (cc65) | A 920-tile view redraw in compiled C takes several frames, so scrolling would stutter. Assembly for that loop is needed. |
| 6502 assembly only (ca65) | Fastest, but map generation, pathfinding and job logic would take much longer to write and change. The speed is only needed in a few routines. |

## Tools

| Tool | Purpose | Verified version | Install source | First command if missing | Override variable |
|---|---|---|---|---|---|
| `cl65` | cc65 compile/assemble/link driver (C and ca65 assembly) | cl65 V2.19 - Git cc3c40c | https://cc65.github.io/getting-started.html | Download https://sourceforge.net/projects/cc65/files/cc65-snapshot-win64.zip, unzip it (for example to C:\cc65), then run: [Environment]::SetEnvironmentVariable('CC65_HOME','C:\cc65','User') and open a new terminal. | `CC65_HOME` |
| `x64sc` | VICE cycle-exact Commodore 64 emulator | VICE 3.10 | https://vice-emu.sourceforge.io/index.html#download | winget install --id VICE-Team.VICE.GTK3 -e (or unzip GTK3VICE-3.10-win64.zip and set VICE_HOME to the unzipped folder) | `VICE_HOME` |

Check them with `pwsh -File tools/check-prereqs.ps1`. Lookup order for each tool: its environment variable (folder or folder\bin), then `PATH`, then common install folders.

## Commands

| Purpose | Command |
|---|---|
| Check prerequisites | `pwsh -File tools/check-prereqs.ps1` |
| Build all targets | `pwsh -File tools/build.ps1` |
| Build one target | `pwsh -File tools/build.ps1 -Target <id>` |
| Run in VICE | `pwsh -File tools/run.ps1 -Target <id>` (add `-Video ntsc` to try NTSC) |
| Automated smoke test | `pwsh -File tools/smoke.ps1` (exit 0 pass, 1 fail, 2 missing tool, 3 manual only) |

## Target settings and verification status

Starter configurations marked verified were exercised by the Foundry's automated checks on 2026-11-26 with cl65 V2.19 - Git cc3c40c (Windows x64 snapshot), VICE 3.10 GTK3 win64 (x64sc, x128, c1541, petcat), PowerShell 7.6.7 on Windows 11 Pro 10.0.26200.

### Target `c64`

- Status: **verified** starter configuration (cc65, c64/vicii-40, mixed-c-asm)
- Build (what tools/build.ps1 runs): `cl65 -t c64 -g -O -D FOUNDRY_TARGET_C64 -I src -o build/stonehold-64.prg -Ln build/stonehold-64.lbl -m build/stonehold-64.map src/*.c src/*.s`
- Emulator: `x64sc -pal -controlport1device 3 -autostart build/stonehold-64.prg`
- Emulator note - mouse-1351: Control port 1 = Mouse (1351). Grab the host mouse in VICE with Alt+M (default GTK3 hotkeys; Alt+Q with the WinVICE legacy hotkey file) or start VICE with -mouse; without a grab the C64 pointer does not move. Press Alt+M again to release it.
- Smoke test: `pwsh -File tools/smoke.ps1 -Target c64`. It runs VICE headless for 30000000 cycles, saves memory when the program reaches `_smoke_ready`, and checks:
- Title on row 0
- Custom charset installed without a memory clash
- Stone counter on the status line
- C64 KERNAL reset vector at $FFFC (machine is in C64 mode)

### How the smoke test works

`tools/smoke.ps1` starts VICE with `-config <temp file> -default -warp -minimized -sounddev dummy`, so your own VICE settings are never read or changed. It gives the monitor a command file (`-moncommands`) that sets non-stopping tracepoints on the program's ready point. When the program reaches it, VICE saves memory with `bsave` into `build/smoke/<target>/`. VICE exits after `-limitcycles` cycles and writes `-exitscreenshot`; that is the normal way the run ends, so VICE's own exit code is ignored. The script then compares the saved memory with the expected screen text (as VIC-II/VDC screen codes) and mode bytes.

Smoke hooks in the source:

- cc65 C programs: `smoke_capture()` and `smoke_ready()` in `src/smoke.c`. 80-column builds copy the first VDC rows into `smoke_probe[]`, because VDC memory is not visible to the CPU.
- ca65 programs: the `smoke_ready` label.
- BASIC programs: `POKE 679,1` (BASIC V2) or `POKE 3071,1` (BASIC 7.0) after the first screen is drawn.

## Assumptions still to verify

- [ ] A1: the pointer follows the grabbed host mouse and the left button is detected while the joystick in port 2 and the keyboard still work (before M2 is complete).
- [ ] A3: memory map. Check the map file (build/stonehold-64.map) at every milestone; settle where the 16 KB map lives in M1.
- [ ] A4: measure worst-case pathfinding time with a border-colour timing bar in M3.
- [ ] Frame budget: the view redraw finishes within one frame on PAL and NTSC (timing bar) in M1.



## Sources

- https://cc65.github.io/doc/cl65.html
- https://cc65.github.io/doc/c64.html#toc4.2
- https://cc65.github.io/doc/c128.html
- https://cc65.github.io/doc/ca65.html
- https://vice-emu.sourceforge.io/vice_2.html#SEC50
- https://vice-emu.sourceforge.io/vice_7.html#SEC194
- https://vice-emu.sourceforge.io/vice_12.html
- https://cc65.github.io/getting-started.html
- https://vice-emu.sourceforge.io/index.html#download

+ 25
- 0
docs/verification-status.md 查看文件

@@ -0,0 +1,25 @@
# Stonehold 64 - Verification status

The implementation agent updates this file after every task (AGENTS.md section 4).
Manual verification stays **pending** until the user confirms it. Only the user can confirm.

Values: automated = `passed (<date>, <command>)`, `failed (...)`, `not run - <reason>`;
manual = `pending`, `confirmed by user (<date>)`, `problem reported (<date>): <note>`.

| Item | Automated check | Manual verification by user |
|---|---|---|
| M0.1 Run tools/check-prereqs.ps1, then tools/smoke.ps1 for every target. | not run | pending |
| M1.1 Settle the memory map (A3): where the 16 KB map, the charset and the program live. Add a check that fails the build or shows an error if they overlap. | not run | pending |
| M1.2 Map generator in C: seeded PRNG, soft rock, hard-rock veins, caverns, starting cave near the centre. Show the seed on row 24. | not run | pending |
| M1.3 Assembly view redraw (draw_view(x, y), C prototype) copying a 40x23 window of the map to screen and colour RAM via a tile-to-glyph/colour table. | not run | pending |
| M1.4 Keyboard cursor (cursor keys and W/A/S/D) with edge scrolling and map-border clamping. Status line: 'STONE 000 SEED nnnnn RUN'. | not run | pending |
| M2.1 Mark/unmark with D on rock tiles only; marked-rock glyph. Joystick port 2 cursor movement with key repeat and fire to mark. | not run | pending |
| M2.2 1351 mouse via cc65 c64_1351_mou: sprite 0 pointer, dig cursor = tile under the pointer tip, left button marks/unmarks, pointer at a view edge scrolls. Verify A1/A2 and record the exact VICE options in docs/. | not run | pending |
| M3.1 Dwarf job system: idle dwarves claim the nearest reachable marked tile via a windowed breadth-first search (one search per frame at most), walk there, mine for a time that depends on the rock type, turn it into floor. | not run | pending |
| M3.2 Stone counter increments per mined tile; SPACE pauses and resumes; marking still works while paused. | not run | pending |
| M3.3 Frame-based timers scaled for PAL and NTSC using get_tv(). | not run | pending |
| M4.1 SID effects (assembly or C): mark/unmark click on one voice, pick strike on another, silenced while paused. | not run | pending |

## Notes

- Generated 2026-11-26. Starter verification at generation time is reported by the Foundry; re-run `pwsh -File tools/smoke.ps1` on your machine and record the result in row M0.1.

+ 3
- 0
fixtures/README.md 查看文件

@@ -0,0 +1,3 @@
# Fixtures

Sample inputs for tests go here. Files in this folder are stored byte-for-byte (see .gitattributes).

+ 828
- 0
project.json 查看文件

@@ -0,0 +1,828 @@
{
"schemaVersion": "1.0",
"status": "approved",
"interview": {
"startedOn": "2026-11-26",
"stage": "review",
"openQuestions": [],
"notes": [
"User idea named an existing commercial game; the Foundry is building an original game in the same genre (no names, characters, art or look from that game). Working title Stonehold 64 accepted by the user.",
"Round 1: C64 only, PAL+NTSC, VICE only. Smallest version accepted; user added: original custom character set, not stock PETSCII.",
"Round 2: user accepted the out-of-scope list (except random map generation, now in). Added: 1351 mouse required, mouse may be used alongside joystick/keyboard. Map 128x128, randomly generated. Sound effects yes.",
"Round 3: dig cursor sits under the mouse pointer. Memory/speed budget, map generation plan, name and destination accepted. Language: C with assembly functions callable from C for speed.",
"Foundry maintenance done at the user's request: mouse-1351 capability added to the catalog (cc65 languages; VICE -controlport1device 3), with test briefs mouse-1351-c and conflict-basic-mouse."
]
},
"project": {
"name": "Stonehold 64",
"slug": "stonehold-64",
"idea": "Dwarf Fortress clone",
"summary": "An original colony-simulation game for the Commodore 64 in the fortress-building genre. The player does not control dwarves directly: they designate tiles to dig and a small crew of dwarves walks over and mines them on their own, revealing a randomly generated underground map. The view is a top-down tile map, drawn with an original custom character set, that scrolls over a world much larger than the screen.",
"kind": "game",
"smallestUsefulVersion": "One randomly generated 128x128 underground level, three dwarves, a cursor (mouse, joystick or keyboard) to mark rock for digging; dwarves path to marked tiles and mine them, each mined tile yields one stone shown in a counter; the game runs in real time and can be paused."
},
"targets": [
{
"id": "c64",
"name": "Commodore 64 (PAL primary, NTSC supported)",
"platform": "c64",
"display": "vicii-40",
"video": "pal-ntsc",
"expectedBehavior": "Autostarts to the Stonehold screen drawn with the custom character set: title on row 0, a map view on rows 1-23, status line (stone counter, seed, RUN/PAUSED) on row 24. Three dwarves move on their own to mine tiles the player marks with the mouse, joystick or keyboard."
}
],
"dualTarget": null,
"buildLocation": "windows-cross",
"onCommodore": null,
"testing": {
"emulator": "vice",
"realHardware": {
"requested": false,
"reason": "VICE only (user choice). Real-hardware steps stay optional in the manual tests."
}
},
"scope": {
"firstRelease": "One randomly generated 128x128 underground level (soft rock, hard rock, a few caverns and a starting cave), shown through a scrolling 40x23 map view drawn with an original custom character set. The player marks rock tiles for digging with a Commodore 1351 mouse (the dig cursor sits under the pointer), a joystick in port 2 or the keyboard. Three autonomous dwarves pick marked tiles within about 32 tiles, walk there, and mine them; each mined tile becomes floor and adds one stone to a counter. Real-time with pause, SID sound effects, same game speed on PAL and NTSC.",
"inScope": [
"Randomly generated 128x128 tile map with a visible seed, new layout each game",
"Scrolling 40x23 map view",
"Original custom character set for terrain, dwarves and cursor",
"Dig designation with a 1351 mouse, a joystick or the keyboard",
"Three autonomous dwarves with local pathfinding to designated tiles",
"Mining turns rock into floor and adds stone to a counter; hard rock takes longer",
"Real-time simulation with pause",
"SID sound effects"
],
"outOfScope": [
"Food, drink, needs and moods",
"Building walls, doors or furniture",
"Stockpiles and hauling",
"Combat and enemies",
"More than one z-level",
"Saving and loading",
"Music"
]
},
"requirements": [
{
"id": "R1",
"title": "Original character set and screen layout",
"priority": "must",
"text": "The game switches the VIC-II to an original custom character set: letters, digits and punctuation keep their usual shapes (copied from ROM at start), and new glyphs are defined for soft rock, hard rock, floor, marked rock, dwarf and cursor. Screen layout: row 0 title, rows 1-23 map view, row 24 status line.",
"acceptance": [
"After autostart in VICE x64sc (PAL) the screen appears within 5 seconds and row 0 reads 'STONEHOLD 64'",
"Rock, floor, dwarves and marked rock are drawn with the game's own glyphs, visibly different from stock PETSCII graphics",
"Text on rows 0 and 24 is readable in the normal uppercase letter shapes"
],
"capabilities": [
"text-ui",
"custom-charset"
]
},
{
"id": "R2",
"title": "Random map generation",
"priority": "must",
"text": "At the start of each game a 128x128 map is generated from a 16-bit seed: mostly soft rock, veins of hard rock, several random caverns, and an open starting cave near the centre where the three dwarves start. The same seed always gives the same map. The seed is shown on the status line.",
"acceptance": [
"Row 24 shows 'SEED nnnnn'",
"Two new games (restart or reload) show different seeds and different map layouts",
"A fixed seed set in the debug build gives an identical map in two runs (compare screenshots)",
"The dwarves start on floor tiles inside an open cave"
],
"capabilities": [
"text-ui"
]
},
{
"id": "R3",
"title": "Scrolling map view",
"priority": "must",
"text": "The 40x23 map view shows part of the 128x128 map. Moving the cursor within 2 tiles of a view edge scrolls the view one tile in that direction, stopping at the map borders. The view is redrawn by an assembly routine callable from C.",
"acceptance": [
"Holding a direction scrolls the map steadily until the map edge, where scrolling stops",
"All four map edges can be reached",
"A full-view redraw completes within one frame (border-colour timing bar check)"
],
"capabilities": [
"text-ui",
"custom-charset"
]
},
{
"id": "R4",
"title": "Dig designation by keyboard and joystick",
"priority": "must",
"text": "Cursor keys or W/A/S/D move the dig cursor one tile; D marks or unmarks the rock tile under the cursor. A joystick in port 2 moves the cursor (with key repeat), and fire marks or unmarks. Floor tiles cannot be marked.",
"acceptance": [
"Pressing D on a rock tile changes it to the marked-rock glyph; pressing D again restores it",
"Pressing D on a floor tile changes nothing",
"The joystick in port 2 moves the cursor and fire marks/unmarks exactly like D"
],
"capabilities": [
"keyboard-input",
"joystick-input"
]
},
{
"id": "R5",
"title": "Commodore 1351 mouse",
"priority": "must",
"text": "A 1351 mouse in control port 1 (proportional mode) moves a sprite pointer. The dig cursor is always the map tile under the pointer. The left button marks or unmarks that tile. Holding the pointer at a view edge scrolls the map. The mouse can be used at the same time as the joystick and keyboard.",
"acceptance": [
"With VICE 1351 mouse emulation on port 1, moving the mouse moves the pointer smoothly by the pixel",
"The highlighted dig cursor tile is always the tile under the pointer tip",
"Left click on a rock tile marks it; left click again unmarks it",
"Holding the pointer at the right edge scrolls the map right"
],
"capabilities": [
"mouse-1351",
"sprites"
]
},
{
"id": "R6",
"title": "Autonomous dwarves",
"priority": "must",
"text": "Three dwarves act on their own. An idle dwarf searches (breadth-first, within about 32 tiles) for the nearest marked tile that has a walkable neighbour, walks there at 2-4 steps per second, and mines it: soft rock takes about 1 second, hard rock about 3 seconds. Two dwarves never claim the same tile. A marked tile no dwarf can reach stays marked.",
"acceptance": [
"Marking a rock tile next to the starting cave makes a dwarf walk to it and mine it within about 5 seconds",
"The mined tile changes to floor",
"With three adjacent marked tiles, the three dwarves mine different tiles",
"Hard rock visibly takes longer to mine than soft rock",
"A marked tile with no path to it stays marked and no dwarf freezes"
],
"capabilities": [
"text-ui"
]
},
{
"id": "R7",
"title": "Stone counter",
"priority": "must",
"text": "Each mined tile adds one stone. The total is shown on row 24 as 'STONE nnn'.",
"acceptance": [
"The game starts with 'STONE 000' on row 24",
"Each mined tile increments the counter by exactly 1"
],
"capabilities": [
"text-ui"
]
},
{
"id": "R8",
"title": "Pause",
"priority": "must",
"text": "SPACE pauses and resumes the simulation. While paused, dwarves and mining stop, the status line shows 'PAUSED', and the player can still scroll and mark tiles.",
"acceptance": [
"SPACE shows 'PAUSED' on row 24 and all dwarves stop",
"Tiles can be marked while paused",
"SPACE again shows 'RUN' and the dwarves continue"
],
"capabilities": [
"keyboard-input"
]
},
{
"id": "R9",
"title": "Sound effects",
"priority": "should",
"text": "SID effects: a short click when a tile is marked or unmarked, and a pick strike on each mining blow. No music.",
"acceptance": [
"A click is heard on each mark or unmark",
"Pick strikes are heard while a dwarf mines, and stop when mining ends or the game is paused"
],
"capabilities": [
"sid-sound"
]
},
{
"id": "R10",
"title": "PAL and NTSC",
"priority": "must",
"text": "The game detects PAL or NTSC at start and scales its timers so that dwarf speed and mining time are the same in seconds on both.",
"acceptance": [
"In VICE with -pal and with -ntsc, a dwarf takes the same time (within 10%) to walk 10 tiles"
],
"capabilities": [
"text-ui"
]
}
],
"design": {
"controls": {
"value": "Commodore 1351 mouse in control port 1 (proportional mode): a sprite pointer, the dig cursor is the tile under the pointer, the left button marks/unmarks, the pointer at a view edge scrolls the map. Joystick in port 2: move the cursor, fire marks/unmarks. Keyboard: cursor keys or W/A/S/D move, D marks/unmarks, SPACE pauses/resumes. All three can be used together.",
"source": "user"
},
"visuals": {
"value": "Character mode with an original custom character set at $3800 (VIC bank 0, screen at $0400): codes 0-63 copied from the uppercase ROM set so text stays readable, codes 64+ hold the game's own glyphs (soft rock, hard rock, floor, marked rock, dwarf, cursor). Colours: rock brown, hard rock grey, floor dark grey, marked rock yellow, dwarves orange, cursor white, on a black background. The mouse pointer is hardware sprite 0.",
"source": "user"
},
"sound": {
"value": "SID effects only: a mark/unmark click and a pick strike while mining. No music.",
"source": "user"
},
"persistence": {
"value": "None. Nothing is saved in the first release.",
"source": "n/a"
},
"fileFormats": {
"value": "None. A single PRG.",
"source": "n/a"
},
"peripherals": {
"value": "Commodore 1351 mouse in control port 1; joystick in control port 2 (optional; keyboard works alone). No disk access after loading.",
"source": "user"
},
"budgets": {
"value": "Map 128x128 at one byte per tile (16 KB: tile type plus marked/claimed flags in the same byte). Pathfinding is a breadth-first search limited to a 65x65 window around the dwarf (about 4.2 KB scratch, shared by all dwarves, one search per frame at most). Dwarves move 2-4 steps per second. View redraw (40x23 tiles) in assembly within one frame. Input polled every frame. Program plus data must fit below $D000 with the charset at $3800.",
"source": "user"
},
"other": [
{
"topic": "Map generation",
"value": "128x128 tiles from a visible 16-bit seed: mostly soft rock, veins of hard rock, several random caverns, a starting cave near the centre. Hard rock takes about three times as long to mine.",
"source": "user"
},
{
"topic": "Language split",
"value": "C for game logic, map generation and pathfinding; ca65 assembly functions with C prototypes for the speed-critical parts (view redraw, frame wait, later anything profiling shows is too slow).",
"source": "user"
}
]
},
"capabilities": [
"text-ui",
"keyboard-input",
"joystick-input",
"custom-charset",
"sprites",
"sid-sound",
"mouse-1351"
],
"assumptions": [
{
"id": "A1",
"text": "cc65's statically linked 1351 driver (c64_1351_mou, mouse_install with mouse_def_callbacks) drives sprite 0 as the pointer and works alongside joystick reads on port 2. The Foundry verified (test brief mouse-1351-c) that the driver links and installs in VICE 3.10 with a 1351 on control port 1; pointer movement together with joystick and keyboard input is still to be checked by hand.",
"status": "unverified"
},
{
"id": "A2",
"text": "VICE emulates the 1351 on control port 1 with -controlport1device 3 (added to tools/run.ps1 and tools/smoke.ps1 automatically by the mouse-1351 capability). The host mouse must be grabbed with Alt+M (or -mouse) for the pointer to move.",
"status": "confirmed"
},
{
"id": "A3",
"text": "Memory map: screen $0400, custom charset $3800-$3FFF in VIC bank 0. Once the program (code, data, BSS including the 16 KB map) grows past $3800, the map or the charset must move (for example map at a fixed address above the program, or a custom ld65 config that reserves $3800-$3FFF and updating tools/build.ps1). The starter checks at run time that its BSS ends below $3800 and shows 'MEMORY CLASH' if not.",
"status": "unverified"
},
{
"id": "A4",
"text": "A breadth-first search over a 65x65 window, at most one search per frame, is fast enough that dwarves start walking within a second of a tile being marked.",
"status": "unverified"
},
{
"id": "A5",
"text": "Video standard is detected at start with get_tv(); timers are counted in frames and scaled for 50 Hz (PAL) and 60 Hz (NTSC).",
"status": "default"
},
{
"id": "A6",
"text": "VICE x64sc with default C64 model settings is a faithful reference for timing.",
"status": "default"
}
],
"openDecisions": [],
"toolchain": {
"recipe": "cc65",
"language": "mixed-c-asm",
"recommended": {
"recipe": "cc65",
"language": "mixed-c-asm"
},
"reasons": [
"BASIC V2 is far too slow: generating a 16 KB map, running pathfinding for three dwarves and redrawing a scrolling 920-tile view every frame is beyond interpreted BASIC.",
"C (cc65) keeps the game rules, map generator and pathfinding readable and easy to change, and cc65 ships a 1351 mouse driver.",
"Small ca65 assembly functions with C prototypes handle the speed-critical parts: the map view redraw and the frame wait. More can be moved to assembly later if profiling shows a hot spot (for example the pathfinding inner loop).",
"The user asked for exactly this split: C with assembly functions callable from C. It matches the Foundry recommendation, so no override is needed.",
"Everything builds on Windows with one cc65 install and runs in VICE x64sc."
],
"alternatives": [
{
"option": "BASIC V2",
"whyNot": "Too slow for map generation, pathfinding and per-frame view redraws."
},
{
"option": "C only (cc65)",
"whyNot": "A 920-tile view redraw in compiled C takes several frames, so scrolling would stutter. Assembly for that loop is needed."
},
{
"option": "6502 assembly only (ca65)",
"whyNot": "Fastest, but map generation, pathfinding and job logic would take much longer to write and change. The speed is only needed in a few routines."
}
],
"override": null,
"assumptionsToVerify": [
"A1: the pointer follows the grabbed host mouse and the left button is detected while the joystick in port 2 and the keyboard still work (before M2 is complete).",
"A3: memory map. Check the map file (build/stonehold-64.map) at every milestone; settle where the 16 KB map lives in M1.",
"A4: measure worst-case pathfinding time with a border-colour timing bar in M3.",
"Frame budget: the view redraw finishes within one frame on PAL and NTSC (timing bar) in M1."
]
},
"starter": {
"screenTitle": "STONEHOLD 64",
"expectedScreen": "Row 0: 'STONEHOLD 64'. Row 1: 'CHARSET OK' (or 'MEMORY CLASH' if the program has grown over the charset at $3800). Rows 3-21: a sample patch of map drawn with the custom glyphs: brown soft rock with grey hard-rock flecks, a dark-grey floor cave in the middle with three orange dwarves, two yellow marked rock tiles and a white cursor bracket. Row 23: a glyph legend (ROCK, HARD, FLOOR, DWARF, DIG). Row 24: 'STONE 000 FRAME nnn ANY KEY EXITS' with the frame counter changing every frame. Any key restores the normal character set and returns to BASIC.",
"smokeChecks": [
{
"row": 0,
"col": 0,
"text": "STONEHOLD 64",
"description": "Title on row 0"
},
{
"row": 1,
"col": 0,
"text": "CHARSET OK",
"description": "Custom charset installed without a memory clash"
},
{
"row": 24,
"col": 0,
"text": "STONE 000",
"description": "Stone counter on the status line"
}
],
"filesDir": "stonehold-64-files",
"requirements": [
"R1"
]
},
"milestones": [
{
"id": "M1",
"title": "World and view",
"goal": "A random 128x128 map exists and the player can scroll around it with the keyboard.",
"tasks": [
{
"id": "M1.1",
"text": "Settle the memory map (A3): where the 16 KB map, the charset and the program live. Add a check that fails the build or shows an error if they overlap.",
"requirements": [
"R1",
"R2"
],
"outcome": "Documented memory map in docs/ and a PRG that still passes the smoke test",
"check": "build/stonehold-64.map shows no overlap; smoke test passes"
},
{
"id": "M1.2",
"text": "Map generator in C: seeded PRNG, soft rock, hard-rock veins, caverns, starting cave near the centre. Show the seed on row 24.",
"requirements": [
"R2"
],
"outcome": "PRG that generates a map and shows 'SEED nnnnn'",
"check": "Manual test MT1.1"
},
{
"id": "M1.3",
"text": "Assembly view redraw (draw_view(x, y), C prototype) copying a 40x23 window of the map to screen and colour RAM via a tile-to-glyph/colour table.",
"requirements": [
"R3"
],
"outcome": "PRG with a full-view redraw inside one frame",
"check": "Border-colour timing bar ends before the bottom of the screen on PAL and NTSC"
},
{
"id": "M1.4",
"text": "Keyboard cursor (cursor keys and W/A/S/D) with edge scrolling and map-border clamping. Status line: 'STONE 000 SEED nnnnn RUN'.",
"requirements": [
"R3",
"R7"
],
"outcome": "PRG in which the cursor moves and the view scrolls",
"check": "Manual test MT1.2"
}
],
"manualTests": [
{
"id": "MT1.1",
"title": "Random map and seed",
"target": "c64",
"setup": "VICE x64sc, PAL.",
"steps": [
"Start the game and note the seed on row 24.",
"Reset VICE and start the game again; note the seed."
],
"expected": [
"Row 24 shows 'SEED nnnnn' each time",
"The two seeds differ and the visible maps differ",
"Three dwarves stand on floor tiles inside a cave"
],
"requirements": [
"R1",
"R2"
]
},
{
"id": "MT1.2",
"title": "Scroll to all four edges",
"target": "c64",
"setup": "VICE x64sc, PAL.",
"steps": [
"Hold the right cursor key until the view stops moving.",
"Repeat for down, left and up (W/A/S/D as well)."
],
"expected": [
"The view scrolls one tile at a time without garbage characters",
"Scrolling stops at each map edge and the cursor cannot leave the map"
],
"requirements": [
"R3"
]
}
]
},
{
"id": "M2",
"title": "Designation by keyboard, joystick and mouse",
"goal": "The player can mark and unmark rock tiles with any of the three input devices.",
"tasks": [
{
"id": "M2.1",
"text": "Mark/unmark with D on rock tiles only; marked-rock glyph. Joystick port 2 cursor movement with key repeat and fire to mark.",
"requirements": [
"R4"
],
"outcome": "PRG in which D and fire toggle marks",
"check": "Manual test MT2.1"
},
{
"id": "M2.2",
"text": "1351 mouse via cc65 c64_1351_mou: sprite 0 pointer, dig cursor = tile under the pointer tip, left button marks/unmarks, pointer at a view edge scrolls. Verify A1/A2 and record the exact VICE options in docs/.",
"requirements": [
"R5"
],
"outcome": "PRG controllable by mouse",
"check": "Manual test MT2.2"
}
],
"manualTests": [
{
"id": "MT2.1",
"title": "Mark by keyboard and joystick",
"target": "c64",
"setup": "VICE x64sc, PAL, a joystick or keyset mapped to port 2.",
"steps": [
"Move the cursor onto a rock tile and press D, then D again.",
"Move onto a floor tile and press D.",
"Use the joystick to move to another rock tile and press fire."
],
"expected": [
"D marks the rock tile (yellow marked glyph) and the second D unmarks it",
"D on floor changes nothing",
"The joystick moves the cursor and fire marks the tile"
],
"requirements": [
"R4"
]
},
{
"id": "MT2.2",
"title": "Mark by mouse",
"target": "c64",
"setup": "VICE x64sc, PAL, control port 1 set to Mouse (1351), mouse grab enabled.",
"steps": [
"Move the mouse slowly across the map.",
"Left-click a rock tile, then click it again.",
"Hold the pointer at the right edge of the view."
],
"expected": [
"The pointer moves smoothly and the highlighted cursor tile is always under the pointer tip",
"The first click marks the tile, the second unmarks it",
"The map scrolls right while the pointer stays at the edge"
],
"requirements": [
"R5"
]
}
]
},
{
"id": "M3",
"title": "Dwarves at work",
"goal": "Three dwarves mine marked tiles on their own; the stone counter and pause work, at the same speed on PAL and NTSC.",
"tasks": [
{
"id": "M3.1",
"text": "Dwarf job system: idle dwarves claim the nearest reachable marked tile via a windowed breadth-first search (one search per frame at most), walk there, mine for a time that depends on the rock type, turn it into floor.",
"requirements": [
"R6"
],
"outcome": "PRG in which dwarves mine marked tiles",
"check": "Manual test MT3.1; timing bar for the search (A4)"
},
{
"id": "M3.2",
"text": "Stone counter increments per mined tile; SPACE pauses and resumes; marking still works while paused.",
"requirements": [
"R7",
"R8"
],
"outcome": "PRG with a working counter and pause",
"check": "Manual test MT3.2"
},
{
"id": "M3.3",
"text": "Frame-based timers scaled for PAL and NTSC using get_tv().",
"requirements": [
"R10"
],
"outcome": "PRG with matching speed on both standards",
"check": "Manual test MT3.3"
}
],
"manualTests": [
{
"id": "MT3.1",
"title": "Dwarves mine marked tiles",
"target": "c64",
"setup": "VICE x64sc, PAL.",
"steps": [
"Mark three adjacent rock tiles at the edge of the starting cave.",
"Watch the dwarves.",
"Mark one soft and one hard rock tile and compare mining time.",
"Mark a rock tile that is completely enclosed by rock."
],
"expected": [
"Within about 5 seconds dwarves walk to the marked tiles, each to a different one",
"Each mined tile turns into floor",
"Hard rock takes clearly longer (about 3x)",
"The enclosed tile stays marked and no dwarf gets stuck"
],
"requirements": [
"R6"
]
},
{
"id": "MT3.2",
"title": "Stone counter and pause",
"target": "c64",
"setup": "VICE x64sc, PAL.",
"steps": [
"Note 'STONE 000' and mark two tiles; wait until both are mined.",
"Press SPACE while a dwarf is walking; mark another tile.",
"Press SPACE again."
],
"expected": [
"The counter reads 'STONE 002' after two tiles",
"Row 24 shows 'PAUSED', the dwarves stop, and marking still works",
"Row 24 shows 'RUN' and the dwarves continue"
],
"requirements": [
"R7",
"R8"
]
},
{
"id": "MT3.3",
"title": "Same speed on PAL and NTSC",
"target": "c64",
"setup": "VICE x64sc started once with -pal and once with -ntsc.",
"steps": [
"Mark a tile 10 tiles away from a dwarf through open floor and time how long it takes to arrive."
],
"expected": [
"The two times differ by less than 10%"
],
"requirements": [
"R10"
]
}
]
},
{
"id": "M4",
"title": "Sound",
"goal": "The game gives audible feedback for marking and mining.",
"tasks": [
{
"id": "M4.1",
"text": "SID effects (assembly or C): mark/unmark click on one voice, pick strike on another, silenced while paused.",
"requirements": [
"R9"
],
"outcome": "PRG with sound effects",
"check": "Manual test MT4.1"
}
],
"manualTests": [
{
"id": "MT4.1",
"title": "Sound effects",
"target": "c64",
"setup": "VICE x64sc, PAL, sound on.",
"steps": [
"Mark and unmark a tile.",
"Watch and listen while a dwarf mines; pause during mining."
],
"expected": [
"A click on each mark and unmark",
"Repeated pick strikes while mining, which stop when the tile is done or the game is paused"
],
"requirements": [
"R9"
]
}
]
}
],
"destination": "C:\\Development\\Commodore\\Foundry Projects\\stonehold-64",
"approval": {
"approvedBy": "Daniel Covington",
"approvedOn": "2026-11-26",
"notes": "Approved together with the request to add 1351 mouse support to the Foundry."
},
"generated": {
"by": "C64/C128 Dev Foundry",
"foundryVersion": "1.0",
"on": "2026-11-26",
"fromBrief": "stonehold-64.json"
},
"resolved": {
"_note": "Generated by the C64/C128 Dev Foundry from the approved brief and catalog. tools/*.ps1 read this section; edit it (and docs/toolchain.md) together if the build changes.",
"recipe": "cc65",
"recipeTitle": "Windows cross-development with cc65 (C, ca65 assembly or mixed) and VICE",
"language": "mixed-c-asm",
"languageTitle": "C (cc65) with ca65 assembly modules",
"starter": "cc65-mixed",
"tools": [
{
"id": "cl65",
"executable": "cl65",
"package": "cc65",
"purpose": "cc65 compile/assemble/link driver (C and ca65 assembly)",
"verifiedVersion": "cl65 V2.19 - Git cc3c40c",
"versionArgs": [
"--version"
],
"envVar": "CC65_HOME",
"searchPaths": [
"C:\\cc65\\bin",
"C:\\Program Files\\cc65\\bin"
],
"install": {
"source": "https://cc65.github.io/getting-started.html",
"download": "https://sourceforge.net/projects/cc65/files/cc65-snapshot-win64.zip",
"firstCommand": "Download https://sourceforge.net/projects/cc65/files/cc65-snapshot-win64.zip, unzip it (for example to C:\\cc65), then run: [Environment]::SetEnvironmentVariable('CC65_HOME','C:\\cc65','User') and open a new terminal."
},
"docs": [
"https://cc65.github.io/doc/cl65.html",
"https://cc65.github.io/doc/ca65.html"
],
"requiredFor": [
"build of target c64 (tools/build.ps1)"
]
},
{
"id": "x64sc",
"executable": "x64sc",
"package": "vice",
"purpose": "VICE cycle-exact Commodore 64 emulator",
"verifiedVersion": "VICE 3.10",
"versionArgs": [],
"envVar": "VICE_HOME",
"searchPaths": [
"C:\\Program Files\\GTK3VICE-*\\bin",
"C:\\Program Files\\SDL2VICE-*",
"%LOCALAPPDATA%\\Microsoft\\WinGet\\Packages\\VICE-Team.VICE.GTK3*\\*\\bin"
],
"install": {
"source": "https://vice-emu.sourceforge.io/index.html#download",
"download": "https://sourceforge.net/projects/vice-emu/files/releases/binaries/windows/GTK3VICE-3.10-win64.zip/download",
"firstCommand": "winget install --id VICE-Team.VICE.GTK3 -e (or unzip GTK3VICE-3.10-win64.zip and set VICE_HOME to the unzipped folder)"
},
"docs": [
"https://vice-emu.sourceforge.io/vice_2.html#SEC50",
"https://vice-emu.sourceforge.io/vice_6.html",
"https://vice-emu.sourceforge.io/vice_12.html"
],
"requiredFor": [
"run and smoke test of target c64 (tools/run.ps1, tools/smoke.ps1)"
]
}
],
"targets": [
{
"id": "c64",
"name": "Commodore 64 (PAL primary, NTSC supported)",
"platform": "c64",
"display": "vicii-40",
"video": "pal",
"videoSupport": "pal-ntsc",
"artifact": "build/stonehold-64.prg",
"expectedBehavior": "Autostarts to the Stonehold screen drawn with the custom character set: title on row 0, a map view on rows 1-23, status line (stone counter, seed, RUN/PAUSED) on row 24. Three dwarves move on their own to mine tiles the player marks with the mouse, joystick or keyboard.",
"build": {
"kind": "cc65",
"cc65Target": "c64",
"config": null,
"defines": [
"FOUNDRY_TARGET_C64"
],
"sourceDirs": [
"src"
],
"labels": "build/stonehold-64.lbl",
"map": "build/stonehold-64.map"
},
"disk": null,
"emulator": {
"binary": "x64sc",
"args": [
"-controlport1device",
"3"
],
"autostart": "prg",
"notes": [
"mouse-1351: Control port 1 = Mouse (1351). Grab the host mouse in VICE with Alt+M (default GTK3 hotkeys; Alt+Q with the WinVICE legacy hotkey file) or start VICE with -mouse; without a grab the C64 pointer does not move. Press Alt+M again to release it."
]
},
"smoke": {
"ready": {
"kind": "exec",
"symbol": "_smoke_ready",
"address": null
},
"limitCycles": 30000000,
"dumps": [
{
"name": "screen",
"symbol": null,
"address": "0400",
"length": 1000
},
{
"name": "vector",
"symbol": null,
"address": "FFFC",
"length": 2
}
],
"checks": [
{
"dump": "screen",
"offset": 0,
"text": "STONEHOLD 64",
"encoding": "screen-mixed",
"bytes": null,
"description": "Title on row 0"
},
{
"dump": "screen",
"offset": 40,
"text": "CHARSET OK",
"encoding": "screen-mixed",
"bytes": null,
"description": "Custom charset installed without a memory clash"
},
{
"dump": "screen",
"offset": 960,
"text": "STONE 000",
"encoding": "screen-mixed",
"bytes": null,
"description": "Stone counter on the status line"
},
{
"dump": "vector",
"offset": 0,
"text": null,
"encoding": null,
"bytes": "E2 FC",
"description": "C64 KERNAL reset vector at $FFFC (machine is in C64 mode)"
}
],
"expectedScreen": "Row 0: 'STONEHOLD 64'. Row 1: 'CHARSET OK' (or 'MEMORY CLASH' if the program has grown over the charset at $3800). Rows 3-21: a sample patch of map drawn with the custom glyphs: brown soft rock with grey hard-rock flecks, a dark-grey floor cave in the middle with three orange dwarves, two yellow marked rock tiles and a white cursor bracket. Row 23: a glyph legend (ROCK, HARD, FLOOR, DWARF, DIG). Row 24: 'STONE 000 FRAME nnn ANY KEY EXITS' with the frame counter changing every frame. Any key restores the normal character set and returns to BASIC."
},
"recipeStatus": "verified",
"validationPlan": []
}
],
"onCommodore": null,
"catalogVerifiedOn": "2026-11-26",
"catalogVerifiedWith": {
"cc65": "cl65 V2.19 - Git cc3c40c (Windows x64 snapshot)",
"vice": "VICE 3.10 GTK3 win64 (x64sc, x128, c1541, petcat)",
"powershell": "PowerShell 7.6.7",
"git": "git 2.53.0.windows.1",
"os": "Windows 11 Pro 10.0.26200"
},
"sources": [
"https://cc65.github.io/doc/cl65.html",
"https://cc65.github.io/doc/c64.html#toc4.2",
"https://cc65.github.io/doc/c128.html",
"https://cc65.github.io/doc/ca65.html",
"https://vice-emu.sourceforge.io/vice_2.html#SEC50",
"https://vice-emu.sourceforge.io/vice_7.html#SEC194",
"https://vice-emu.sourceforge.io/vice_12.html"
]
}
}

+ 52
- 0
src/charset.c 查看文件

@@ -0,0 +1,52 @@
/* Stonehold 64 custom character set. */
#include <string.h>
#include <c64.h>
#include "charset.h"

#define CPU_PORT (*(unsigned char *)0x01)
#define CHARROM ((const unsigned char *)0xD000)

/* Original game glyphs, 8 bytes each, in screen-code order starting at GLYPH_ROCK_SOFT. */
static const unsigned char glyphs[] = {
/* 64 soft rock: rough solid block */
0xFF, 0xDD, 0xFF, 0x77, 0xFF, 0xDD, 0xFF, 0x77,
/* 65 hard rock: dense crosshatch */
0xFF, 0x99, 0xFF, 0x66, 0xFF, 0x99, 0xFF, 0x66,
/* 66 floor: sparse pebbles */
0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x40, 0x00,
/* 67 marked rock: framed X */
0xFF, 0xC3, 0xA5, 0x99, 0x99, 0xA5, 0xC3, 0xFF,
/* 68 dwarf: hooded figure */
0x18, 0x3C, 0x18, 0x7E, 0x5A, 0x18, 0x24, 0x66,
/* 69 cursor: corner brackets */
0xE7, 0x81, 0x81, 0x00, 0x00, 0x81, 0x81, 0xE7
};

void charset_install(void)
{
unsigned char *dst = (unsigned char *)CHARSET_ADDR;
unsigned char old_port;
unsigned i;

memset(dst, 0, 2048);

/* Map the character ROM in at $D000 (clear CHAREN) to copy codes 0-63. */
__asm__("sei");
old_port = CPU_PORT;
CPU_PORT = (unsigned char)(old_port & 0xFB);
for (i = 0; i < 64u * 8u; ++i) {
dst[i] = CHARROM[i];
}
CPU_PORT = old_port;
__asm__("cli");

memcpy(dst + GLYPH_ROCK_SOFT * 8u, glyphs, sizeof glyphs);

/* Screen at $0400 (upper nibble 1), charset at $3800 (bits 1-3 = 7). */
VIC.addr = 0x1E;
}

void charset_remove(void)
{
VIC.addr = 0x15; /* screen $0400, ROM uppercase set */
}

+ 21
- 0
src/charset.h 查看文件

@@ -0,0 +1,21 @@
#ifndef CHARSET_H
#define CHARSET_H

/* Custom character set location (VIC bank 0, 2 KB). See docs and assumption A3. */
#define CHARSET_ADDR 0x3800u

/* Game glyph screen codes (codes 0-63 keep the ROM letter shapes). */
#define GLYPH_ROCK_SOFT 64
#define GLYPH_ROCK_HARD 65
#define GLYPH_FLOOR 66
#define GLYPH_MARKED 67
#define GLYPH_DWARF 68
#define GLYPH_CURSOR 69

/* Build the charset at CHARSET_ADDR and point the VIC-II at it. */
void charset_install(void);

/* Point the VIC-II back at the ROM uppercase set. */
void charset_remove(void);

#endif

+ 5
- 0
src/frame.h 查看文件

@@ -0,0 +1,5 @@
#ifndef FRAME_H
#define FRAME_H
/* Wait until the raster beam reaches the bottom border once (one video frame). */
void __fastcall__ wait_frame(void);
#endif

+ 18
- 0
src/frame.s 查看文件

@@ -0,0 +1,18 @@
; wait_frame: block until the VIC-II raster reaches line 251 (bottom border), once per frame.
; Works on PAL and NTSC because line 251 exists on both.
.export _wait_frame

VIC_RASTER = $D012
VIC_CTRL1 = $D011

.segment "CODE"
_wait_frame:
@leave: lda VIC_RASTER ; first make sure we are not already on line 251
cmp #251
beq @leave
@wait: lda VIC_CTRL1 ; bit 7 = raster bit 8; we want line < 256
bmi @wait
lda VIC_RASTER
cmp #251
bne @wait
rts

+ 118
- 0
src/main.c 查看文件

@@ -0,0 +1,118 @@
/* Stonehold 64 - starter (milestone M0).
**
** Installs the game's own character set at $3800 (VIC bank 0, screen stays at $0400),
** draws a sample patch of map with the custom glyphs and runs the frame-locked loop
** (wait_frame() from frame.s) with a visible frame counter.
**
** Character set layout:
** codes 0-63 copied from the uppercase ROM set (letters, digits, punctuation)
** codes 64-69 game glyphs (see charset.h)
**
** Screen layout (40x25 text, VIC-II):
** row 0 title
** row 1 charset / memory check
** rows 3-21 sample map patch
** row 23 glyph legend
** row 24 status line
*/
#include <conio.h>
#include <string.h>
#include <c64.h>
#include "smoke.h"
#include "frame.h"
#include "charset.h"

#define SCREEN ((unsigned char *)0x0400)
#define COLRAM ((unsigned char *)0xD800)

/* Linker symbols: end of the program's BSS must stay below the charset. */
extern unsigned char _BSS_RUN__[];
extern unsigned char _BSS_SIZE__[];

static void put_tile(unsigned char x, unsigned char y, unsigned char code, unsigned char color)
{
unsigned off = (unsigned)y * 40u + x;
SCREEN[off] = code;
COLRAM[off] = color;
}

static void draw_sample_map(void)
{
unsigned char x, y;
for (y = 3; y <= 21; ++y) {
for (x = 0; x < 40; ++x) {
if ((unsigned char)((x * 7u + y * 13u) % 11u) == 0) {
put_tile(x, y, GLYPH_ROCK_HARD, COLOR_GRAY2);
} else {
put_tile(x, y, GLYPH_ROCK_SOFT, COLOR_BROWN);
}
}
}
/* Starting cave. */
for (y = 9; y <= 15; ++y) {
for (x = 14; x <= 25; ++x) {
put_tile(x, y, GLYPH_FLOOR, COLOR_GRAY1);
}
}
put_tile(17, 12, GLYPH_DWARF, COLOR_ORANGE);
put_tile(19, 11, GLYPH_DWARF, COLOR_ORANGE);
put_tile(21, 13, GLYPH_DWARF, COLOR_ORANGE);
put_tile(26, 12, GLYPH_MARKED, COLOR_YELLOW);
put_tile(26, 13, GLYPH_MARKED, COLOR_YELLOW);
put_tile(24, 14, GLYPH_CURSOR, COLOR_WHITE);
}

static void draw_legend(void)
{
textcolor(COLOR_GRAY3);
put_tile(0, 23, GLYPH_ROCK_SOFT, COLOR_BROWN);
cputsxy(2, 23, "ROCK");
put_tile(8, 23, GLYPH_ROCK_HARD, COLOR_GRAY2);
cputsxy(10, 23, "HARD");
put_tile(16, 23, GLYPH_FLOOR, COLOR_GRAY1);
cputsxy(18, 23, "FLOOR");
put_tile(25, 23, GLYPH_DWARF, COLOR_ORANGE);
cputsxy(27, 23, "DWARF");
put_tile(34, 23, GLYPH_MARKED, COLOR_YELLOW);
cputsxy(36, 23, "DIG");
}

int main(void)
{
unsigned char frames = 0;
unsigned char charset_ok;

bordercolor(COLOR_BLACK);
bgcolor(COLOR_BLACK);
clrscr();

/* The charset area must not overlap the program (assumption A3). */
charset_ok = (unsigned)_BSS_RUN__ + (unsigned)_BSS_SIZE__ <= CHARSET_ADDR;

textcolor(COLOR_WHITE);
cputsxy(0, 0, "STONEHOLD 64");
if (charset_ok) {
charset_install();
cputsxy(0, 1, "CHARSET OK");
draw_sample_map();
draw_legend();
} else {
textcolor(COLOR_LIGHTRED);
cputsxy(0, 1, "MEMORY CLASH");
}
textcolor(COLOR_WHITE);
cputsxy(0, 24, "STONE 000 FRAME ANY KEY EXITS");

smoke_capture();
smoke_ready();

while (!kbhit()) {
wait_frame();
gotoxy(18, 24);
cprintf("%3u", (unsigned)frames++);
}
cgetc();
charset_remove();
clrscr();
return 0;
}

+ 48
- 0
src/smoke.c 查看文件

@@ -0,0 +1,48 @@
/* Smoke-test hooks. See smoke.h. */
#include "smoke.h"

#if defined(__C128__) && defined(FOUNDRY_VDC80)
#include <c128.h>

unsigned char smoke_probe[SMOKE_PROBE_ROWS * 80];

static unsigned char vdc_read(unsigned char reg)
{
VDC.ctrl = reg;
while ((VDC.ctrl & 0x80) == 0) { }
return VDC.data;
}

static void vdc_write(unsigned char reg, unsigned char value)
{
VDC.ctrl = reg;
while ((VDC.ctrl & 0x80) == 0) { }
VDC.data = value;
}

void smoke_capture(void)
{
/* VDC registers 12/13 hold the screen start; register 31 reads VDC RAM and
** auto-increments the update address in registers 18/19. */
unsigned char hi = vdc_read(12);
unsigned char lo = vdc_read(13);
unsigned i;
vdc_write(18, hi);
vdc_write(19, lo);
for (i = 0; i < sizeof smoke_probe; ++i) {
smoke_probe[i] = vdc_read(31);
}
}
#else
unsigned char smoke_probe[1];

void smoke_capture(void)
{
/* 40-column builds: tools/smoke.ps1 reads screen RAM at $0400 directly. */
}
#endif

void smoke_ready(void)
{
/* Intentionally empty: VICE tracepoint target. */
}

+ 17
- 0
src/smoke.h 查看文件

@@ -0,0 +1,17 @@
/* Smoke-test hooks used by tools/smoke.ps1. Keep these in the program.
**
** smoke_capture() copies what is on the VDC 80-column screen into smoke_probe[]
** (80-column builds only), because VICE can only save CPU-visible memory.
** smoke_ready() is an empty function: tools/smoke.ps1 sets a VICE tracepoint on it
** and saves screen memory when it runs. Call both once the first screen is drawn.
*/
#ifndef SMOKE_H
#define SMOKE_H

#define SMOKE_PROBE_ROWS 4

extern unsigned char smoke_probe[];
void smoke_capture(void);
void smoke_ready(void);

#endif

+ 31
- 0
tools/build.ps1 查看文件

@@ -0,0 +1,31 @@
<#
.SYNOPSIS
Build every target (or one target) listed in project.json.

.DESCRIPTION
Reads resolved.targets from project.json. cc65 targets compile every .c and .s file in the
target's source folders; BASIC targets tokenize the listing with petcat. Targets with a disk
section also get a disk image built with c1541. Outputs go to build/ (ignored by Git).

Exit codes: 0 = built, 1 = build error, 2 = a required tool is missing.

.EXAMPLE
pwsh -File tools/build.ps1
pwsh -File tools/build.ps1 -Target c64
#>
[CmdletBinding()]
param([string]$Target)
. (Join-Path $PSScriptRoot 'lib.ps1')

try {
$project = Get-ProjectConfig
$done = @{}
foreach ($t in Get-ProjectTargets $project $Target) { Invoke-TargetBuild $project $t $done }
Write-Host "Build complete."
} catch [MissingToolException] {
Write-Host $_.Exception.Message -ForegroundColor Yellow
exit 2
} catch {
Write-Host "BUILD FAILED: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}

+ 48
- 0
tools/check-prereqs.ps1 查看文件

@@ -0,0 +1,48 @@
<#
.SYNOPSIS
Check that every tool this project needs is installed, and say exactly what to do if not.

.DESCRIPTION
Looks for each tool in resolved.tools (project.json) in this order: the tool's environment
variable (for example VICE_HOME or CC65_HOME, pointing at the install folder or its bin
folder), then PATH, then common install folders. Prints the path and version found, or the
first command to run and what stays unverified until the tool is installed.

Exit codes: 0 = everything found, 2 = something is missing.
#>
[CmdletBinding()]
param()
. (Join-Path $PSScriptRoot 'lib.ps1')

$project = Get-ProjectConfig
$missing = 0
Write-Host "Prerequisites for $($project.project.name)"
Write-Host ""
$ps = $PSVersionTable.PSVersion
if ($ps.Major -ge 7) { Write-Host (" [ok] PowerShell {0}" -f $ps) -ForegroundColor Green }
else { Write-Host " [MISSING] PowerShell 7+ (running $ps). First step: winget install --id Microsoft.PowerShell -e" -ForegroundColor Yellow; $missing++ }

$git = Get-Command git -ErrorAction SilentlyContinue
if ($git) { Write-Host (" [ok] {0}" -f ((& git --version) -join '')) -ForegroundColor Green }
else { Write-Host " [MISSING] git. First step: winget install --id Git.Git -e" -ForegroundColor Yellow; $missing++ }

foreach ($tool in @($project.resolved.tools)) {
$path = Find-ToolPath $tool
if ($path) {
$ver = Get-ToolVersion $tool $path
Write-Host (" [ok] {0,-7} {1}" -f $tool.executable, $ver) -ForegroundColor Green
Write-Host (" {0}" -f $path)
Write-Host (" verified with: {0}" -f $tool.verifiedVersion)
} else {
$missing++
Write-Host (" [MISSING] {0} - {1}" -f $tool.executable, $tool.purpose) -ForegroundColor Yellow
Write-Host (" First step : {0}" -f $tool.install.firstCommand)
Write-Host (" Source : {0}" -f $tool.install.source)
Write-Host (" Or set {0} to the install folder." -f $tool.envVar)
Write-Host (" Unverified until installed: {0}" -f (@($tool.requiredFor) -join '; '))
}
}
Write-Host ""
if ($missing) { Write-Host "$missing prerequisite(s) missing." -ForegroundColor Yellow; exit 2 }
Write-Host "All prerequisites found. Next: pwsh -File tools/smoke.ps1"
exit 0

+ 248
- 0
tools/lib.ps1 查看文件

@@ -0,0 +1,248 @@
# Shared helpers for tools/*.ps1. Generated by the C64/C128 Dev Foundry.
# Everything project-specific comes from project.json ("resolved" section), so these
# scripts do not need editing when sources are added. Requires PowerShell 7+.
Set-StrictMode -Version 1.0
$ErrorActionPreference = 'Stop'

$script:RepoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path

class MissingToolException : System.Exception {
[string]$ToolId
MissingToolException([string]$toolId, [string]$message) : base($message) { $this.ToolId = $toolId }
}

function Get-RepoRoot { $script:RepoRoot }

function Get-RepoPath([string]$Relative) {
if ([IO.Path]::IsPathRooted($Relative)) { return $Relative }
Join-Path $script:RepoRoot ($Relative -replace '[\\/]', [IO.Path]::DirectorySeparatorChar)
}

function Get-ProjectConfig {
$path = Join-Path $script:RepoRoot 'project.json'
Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable -Depth 64
}

function Get-ProjectTargets([hashtable]$Project, [string]$TargetId) {
$targets = @($Project.resolved.targets)
if ($TargetId) {
$targets = @($targets | Where-Object { $_.id -eq $TargetId })
if ($targets.Count -eq 0) {
$known = ($Project.resolved.targets | ForEach-Object { $_.id }) -join ', '
throw "Unknown target '$TargetId'. Known targets: $known"
}
}
$targets
}

function Get-ToolEntry([hashtable]$Project, [string]$ToolId) {
$entry = $Project.resolved.tools | Where-Object { $_.id -eq $ToolId } | Select-Object -First 1
if (-not $entry) { throw "project.json does not list tool '$ToolId' under resolved.tools." }
$entry
}

function Find-ToolPath([hashtable]$Tool) {
$exe = $Tool.executable
$names = if ($IsWindows) { @("$exe.exe", $exe) } else { @($exe) }
# 1. Explicit environment variable (folder or folder\bin)
if ($Tool.envVar) {
$base = [Environment]::GetEnvironmentVariable($Tool.envVar)
if ($base) {
foreach ($dir in @($base, (Join-Path $base 'bin'))) {
foreach ($n in $names) {
$p = Join-Path $dir $n
if (Test-Path -LiteralPath $p -PathType Leaf) { return $p }
}
}
}
}
# 2. PATH
$cmd = Get-Command $exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($cmd) { return $cmd.Source }
# 3. Well-known install folders (newest first)
foreach ($pattern in @($Tool.searchPaths)) {
if (-not $pattern) { continue }
$expanded = [Environment]::ExpandEnvironmentVariables($pattern)
$dirs = @(Resolve-Path -Path $expanded -ErrorAction SilentlyContinue | ForEach-Object { $_.ProviderPath } | Sort-Object -Descending)
foreach ($dir in $dirs) {
foreach ($n in $names) {
$p = Join-Path $dir $n
if (Test-Path -LiteralPath $p -PathType Leaf) { return $p }
}
}
}
$null
}

function Get-ToolPath([hashtable]$Project, [string]$ToolId) {
$tool = Get-ToolEntry $Project $ToolId
$path = Find-ToolPath $tool
if (-not $path) {
$msg = @"
MISSING TOOL: $($tool.executable) ($($tool.purpose))
First step : $($tool.install.firstCommand)
Source : $($tool.install.source)
Detection : set $($tool.envVar) to the install folder, or put $($tool.executable) on PATH.
Unverified until installed: $(@($tool.requiredFor) -join '; ')
"@
throw [MissingToolException]::new($ToolId, $msg)
}
$path
}

function Get-ToolVersion([hashtable]$Tool, [string]$Path) {
if (-not $Tool.versionArgs -or @($Tool.versionArgs).Count -eq 0) {
# VICE emulators have no quiet version switch; report the install folder name instead.
return "(version from folder) " + (Split-Path (Split-Path $Path -Parent) -Leaf)
}
try {
$out = & $Path @($Tool.versionArgs) 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -match '\d+\.\d+' } | Select-Object -First 1
if ($out) { return $out.Trim() }
} catch { }
'(version unknown)'
}

function Invoke-Tool([string]$Path, [string[]]$Arguments, [string]$WorkingDirectory = $script:RepoRoot) {
Write-Host (" > {0} {1}" -f (Split-Path $Path -Leaf), (($Arguments | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' '))
Push-Location -LiteralPath $WorkingDirectory
try {
$output = & $Path @Arguments 2>&1 | ForEach-Object { "$_" }
$code = $LASTEXITCODE
} finally { Pop-Location }
foreach ($line in $output) { if ($line.Trim()) { Write-Host " $line" } }
if ($code -ne 0) { throw "$(Split-Path $Path -Leaf) failed with exit code $code." }
}

# ---------------------------------------------------------------------------
# Text conversion
# ---------------------------------------------------------------------------

# Plain ASCII text -> PETSCII bytes for the upper/lower-case character set.
# ASCII lower case -> PETSCII $41-$5A, ASCII upper case -> PETSCII $C1-$DA.
# LineEndings: 'cr' converts LF and CRLF to CR ($0D); 'keep' leaves them alone.
function ConvertTo-Petscii([byte[]]$Bytes, [string]$LineEndings = 'cr') {
$out = [System.Collections.Generic.List[byte]]::new()
for ($i = 0; $i -lt $Bytes.Length; $i++) {
$b = $Bytes[$i]
if ($LineEndings -eq 'cr') {
if ($b -eq 0x0D) { $out.Add(0x0D); if ($i + 1 -lt $Bytes.Length -and $Bytes[$i + 1] -eq 0x0A) { $i++ }; continue }
if ($b -eq 0x0A) { $out.Add(0x0D); continue }
}
if ($b -ge 0x61 -and $b -le 0x7A) { $out.Add([byte]($b - 0x20)); continue }
if ($b -ge 0x41 -and $b -le 0x5A) { $out.Add([byte]($b + 0x80)); continue }
$out.Add($b)
}
, $out.ToArray()
}

# Expected text -> VIC-II/VDC screen codes.
# screen-upper: upper-case/graphics set (BASIC and KERNAL default): letters -> 1..26
# screen-mixed: lower/upper-case set (cc65 C programs): a-z -> 1..26, A-Z -> $41..$5A
function ConvertTo-ScreenCodes([string]$Text, [string]$Encoding) {
$codes = foreach ($ch in $Text.ToCharArray()) {
$c = [int]$ch
if ($c -ge 0x61 -and $c -le 0x7A) { $c - 0x60 }
elseif ($c -ge 0x41 -and $c -le 0x5A) { if ($Encoding -eq 'screen-mixed') { $c } else { $c - 0x40 } }
elseif ($c -eq 0x40) { 0 }
elseif ($c -ge 0x5B -and $c -le 0x5F) { $c - 0x40 }
else { $c }
}
, [byte[]]$codes
}

function Format-Hex([byte[]]$Bytes) { ($Bytes | ForEach-Object { '{0:X2}' -f $_ }) -join ' ' }

# ---------------------------------------------------------------------------
# Build
# ---------------------------------------------------------------------------

function Get-SourceFiles([hashtable]$Build) {
$files = foreach ($dir in @($Build.sourceDirs)) {
$full = Get-RepoPath $dir
if (Test-Path -LiteralPath $full) {
Get-ChildItem -LiteralPath $full -File | Where-Object { $_.Extension -in '.c', '.s' } | Sort-Object Name
}
}
@($files | ForEach-Object { $_.FullName })
}

function Invoke-TargetBuild([hashtable]$Project, [hashtable]$Target, [hashtable]$Done) {
$build = $Target.build
$key = "$($build.kind)|$($Target.artifact)"
if ($Done.ContainsKey($key)) {
Write-Host "[$($Target.id)] artifact $($Target.artifact) already built for target $($Done[$key])"
} else {
Write-Host "[$($Target.id)] building $($Target.artifact)"
$artifact = Get-RepoPath $Target.artifact
New-Item -ItemType Directory -Force -Path (Split-Path $artifact -Parent) | Out-Null
switch ($build.kind) {
'cc65' {
$cl65 = Get-ToolPath $Project 'cl65'
$sources = Get-SourceFiles $build
if ($sources.Count -eq 0) { throw "No .c or .s files found in $(@($build.sourceDirs) -join ', ')." }
$toolArgs = @('-t', $build.cc65Target, '-g')
if ($build.config) { $toolArgs += @('-C', $build.config, '-u', '__EXEHDR__') } else { $toolArgs += '-O' }
foreach ($d in @($build.defines)) { if ($d) { $toolArgs += @('-D', $d) } }
foreach ($dir in @($build.sourceDirs)) { $toolArgs += @('-I', (Get-RepoPath $dir)) }
$toolArgs += @('-o', $artifact, '-Ln', (Get-RepoPath $build.labels), '-m', (Get-RepoPath $build.map))
$toolArgs += $sources
Invoke-Tool $cl65 $toolArgs
# cl65 leaves object files next to sources; keep the source tree clean.
foreach ($s in $sources) { $o = [IO.Path]::ChangeExtension($s, '.o'); if (Test-Path -LiteralPath $o) { Remove-Item -LiteralPath $o } }
}
'petcat' {
$petcat = Get-ToolPath $Project 'petcat'
Invoke-Tool $petcat @("-w$($build.dialect)", '-f', '-o', $artifact, '--', (Get-RepoPath $build.source))
}
'none' {
Write-Host " This target is built on the Commodore (see docs/toolchain.md). Nothing to build on the host."
return
}
default { throw "Unknown build kind '$($build.kind)'." }
}
if (-not (Test-Path -LiteralPath $artifact)) { throw "Build reported success but $($Target.artifact) was not created." }
Write-Host (" ok: {0} ({1} bytes)" -f $Target.artifact, (Get-Item -LiteralPath $artifact).Length)
$Done[$key] = $Target.id
}
if ($Target.disk) { New-TargetDisk $Project $Target $Done }
}

function New-TargetDisk([hashtable]$Project, [hashtable]$Target, [hashtable]$Done) {
$disk = $Target.disk
$key = "disk|$($disk.image)"
if ($Done.ContainsKey($key)) { return }
$c1541 = Get-ToolPath $Project 'c1541'
$image = Get-RepoPath $disk.image
$stage = Join-Path (Split-Path $image -Parent) 'disk-files'
New-Item -ItemType Directory -Force -Path $stage | Out-Null
if (Test-Path -LiteralPath $image) { Remove-Item -LiteralPath $image }
$toolArgs = @('-format', $disk.name, $disk.format, $image)
foreach ($f in @($disk.files)) {
$src = Get-RepoPath $f.source
if (-not (Test-Path -LiteralPath $src)) { throw "Disk file source not found: $($f.source)" }
if ($f.convert -eq 'ascii-to-petscii') {
$converted = Join-Path $stage ($f.name + '.petscii')
[IO.File]::WriteAllBytes($converted, (ConvertTo-Petscii ([IO.File]::ReadAllBytes($src)) $f.lineEndings))
$src = $converted
}
$dest = if ($f.type -eq 'seq') { "$($f.name),s" } else { $f.name }
$toolArgs += @('-write', $src, $dest)
}
$toolArgs += '-list'
Write-Host "[$($Target.id)] writing disk image $($disk.image)"
Invoke-Tool $c1541 $toolArgs
$Done[$key] = $Target.id
}

# ---------------------------------------------------------------------------
# Emulator
# ---------------------------------------------------------------------------

function Get-AutostartFile([hashtable]$Target) {
if ($Target.emulator.autostart -eq 'disk') { return Get-RepoPath $Target.disk.image }
Get-RepoPath $Target.artifact
}

function Get-VideoArgs([hashtable]$Target) {
switch ($Target.video) { 'ntsc' { @('-ntsc') } default { @('-pal') } }
}

+ 42
- 0
tools/run.ps1 查看文件

@@ -0,0 +1,42 @@
<#
.SYNOPSIS
Build a target and start it in VICE for interactive testing.

.DESCRIPTION
Starts the emulator listed for the target in project.json with the target's display and
video options, attaches the disk image when there is one, and autostarts the program.
VICE uses your normal VICE settings here (unlike tools/smoke.ps1).

.EXAMPLE
pwsh -File tools/run.ps1
pwsh -File tools/run.ps1 -Target c128-80
#>
[CmdletBinding()]
param(
[string]$Target,
[switch]$NoBuild,
[ValidateSet('pal', 'ntsc')][string]$Video
)
. (Join-Path $PSScriptRoot 'lib.ps1')

try {
$project = Get-ProjectConfig
$t = if ($Target) { Get-ProjectTargets $project $Target } else { @($project.resolved.targets)[0] }
if (-not $NoBuild) { Invoke-TargetBuild $project $t @{} }
if ($t.build.kind -eq 'none' -and -not $t.disk) { throw "Target $($t.id) is built on the Commodore; follow docs/toolchain.md to load it." }
$emu = Get-ToolPath $project $t.emulator.binary
if ($Video) { $t.video = $Video }
$vargs = @(Get-VideoArgs $t) + @($t.emulator.args)
if ($t.emulator.autostart -ne 'disk' -and $t.disk) { $vargs += @('-8', (Get-RepoPath $t.disk.image)) }
$vargs += @('-autostart', (Get-AutostartFile $t))
$quoted = $vargs | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }
Write-Host "[$($t.id)] starting $($t.emulator.binary) $($quoted -join ' ')"
Start-Process -FilePath $emu -ArgumentList $quoted | Out-Null
Write-Host "Expected: $($t.expectedBehavior)"
} catch [MissingToolException] {
Write-Host $_.Exception.Message -ForegroundColor Yellow
exit 2
} catch {
Write-Host "RUN FAILED: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}

+ 158
- 0
tools/smoke.ps1 查看文件

@@ -0,0 +1,158 @@
<#
.SYNOPSIS
Build each target, run it headless in VICE, and check that the expected screen appears.

.DESCRIPTION
For every target in project.json (resolved.targets) that has a "smoke" section:
1. builds the artifact (and disk image, if any);
2. starts VICE minimized, in warp mode, with sound off and a private config file,
so your own VICE settings are never read or changed;
3. sets non-stopping monitor tracepoints on the program's "ready" point. When the
program reaches it, VICE saves the listed memory ranges (screen RAM, a VDC probe,
mode flags) to build/smoke/<target>/*.bin;
4. lets VICE quit after a fixed number of cycles (-limitcycles) and saves a screenshot;
5. compares the saved memory with the expected text and bytes.

Exit codes: 0 = all automated checks passed, 1 = a check failed, 2 = a tool is missing,
3 = nothing automated to run (manual verification only).

.EXAMPLE
pwsh -File tools/smoke.ps1
pwsh -File tools/smoke.ps1 -Target c64
#>
[CmdletBinding()]
param(
[string]$Target,
[switch]$NoBuild,
[int]$TimeoutSeconds = 180
)
. (Join-Path $PSScriptRoot 'lib.ps1')

function Resolve-SmokeAddress([hashtable]$Target, [string]$Symbol, [string]$Address) {
if ($Address) { return [Convert]::ToInt32($Address, 16) }
$labels = Get-RepoPath $Target.build.labels
if (-not (Test-Path -LiteralPath $labels)) { throw "Label file $($Target.build.labels) not found; cannot resolve symbol '$Symbol'." }
foreach ($line in Get-Content -LiteralPath $labels) {
$parts = $line -split '\s+'
if ($parts.Count -ge 3 -and $parts[2].TrimStart('.') -eq $Symbol.TrimStart('.')) { return [Convert]::ToInt32($parts[1], 16) }
}
throw "Symbol '$Symbol' not found in $($Target.build.labels). Keep the smoke hook in the source (see AGENTS.md)."
}

function ConvertFrom-ScreenCodes([byte[]]$Codes, [string]$Encoding) {
$chars = foreach ($b in $Codes) {
$c = $b -band 0x7F
if ($c -eq 0) { '@' }
elseif ($c -ge 1 -and $c -le 26) { if ($Encoding -eq 'screen-mixed') { [char](0x60 + $c) } else { [char](0x40 + $c) } }
elseif ($c -ge 0x1B -and $c -le 0x1F) { [char](0x40 + $c) }
elseif ($c -ge 0x20 -and $c -le 0x3F) { [char]$c }
elseif ($c -ge 0x41 -and $c -le 0x5A -and $Encoding -eq 'screen-mixed') { [char]$c }
else { '.' }
}
-join $chars
}

function Invoke-TargetSmoke([hashtable]$Project, [hashtable]$Target) {
$smoke = $Target.smoke
$dir = Get-RepoPath "build/smoke/$($Target.id)"
if (Test-Path -LiteralPath $dir) { Remove-Item -LiteralPath $dir -Recurse -Force }
New-Item -ItemType Directory -Force -Path $dir | Out-Null

$readyAddr = Resolve-SmokeAddress $Target $smoke.ready.symbol $smoke.ready.address
$mon = [System.Collections.Generic.List[string]]::new()
$n = 0
foreach ($d in @($smoke.dumps)) {
$n++
$start = Resolve-SmokeAddress $Target $d.symbol $d.address
$end = $start + [int]$d.length - 1
$mon.Add(('trace {0} ${1:x4}' -f $smoke.ready.kind, $readyAddr))
$mon.Add(('command {0} "bsave \"{1}.bin\" 0 {2:x4} {3:x4}"' -f $n, $d.name, $start, $end))
}
Set-Content -LiteralPath (Join-Path $dir 'monitor.txt') -Value $mon
Set-Content -LiteralPath (Join-Path $dir 'vicerc') -Value ''

$emu = Get-ToolPath $Project $Target.emulator.binary
$vargs = @('-config', 'vicerc', '-default', '-sounddev', 'dummy', '-warp', '-minimized') + (Get-VideoArgs $Target) + @($Target.emulator.args)
$vargs += @('-limitcycles', [string]$smoke.limitCycles, '-exitscreenshot', 'screen.png')
if ($Target.emulator.binary -eq 'x128') { $vargs += @('-exitscreenshotvicii', 'vicii.png') }
$vargs += @('-moncommands', 'monitor.txt')
if ($Target.emulator.autostart -eq 'disk') {
$vargs += @('-autostart', (Get-AutostartFile $Target))
} else {
if ($Target.disk) { $vargs += @('-8', (Get-RepoPath $Target.disk.image)) }
$vargs += @('-autostartprgmode', '1', '-autostart', (Get-AutostartFile $Target))
}
$quoted = $vargs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }
Set-Content -LiteralPath (Join-Path $dir 'command.txt') -Value ("`"$emu`" " + ($quoted -join ' '))
Write-Host "[$($Target.id)] running $($Target.emulator.binary) headless (limit $($smoke.limitCycles) cycles)"
$sw = [Diagnostics.Stopwatch]::StartNew()
$p = Start-Process -FilePath $emu -ArgumentList $quoted -WorkingDirectory $dir -PassThru `
-RedirectStandardOutput (Join-Path $dir 'vice.log') -RedirectStandardError (Join-Path $dir 'vice.err')
if (-not $p.WaitForExit($TimeoutSeconds * 1000)) {
$p.Kill($true)
return @{ target = $Target.id; status = 'FAIL'; seconds = [int]$sw.Elapsed.TotalSeconds; checks = @(); message = "VICE did not exit within $TimeoutSeconds s (killed)." }
}

$checks = @()
$reached = @($smoke.dumps | Where-Object { Test-Path -LiteralPath (Join-Path $dir "$($_.name).bin") }).Count -gt 0
if (-not $reached) {
$where = if ($smoke.ready.symbol) { "symbol $($smoke.ready.symbol)" } else { "store to `$$($smoke.ready.address)" }
return @{ target = $Target.id; status = 'FAIL'; seconds = [int]$sw.Elapsed.TotalSeconds; checks = @(); message = "Program never reached its ready point ($where) within $($smoke.limitCycles) cycles. See build/smoke/$($Target.id)/vice.log and screen.png." }
}
foreach ($c in @($smoke.checks)) {
$file = Join-Path $dir "$($c.dump).bin"
$result = @{ description = $c.description; pass = $false; detail = '' }
if (-not (Test-Path -LiteralPath $file)) { $result.detail = "dump '$($c.dump)' missing"; $checks += $result; continue }
$data = [IO.File]::ReadAllBytes($file)
$expected = if ($null -ne $c.text) { ConvertTo-ScreenCodes $c.text $c.encoding } else { [byte[]]($c.bytes -split '\s+' | Where-Object { $_ } | ForEach-Object { [Convert]::ToByte($_, 16) }) }
$offset = [int]$c.offset
if ($offset + $expected.Length -gt $data.Length) { $result.detail = "dump '$($c.dump)' too short"; $checks += $result; continue }
$actual = [byte[]]$data[$offset..($offset + $expected.Length - 1)]
$result.pass = ((Format-Hex $actual) -eq (Format-Hex $expected))
if ($null -ne $c.text) {
$result.detail = "expected '$($c.text)', found '$(ConvertFrom-ScreenCodes $actual $c.encoding)'"
} else {
$result.detail = "expected $(Format-Hex $expected), found $(Format-Hex $actual)"
}
$checks += $result
}
$status = if (@($checks | Where-Object { -not $_.pass }).Count -eq 0) { 'PASS' } else { 'FAIL' }
$shots = @('screen.png', 'vicii.png') | Where-Object { Test-Path -LiteralPath (Join-Path $dir $_) } | ForEach-Object { "build/smoke/$($Target.id)/$_" }
@{ target = $Target.id; status = $status; seconds = [int]$sw.Elapsed.TotalSeconds; checks = $checks; screenshots = @($shots); message = $smoke.expectedScreen }
}

$exitCode = 0
try {
$project = Get-ProjectConfig
$targets = Get-ProjectTargets $project $Target
$done = @{}
$results = @()
foreach ($t in $targets) {
if (-not $NoBuild) { Invoke-TargetBuild $project $t $done }
if (-not $t.smoke) {
$results += @{ target = $t.id; status = 'MANUAL'; checks = @(); message = 'No automated smoke check for this target; follow docs/manual-tests.md (M0).' }
continue
}
$results += Invoke-TargetSmoke $project $t
}
} catch [MissingToolException] {
Write-Host ""
Write-Host $_.Exception.Message -ForegroundColor Yellow
exit 2
}

Write-Host ""
Write-Host "Smoke results"
foreach ($r in $results) {
$color = switch ($r.status) { 'PASS' { 'Green' } 'FAIL' { 'Red' } default { 'Yellow' } }
Write-Host (" [{0}] {1}" -f $r.status, $r.target) -ForegroundColor $color
foreach ($c in @($r.checks)) { Write-Host (" {0} {1}: {2}" -f ($(if ($c.pass) { 'ok ' } else { 'FAIL' })), $c.description, $c.detail) }
if ($r.ContainsKey('screenshots') -and $r.screenshots) { Write-Host (" screenshot: {0}" -f ($r.screenshots -join ', ')) }
if ($r.message) { Write-Host " $($r.message)" }
}
New-Item -ItemType Directory -Force -Path (Get-RepoPath 'build/smoke') | Out-Null
$results | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Get-RepoPath 'build/smoke/results.json')

if (@($results | Where-Object { $_.status -eq 'FAIL' }).Count -gt 0) { $exitCode = 1 }
elseif (@($results | Where-Object { $_.status -eq 'PASS' }).Count -eq 0) { $exitCode = 3 }
exit $exitCode

正在加载...
取消
保存

Powered by TurnKey Linux.