Tutorial · Chapter 14 of 23

Reuse one buffer across a far table

Process a whole table a page at a time and decide when copying a page saves work.

Jump to a section

Choose one record, a whole table, or a range

WorkRead or copy inWrite back
Inspect or replace one recordtable.get(index)table.set(index, record) if it changed.
Repeatedly edit a small table that fits in scratchtable.materialize(scratch)table.flush(local)
Repeatedly edit a larger tabletable.materializeRange(scratch, start, count)table.flushRange(start, local)

A far get or set transfers one record through staging. Materialization trades working RAM and a larger transfer for local reads and writes. A read-only pass can skip flush. A whole-view flush needs the same record type and count on each side. A range count is a compile-time literal, while the starting index can change at runtime.

Update 200 enemies in batches of 20

Suppose a game level has 200 enemies. A record holds health, a 16-bit point total, an enemy-kind tag, a nested X/Y position, four patrol steps, the current patrol phase, and an attack cooldown. At 12 bytes each, the roster takes 2,400 bytes in REU. Reserve 240 bytes of C64 RAM for one batch of 20 records and reuse it ten times.

StepWhere it happensWhat changes
MaterializeREU to C64 RAMCopy 20 records starting at the current roster index. In the second batch, far index 20 is local index 0.
MoveC64 RAMUse each enemy's patrol step to advance X, then advance its patrol phase and count down its cooldown.
Resolve damageC64 RAMScouts that moved into the hazard at X below 12 lose one health point and gain five points.
Flush and resetC64 RAM to REUWrite the 20 updated records back to the same far start, then reclaim the buffer for the next batch.
reu-enemy-batches.zp64
const c64 = @import("c64");
const ZeroPage = @import("ZeroPage");

const Kind = enum(u8) { scout = 1, guard = 2 };
const Position = struct { x: u8, y: u8 };
const Enemy = struct {
    hp: u8,
    points: u16,
    kind: Kind,
    pos: Position,
    patrol: [4]u8,
    phase: u8,
    cooldown: u8,
};

memory {
    region tick_ram: c64 at 0x9000 size 240;
    region roster_reu: reu at 0x010000 size 2400;
    arena scratch in tick_ram;
    arena roster in roster_reu;
}

fn showEnemy(index: u8, enemy: Enemy) void {
    const x = enemy.pos.x;
    const hp = enemy.hp;
    const points = enemy.points;
    c64.console.print("ENEMY {x} X {x} HP {x} PTS {x16}\n", .{ index, x, hp, points });
}

fn tickRoster() bool {
    if (roster.allocBytes(@sizeOf(Enemy) * 200)) |bytes| {
        var enemies = ZeroPage.reu.view(Enemy, bytes, 200);
        var index: u8 = 0;
        while (index < 200) {
            enemies.set(index, Enemy{
                .hp = 6,
                .points = 0x0100,
                .kind = .scout,
                .pos = Position{ .x = index & 31, .y = 10 },
                .patrol = [_]u8{ 4, 8, 12, 16 },
                .phase = 0,
                .cooldown = 1,
            });
            index += 1;
        }

        var hits: u8 = 0;
        var start: u8 = 0;
        while (start < 200) {
            if (enemies.materializeRange(scratch, start, 20)) |batch| {
                for (0..20) |movement_index| {
                    var moving = batch.get(movement_index);
                    const phase = moving.phase;
                    const step = moving.patrol[phase];
                    moving.pos.x = moving.pos.x + step;
                    moving.phase = (phase + 1) & 3;
                    if (moving.cooldown != 0) {
                        moving.cooldown -= 1;
                    }
                    batch.set(movement_index, moving);
                }
                for (0..20) |i| {
                    var enemy = batch.get(i);
                    if (enemy.kind == .scout and enemy.pos.x < 12 and enemy.hp > 0) {
                        enemy.hp -= 1;
                        enemy.points += 5;
                        hits += 1;
                        batch.set(i, enemy);
                    }
                }
                enemies.flushRange(start, batch);
            } else {
                roster.reset();
                return false;
            }
            scratch.reset();
            start += 20;
        }

        c64.console.print("TICK HITS {x}\n", .{hits});
        const first = enemies.get(0);
        const last = enemies.get(199);
        showEnemy(0, first);
        showEnemy(199, last);
        roster.reset();
        return true;
    }
    return false;
}

export fn main() void {
    c64.console.clear();
    if (ZeroPage.reu.present()) {
        if (tickRoster() == false) {
            c64.console.print("ROSTER DOES NOT FIT\n", .{});
        }
    } else {
        c64.console.print("REU REQUIRED\n", .{});
    }
}

Open the complete source

Expect TICK HITS 38 (56 in decimal). The two sample reads after the update show ENEMY 00 X 04 HP 05 PTS 0105 and ENEMY C7 X 0B HP 05 PTS 0105. The first and last records came from different batches, and both reflect the write-back. The run command enables a 128 KiB REU. The roster starts at $010000 and ends at $010960 exclusive, so check the installed capacity before running on hardware.

The update loop issues ten copy-ins and ten write-backs. A one-record-at-a-time version that reads and writes each enemy once would issue 400 transfers for the same tick. Both move 4,800 bytes for that update. Batching cuts DMA setups, and both passes share the data while it is local. The counts exclude level initialization and the two display reads. This example resolves each enemy against a fixed hazard, so all of its work fits within the current batch. A rule that needs enemies from other batches needs a separate global pass or an index.

Try giving scratch 239 bytes. The 240-byte batch can no longer materialize and the program reports ROSTER DOES NOT FIT. In a game loop, initialize the roster when loading the level and keep it between ticks. This program runs one tick, prints the results, and releases the roster.

Finish one page before asking for the next

This example has four three-byte records in REU. A six-byte arena in C64 RAM can hold exactly two records. The first pass brings far indexes 0 and 1 into local indexes 0 and 1. The second pass brings far indexes 2 and 3 into those same local indexes.

reu-working-set.zp64
const c64 = @import("c64");
const ZeroPage = @import("ZeroPage");

const Sector = struct { visits: u8, score: u16 };

memory {
    region work_ram: c64 at 0x9000 size 6;
    region asset_ram: reu at 0x010000 size 0x0100;
    arena scratch in work_ram;
    arena assets in asset_ram;
}

fn update(sector: Sector, bonus: u8) Sector {
    return Sector{
        .visits = sector.visits + 1,
        .score = sector.score + @as(u16, bonus),
    };
}

fn run() bool {
    if (ZeroPage.reu.present() == false) {
        return false;
    }
    if (assets.allocBytes(@sizeOf(Sector) * 4)) |storage| {
        var sectors = ZeroPage.reu.view(Sector, storage, 4);
        sectors.set(0, Sector{ .visits = 0, .score = 0x1000 });
        sectors.set(1, Sector{ .visits = 0, .score = 0x2000 });
        sectors.set(2, Sector{ .visits = 0, .score = 0x3000 });
        sectors.set(3, Sector{ .visits = 0, .score = 0x4000 });

        var start: u8 = 0;
        while (start < 4) {
            if (sectors.materializeRange(scratch, start, 2)) |local| {
                var pass: u8 = 0;
                while (pass < 3) {
                    const a = local.get(0);
                    const b = local.get(1);
                    const updated_a = update(a, 1);
                    const updated_b = update(b, 2);
                    local.set(0, updated_a);
                    local.set(1, updated_b);
                    pass += 1;
                }
                sectors.flushRange(start, local);
            } else {
                assets.reset();
                return false;
            }
            scratch.reset();
            start += 2;
        }

        const first = sectors.get(0);
        const second = sectors.get(1);
        const third = sectors.get(2);
        const last = sectors.get(3);
        assets.reset();
        return first.visits == 3 and first.score == 0x1003 and
            second.visits == 3 and second.score == 0x2006 and
            third.visits == 3 and third.score == 0x3003 and
            last.visits == 3 and last.score == 0x4006;
    }
    return false;
}

export fn main() void {
    c64.console.clear();
    if (run()) {
        c64.console.print("WORKING SET OK\n", .{});
        c64.vic.border = 5;
    } else {
        c64.console.print("WORKING SET FAILED\n", .{});
        c64.vic.border = 2;
    }
}

Open the complete source

Expect WORKING SET OK. Each page receives three local update passes and one write-back. scratch.reset() makes room for the next page. Keep the successful start through flush. With a runtime start, the caller owns the destination bounds.

Check the second page and handle a short tail

Try removing only scratch.reset() inside the loop. The first page consumes the whole near arena and the second materialization fails. Restore the reset and check that the final scores are $1003, $2006, $3003, and $4006.

For an odd record count, process the full pairs and handle the final record separately with a single far get/set or a one-record materialization. Check the table bounds before choosing which path to use. The guide compares DMA counts and VICE timings for direct updates and a materialized working set.