Tuesday, February 01, 2022

Monday, March 08, 2021

Social "Justice" at Smith College

Unconscionable.  I challenge any of my SJW aligned acquaintances to defend any of this.

https://www.youtube.com/watch?v=IZZ1VC44k9k

Friday, April 19, 2019

More on drawing sprites on the ZX Spectrum

A recent discussion on the Z80 Assembly Programming on the ZX Spectrum Facebook group prompted me to look into the differing costs of various ways of drawing sprite images on the ZX Spectrum.

The discussion revolved around handling the Speccy's slightly odd display file layout.  To recap, the bitmap display consists of 24 rows of 32 columns of cells, each cell of which has 8 lines of 8 pixels (one byte per line).  The address for a particular cell line is 010RRLLL RRRCCCCC where RRRRR is the row number (0..23), CCCCC is the column number (0..31), and LLL is the line number (0..7), all in binary.  Note that the display addresses are broken into three sections under this scheme: rows 0..7, rows 8..15, and rows 16..23.

(There is a separate attribute overlay giving the foreground and background colour for each cell, but I'm not going to discuss that here.)

The advantage of this layout is that if the display address is in a Z80 register pair, HL say, one can move from one cell line to the next simply by incrementing the upper half of the register pair: inc H.

There are three main ways of drawing a sprite image on to the display.  For the sake of argument, I will assume a 16x16 pixel image (more or less standard for most games on the Speccy).  I am not going to consider clipping at the edges of the display.  I am going to assume that we will draw images to the display using the xor method (very common: redrawing an image in the same place has the effect of removing it from the display).  I will further assume that, for speed, each image comes in 8 pre-shifted forms:

xxxxxxxx xxxxxxxx ........  - x 16 lines for 0px offset
.xxxxxxx xxxxxxxx x.......  - x 16 lines for 1px offset
..xxxxxx xxxxxxxx xx......  - x 16 lines for 2px offset
.
.
.
.......x xxxxxxxx xxxxxxx.  - x 16 lines for 7px offset

(1) Break the image into cell sized chunks and draw each cell as a separate operation.  This means that a 16x16 image at an arbitrary pixel position on the display will be drawn over a 3x3 cell region (i.e., 24 lines of drawing for 50% over-draw).  I have discussed this at length here before.

(2) Draw only the lines in the image (i.e., no over-draw), dealing with the line/row/third transition with in-line code.

(3) Draw only the lines in the image, but use a separate table of display line addresses (i.e., pre-computing the line/row/third transitions ahead of time).

So how do these schemes work out?  (I'm using Simon Brattel's excellent Zeus assembler syntax here, in case anyone is wondering.)

Dealing with the line/row/third transitions with in-line code.

The best approach I could come up with here was this:
- unroll the drawing code for 8 lines at a time;
- handle the row/third adjustment after the 8th line;
- jump into the correct spot at the start (e.g., if the top line of our image starts at line 3 of our cell, then we would start drawing at the "line 3" entry point).

Here's my code to do that:

; DE points to the image data: L-to-R, T-to-B, three bytes per line.
; C is height of sprite in lines.
; HL is address of display byte for the top-left byte of the sprite image.
Xor24px_Adj proc
                ; Jump into the correct offset for row adjustment.
                ; Mean cost is about 18 + 3 * (4 + 7) + 1 * (4 + 12)
                ; = 67 t-states.
                ld A, H
                and 000111
                xor 000111
                       jr z, _L7
                dec A: jr Z, _L6
                dec A: jr Z, _L5
                dec A: jr Z, _L4
                dec A: jr Z, _L3
                dec A: jr Z, _L2
                dec A: jr Z, _L1
                ; Unrolled drawing loop.
                _XorLineAdj macro()
                    ; Cost per 3 byte line is 3 * (21 + 6) + 6 * 4 + 5
                    ; = 112 t-states.
                    ld A, (DE): xor (HL): ld (HL), A: inc DE: inc L
                    ld A, (DE): xor (HL): ld (HL), A: inc DE: inc L
                    ld A, (DE): xor (HL): ld (HL), A: inc DE
                    dec L: dec L: inc H
                    dec C: ret z
                endm
    _L0         _XorLineAdj()
    _L1         _XorLineAdj()
    _L2         _XorLineAdj()
    _L3         _XorLineAdj()
    _L4         _XorLineAdj()
    _L5         _XorLineAdj()
    _L6         _XorLineAdj()
    _L7         _XorLineAdj()
                ; Adjustment for next row.
                ; Mean cost per line is (2 * (4 + 7 + 4) + 7 + 12) / 8
                ; = 6 t-states.
                ld A, L: add 32: ld L, A: jr c, _L0
                lf A, H: sub  8: ld H, A: jr _L0
                ; Overall cost after setup overhead is
                ; 112 + 6 = 118 t-states per line.
endp

So, for 16x16px pre-shifted sprite images, we expect to take around 67 + 16 * 118 = 1,955 t-states per image with this approach (there are other overheads, of course, but let's take this as our baseline).

Note: this runs to about 189 bytes of machine code, so it is quite compact.

Dealing with the line/row/third transitions with a pre-computed table of display line addresses.

The best approach I could come up with here is to pre-compute the starting address of each display line:

    dw $4000, $4100, $4200, ..., $4700
    dw $4020, $4120, $4220, ..., $4720
    ...
    dw $40e0, $41e0, $42e0, ..., $47e0
    dw $4800, $4900, $4a00, ..., $4f00
    dw $4820, $4920, $4a20, ..., $4f20
    ...

then
- point the stack pointer SP at the correct entry for the starting display line of the sprite image;
- put the image column number in a different register, B;
- pop each display line address off the stack (this is the fastest way of fetching 16-byte data on the Z80);
- drawing code for the entire image is unrolled!  If you want to draw a smaller image, you jump into the correct entry point for that.

Here's my code to do that:

; DE points to the image data: L-to-R, T-to-B, three bytes per line.
; SP points to the table of display line start addresses offset for
;   the first line of the sprite image.
; B is the leftmost column number of the sprite image.
; User calls into the correct offset (e.g., Xor24px_Tbl_16 for a 16 line
; image).
_XorLineTbl macro()
                ; Cost per 3 byte line is 22 + 3 * (21 + 6)
                ; = 93 t-states.
                pop HL: ld A, L: or B: ld L, A
                ld A, (DE): xor (HL): ld (HL), A: inc DE: inc L
                ld A, (DE): xor (HL): ld (HL), A: inc DE: inc L
                ld A, (DE): xor (HL): ld (HL), A: inc DE
endm

Xor24px_Tbl_16  _XorLineTbl()
Xor24px_Tbl_15  _XorLineTbl()
Xor24px_Tbl_14  _XorLineTbl()
; ...
Xor24px_Tbl_3   _XorLineTbl()
Xor24px_Tbl_2   _XorLineTbl()
Xor24px_Tbl_1   _XorLineTbl()
; Exit code goes here (e.g., restore SP and ret).

So, for 16x16px pre-shifted sprite images, we expect to take around 16 * 93 = 1,488 t-states per image.  Again, there is a bit more overhead to take into account here, but I'll call this the base-line figure.

Note that this scheme uses a lot more code: around 288 bytes of unrolled drawing code for a 16x16px image along with a 384 byte address table.  For my money, that is a good trade-off for the extra speed.

Comparison.

Rounding the numbers up, fixing things at the line-8 transition costs you 2,000 t-states per sprite image whereas using the stack-pointer-into-a-lookup-table scheme costs you only 1,500 t-states per sprite image.

What does this mean in practice?  Well, the usual approach to obtaining flicker-free graphics involves waiting for the screen-refresh interrupt, then redrawing everything before the CRT scan line catches up with you.  On the ZX Spectrum the upper screen border (before the display bitmap is drawn) takes around 14,000 t-states. 

For the fix-in-code approach, this is enough time to erase and redraw 14,000 / 2,000 / 2 = 3.5 16x16px sprites before you risk being caught be the screen refresh.

For the use-a-table approach, this is enough time to erase and redraw 14,000 / 1,500 / 2 = 4.6 16x16px sprites before you risk being caught by the screen refresh.

Conclusion.

For my money, I'd go for the table-based approach.

Wednesday, July 18, 2018

High speed full-screen drawing on the ZX Spectrum

This is another retro-programming idea that occurred to me, harking back to my old ZX Spectrum days.  If you're not au fait with the speccy's screen layout, I refer you to this posting of mine about rendering sprites.

The problem is that the old Z80 isn't fast enough to update all of the video memory before the CRT beam catches up with you.  The screen has a 64 pixel upper border (requiring no video memory), followed by a 192 pixel high by 256 pixel wide bitmap, followed by a lower border (also requiring no video memory).  The bitmap is monochrome, with each consecutive set of 8 pixels being represented in a single byte.  There is a separate 24 row by 32 column attribute map specifying foreground and background colours for each 8x8 pixel cell.

The only interrupt you get on the speccy occurs once every 50th of a second when the CRT beam starts from the top of the upper border (so this is pretty much when you have to start drawing).  It takes 224 T-states (i.e., clock ticks) for the CRT beam to scan one pixel line.  Since it takes around 16 Ts to move a single byte (give or take), the Z80 can update at most half of the 32 bytes on each row of pixels before the CRT beam catches up (which would appear as "tearing" on the screen).

[Note: some games did manage a full 50 FPS refresh rate, but only by severely restricting the area of the screen that was updated.]

However, let's say you only wanted to update about a third of the bitmap at 50 FPS, but didn't want to be restricted to which third.  The remainder would be painted in the background colour, which is easily arranged by setting the corresponding cells in the attribute map to have the same foreground and background colour (i.e., the set pixels and the clear pixels in such an 8x8 cell will have the same colour).

What occurs to me is this.  For a "blank" cell, we just need to set the cell attribute.  For a "bitmap" cell, we need to set the cell attribute and set the corresponding bitmap bytes in the video memory.  Assuming that we have the address of the "current" attribute entry in DE and the bitmap entry in HL (and the magic number 1 - $0700 in BC), then we can do the following:

DrawSomeBlankCell:
    ld A, SomeAttr
    ld (DE), A
    inc E
    inc L
    ret

(for 32 Ts per blank cell)

DrawSomeBitmapCell:
    ld A, SomeAttr
    ld (DE), A
    inc E
    ld (HL), SomeBitmapByte0 : inc H
    ld (HL), SomeBitmapByte1 : inc H
    ld (HL), SomeBitmapByte2 : inc H
    ld (HL), SomeBitmapByte3 : inc H
    ld (HL), SomeBitmapByte4 : inc H
    ld (HL), SomeBitmapByte5 : inc H
    ld (HL), SomeBitmapByte6 : inc H
    ld (HL), SomeBitmapByte7 : add HL, BC
    ret

(for 146 Ts per bitmap cell).

The "draw list" would simply be a consecutive list of pointers to these drawing functions:

DrawList:
    dw Draw0, Draw1, Draw2, ..., Draw31, [fix up]
    dw Draw32, Draw33, Draw34, ..., Draw 63, [fix up]
    ....
    dw ..., Draw767, [finish up]

We would redraw the entire screen by simply pointing DE at the display attributes, HL at the display bitmap, SP at DrawList and executing a 'ret'.  (The [fix up] calls would simply deal with the odd end-of-line addressing fixes that are needed when handling the ZX Spectrum display.)

How much could we redraw, assuming an even distribution of action across the screen?  A simple calculation shows we can have a good 11 bitmaps on each line and still update the entire display before the CRT beam catches up.  That is just slightly in excess of 33% of the entire display!

(I'm currently working on a full-screen Pac Man demo. to illustrate this idea.  Time is scarce, so don't hold your breath.)

A very belated update: you can find the working source code at https://github.com/ralphbecket/Z80/tree/master/MegaPacMan showing a full-screen 50 FPS scrolling maze with four ghosts running around at random.  It could support many more and/or much larger sprites, but I'm happy to call it a day here!

Friday, November 17, 2017

Retro-programming: an High-Level Byte-Code for 8-bit CPUs

This idea has been percolating around in my hind-brain for a while now, so I thought I'd set it down on paper.

The Problem

Imagine you are back in the 1980s, programming one of the wonderfully primitive home micro-computers that has just arrived on the scene.  Say, a ZX Spectrum, sporting a mere 48 Kbytes RAM and a 3.5 MHz Z80 CPU (alternatively, a comparable 1 MHz 6502-based Commodore 64).  These CPUs are aggressively 8-bit in nature -- yes, the Z80 has some 16-bit support, but it isn't great.  Worse, these CPUs are non-orthogonal: every register seems to have its own special rules.  What would have been nice was some kind of easy-to-implement byte-code interpreter which would be comfortable to program in and for which it would be easy to write a compiler in BASIC (all home micro-computers booted directly to BASIC in those days).  This virtual machine would, of course, run more slowly than hand-crafted assembly language, but many times faster than the interpreted BASICs of the day.  Having a standardised byte-code would mean you could run the same program on any machine on which you had an implementation of the byte-code interpreter.

[Note: these thoughts are partially inspired by Wozniak's SWEET16, although that is a much lower-level VM than what I have in mind.]

One thing I have aimed for is a rich set of addressing modes, important for raising the level of abstraction and for reasonable code density.  Most 8-bit VMs that I've seen, like SWEET16, provide a rather low-level virtual machine typically requiring several instructions to do anything useful.  Ugh!

Outline of the Virtual Machine

The proposed VM works in 16-bit words.

A variable is any address in RAM.

Op-codes take 0, 1, or 2 arguments (if op-codes take a third argument which is a fixed address to branch to).  Typically, the first argument will be an assignment target.

There are two "registers", X and Y, to hold the arguments for op-codes.

The registers are set via the following instructions (the explanation uses C syntax for the semantics, recall that & in C is the "address-of" operator).

  • Xk -- load X with a constant; X := &k.
  • Xv -- load X with a variable; X := &v.
  • X_k -- subscript X by a constant; X := &(X[k]).
  • X_v -- subscript X by a variable; X := &(X[v]).
  • X@ -- indirection through X (equivalent to X_k 0); X := *X.
and similarly for the Y register.

Together, these allow for quite rich argument addressing.  For example, loading register X with x.i.foo.bar (or, in C syntax, x[i]->foo->bar) would be expressed in the VM as

  Xv x
  X_v i
  X_k foo
  X_k bar


In the VM, SP is a global stack-pointer variable used by the push, pop, call, and ret op-codes.

Op-codes:
  • X := Y; X += Y; X -= Y; X *= Y; X /= Y; X &= Y; X |= Y; X ^= Y; etc.
  • inc X; dec X
  • push X -- equivalent to SP -= 2; @SP := X.
  • pop X -- equivalent to X := @SP; SP += 2.
  • jp X -- jump to address X.
  • call X -- equivalent to push IP; jp X where IP is the address of the next op-code.
  • ret -- equivalent to pop IP.
  • poke X, Y -- write the least significant byte of Y to address X.
  • X :=peek Y -- assign the byte at address Y to X.
  • if X = Y A; if X != Y A; if X < Y A;etc. -- branch to address A if the test fails (i.e., unless X = Y; X != Y; X < Y; etc.).
  • And anything else that might be useful.
The odd inversion of the if op-codes is to support some sensible high-level syntax, such as

if q != 0 { p /= q }

which would have the obvious translation.

Example Code: Searching a Binary Tree

I'm making up some high-level syntax here, fill in any gaps using your imagination.

// Symbols for the field offsets in our binary tree vertices.
Value .equ 0
Left .equ 1
Right .equ 2

// We assume t is the root of the binary tree and we are looking for the vertex containing x.
loop {
  if t = 0 { ret } // We hit null, we failed to find x.
  t := t.Value
  if t = x { ret }
  if t < x { t := t.Left } else { t := t.Right }
}

That, I claim, is fairly neat.  The equivalent Z80 or 6502 assembly code would be far less transparent.

The above would be expanded in a simple "assembler" into something like this (where  X or Y is syntactically unchanged from its previous use, no op-codes need be omitted for set-up):

_1:
  Xv t; Yk 0; if= _2
    ret
_2:
  Yv t; Y_k Value; :=
  Yv x; if= _3
    ret
_3:
  if< _4
    Yv t; Y_k Left; :=
    Xk _5; jp
_4:
    Yv t; Y_k Right; :=
_5:
  Xk _1; jp

The Byte-code and Interpreter

Now, as an ex-Sinclair kiddie, I'm used to the Z80, so I'm going to use that to inform my idea of how the byte code might be expressed.

Rather than interpreting byte-codes, I'm simply going to propose a sequence of [op code address][arg] or just [op code address] 16-bit values as my byte code.  That is, every op-code is represented by the address of the machine code implementing it.

For example:

Xk:
  ld (X), SP: pop HL: ret    ; Because the Z80 SP now holds the address of the constant.

Xv:
  pop HL: ld (X), HL: ret

X_k:
  ld HL, (X): pop DE; add HL, DE: add HL, DE: ld (X), HL: ret

':=':
  ld HL, (Y): ld DE, (X): ldi: ldi: ret

'+=':
  ld HL, (X): ld DE, (Y)
  ld A, (DE): inc DE: add (HL): ld (HL), A: inc HL
  ld A, (DE): ld B, (HL): adc A, B: ld (HL), A    ; Ain't the Z80 horrible?
  ret

By pointing the Z80 stack-pointer at the byte-code stream, I can start executing it just by issuing the ret assembly instruction (which pops the next address off the stack and jumps to it).

Going by this, each register set-up op-code and argument takes 4 bytes, each if op-code and jump address takes 4 bytes, and every other op-code takes 2 bytes.

Under this scheme, the above binary tree search function would take 140 bytes.  This is comparable to the equivalent Z80 machine code.  It would run fairly quickly, the "interpretation" overhead being about as small as I can think of making it.

A Quick Comparison with SWEET16

This article on SWEET16 provides an 18-byte SWEET16 memory copy routine.  How would our putative VM do?

loop {
  if n = 0 { ret }
  poke dest, src
  inc dest
  inc src
}

which would turn into the following byte code:

_1:
  Xv n; Yk 0; if= _2
    ret
_2:
  Xv dest; Yv src; poke
  inc
  Xv src; inc
  jp _1

which, by my reckoning, comes to 36 bytes, twice what SWEET16 requires.  Not such a big deal given how much more comfortable the new VM feels to program in than SWEET16.

Closing Thoughts

I wish I'd thought of this back in the early 1980s!  While coding everything in assembly language was fun, it was error prone, and the weirdness of the Z80 turned every little design decision into a mental challenge.  I think this VM (and accompanying compiler) would have been possible to write in BASIC and a handful of assembler in a few evenings and that it would been a great tool for bootstrapping other projects.

(Later in life I ended up spending fifteen years in programming language design and compiler research...)


Tuesday, August 29, 2017

Tuesday, May 03, 2016

Od -- it's like Mithril and Knockout, but better

I've loved using Knockout these last few years, but struggled with its unpredictable performance.  I really like the idea of Mithril (and the other virtual-DOM schemes), but it has really wonky problems if you move a component around in your DOM.

To address these issues, I recently came up with my own scheme, Od, and I really like it:

https://github.com/ralphbecket/Web/tree/master/Od

The web site there has plenty of explanation, examples, and documentation.
TypeScript, the beautiful face of the ugly tapeworm that is JavaScript.  It's the only way to do this stuff.

To add a TypeScript component to a non-TypeScript Visual Studio project, add the following to the end of the project .csproj file (do this in notepad or somesuch; adjust the TypeScript path version accordingly):

Reload the project and away you go.  When you add TypeScript files to your project, you can set their BuildAction properties to TypeScriptCompile, if this doesn't happen automatically.

Friday, March 18, 2016

On Python (vulgar, but funny)

https://semitwist.com/articles/article/view/why-i-hate-python-or-any-dynamic-language-really

Wednesday, February 17, 2016

Wonderful explanation of quantum weirdness

A discussion on the excellent Quora site led me to this series of articles explaining the mysteries of quantum mechanics at a level comprehensible by an armchair physicist or even myself.  No hand-waving, nothing above some basic arithmetic with complex numbers, perspicuous and concise.

While on the topic, I'll take the opportunity to plug Introducing Quantum Theory which tells the tale of how physics moved from classical to quantum theory.  There's no mathematics in the book, instead it tells the story of all the things that didn't quite make sense along the way and how Dirac, Schroedinger, Einstein, and the rest of the gang arrived at the new model.  Don't be put off by the cartoonesque presentation: it is a book for grown-ups.  I've bought it three times so far, having loaned it out twice and not had it returned...

Wednesday, September 30, 2015

Faster Sprites on the ZX Spectrum

This is one for anybody who grew up programming the Sinclair ZX Spectrum, a wonderful machine from the early '80s microcomputer days, sporting a 3.5 MHz Z80 CPU and 48 KBytes of RAM.

Lacking hardware sprites, ZX Spectrum programmers were/are forced to draw directly to the display. Moving a sprite therefore involves removing the previous sprite image before drawing the new one. Since sprites can overlap, this typically means first removing all previously drawn sprites before redrawing any of them in their new positions (unless you use XOR to draw your sprites, in which case removing a sprite is just redrawing it in its previous position and removing/redrawing can occur in any order).

My code implementing the ideas here is available at https://github.com/ralphbecket/Z80/tree/master/FasterSprites

Screen Layout and Timing

To achieve flicker-free animation, all drawing must occur before the display refresh crosses the part of the screen being updated. This means understanding something of the ZX Spectrum display arrangement:

+-----------------------------------------------------+
| Border: 64 scan lines before display file.          |
|                                                     |
|    +-------------------------------------------+    |
|    |  |  |  |  |  |   Display: 256 x 192 pixels|    |
|    |--+--+--+--+--+-- arranged as 32 cols of   |    |
|    |  |  |  |  |  |   24 rows of 8x8 cells.    |    |
|    |--+--+--+--+--+--                          |    |
|    |  |  |  |  |  |                            |    |
|    |--+--+--+--+--+--                          |    |
|    |  |  |  |  |  |                            |    |
|    |                                           |    |
|    |                                           |    |
|    |                                           |    | 
|    |                                           |    | 
|    |                                           |    | 
|    |                                           |    | 
|    +-------------------------------------------+    | 
|                                                     | 
|                                                     | 
+-----------------------------------------------------+ 

The border is a single, block colour surrounding the display file. It starts 64 scan lines before the display file. The display file is a 256 x 192 pixel bitmap arranged as 24 rows of 32 columns of 8x8 pixel cells. A separate attribute map specifies a single foreground/background colour pair for each cell (i.e., colours can only be specified at the level of cells, not pixels).

Each line takes 224 Ts for the hardware to display, where 1 T = 1 t-state = 1 clock tick of the 3.5 MHz Z80 CPU. The only reliable way to know when to start drawing is to wait for the vertical refresh interrupt, which occurs every time the hardware starts drawing a new frame from the top of the screen. To put this in perspective, a typical Z80 instruction takes around 4 to 16 Ts to execute.

Assuming we want flicker-free animation, this means we have 224 * 64 = 14,336 Ts from the start of the interrupt before the display refresh catches up with us. (There is a clever trick involving waiting for the display hardware to just pass the top of the display file and start drawing behind it, but it isn't very portable.) A whole frame takes 224 * (64 + 192 + 64) = 71,680 Ts.

Display Addressing

The display file is arranged as 32 columns of 24 rows of 8x8 pixel cells. Each cell has a colour attribute and eight bytes of bitmap data. Bitmap addresses are given in binary as 010RRLLL RRRCCCCC where RRRRR is the row number (0..23), CCCCC is the column number (0..31), and LLL is the line number within the cell (0..7). Attribute addresses are given as 010110RR RRRCCCCC. The curious looking bitmap addressing is cunningly arranged so that successive lines within a cell can be reached by simply incrementing the upper byte of the address.

Moving Bytes to the Display

Now, how best to move bits on to the display file? Setting aside the attribute file for now, there are a number of options. For the sake of this part of the discussion, I'm going to assume we are just interested in moving bytes from some (pre-shifted) source to a cell on the display file.

Here are the most common approaches, assuming the source bitmap address is in DE or SP and the target display bitmap cell address is in HL:

(1) Naive copy

    ld A, (DE)      ;   7 Ts
    ld (HL), A      ;   7 Ts
    inc DE          ;   6 Ts
    inc H           ;   4 Ts
    ; ... and so on for the next 7 lines.
    ; Cost per byte: 24 Ts

(2) Loading from the stack

    pop DE          ;  10 Ts
    ld (HL), D      ;   7 Ts
    inc H           ;   4 Ts
    ld (HL), E      ;   7 Ts
    inc H           ;   4 Ts
    ; ... and so on for the next 3 line pairs.
    ; Cost per byte: 16 Ts

(3) Self-modifying code

    ld (HL), line_1 ;  10 Ts
    inc H           ;   4 Ts
    ld (HL), line_2 ;  10 Ts
    inc H           ;   4 Ts
    ; and so on for the next 6 lines.
    ; Cost per byte: 14 Ts

(4) Copying from double buffer with some SMC

    ld SP, src_addr
    pop HL
    pop DE
    pop BC
    ; ... and so on for other register pairs.
    ld SP, disp_addr
    ; ...
    push BC
    push DE
    push HL
    ; and repeat until done.
    ; Cost per byte: 10.5 Ts

Comparing the Options

We can safely discard option (1) as the slowest and having no compensating merits.

Option (4) essentially assumes we have written to some backing buffer and are simply copying it to the display. A full screen takes 192 * 32 * 10.5 = 64,512 Ts, which, being approximately the same as the 224 * (64 + 192 + 64) = 71,680 Ts it takes for the hardware to display a full frame, leaves no time for drawing the backing buffer in the first place. In other words, option (4) is only acceptable if we are prepared to render every other frame or less. For this reason, I'm going to discard option (4) -- I want to see what we can manage in the opening 14,336 Ts of every frame.

Options (2) and (3) remain. In theory, we could manage 14,336 / (8 * 16) = 112 cells per frame with option (2) or 14,336 / (8 * 14) = 128 cells per frame with option (3).

These figures, of course, are without counting bookkeeping such as setting up DE/SP/HL or writing colour attributes. For example, for each cell we'd need something like the following to set up the registers and set the attribute byte:

    pop HL      ;  10 Ts -- load the attr addr.
    pop DE      ;  10 Ts -- load the attr byte and disp upper addr.
    ld (HL), D  ;   7 Ts -- write the attr byte.
    ld H, E     ;   4 Ts -- convert attr addr to disp addr.

Let's assume we need at least 40 Ts of overhead per cell or 40 / 8 = 5 Ts per byte. This gives 14,336 / (8 * 21) = 85 cells per frame for option (2) and 14,336 / (8 * 19) = 94 cells per frame for option (3).

How many sprites at full tilt?

Assuming a "standard" 16 x 16 pixel sprite, pre-shifted to any position, such a sprite will occupy a 3 * 3 cell region. Therefore, option (2) allows for 85 / 9 = 9.4 sprites per frame, while option (3) allows for 94 / 9 = 10.4 sprites per frame.

Memory budgets

The downside of option (3) is the amount of memory it requires. Each cell that we draw requires the following space for self-modifying code:

    ld HL, attr_addr    ; 3 bytes
    ld (HL), attr       ; 2 bytes
    ld H, disp_hi_addr  ; 2 bytes
    ld (HL), line_1     ; 2 bytes
    inc H               ; 1 byte
    ; ... last two lines repeated eight times in total.
    ; Total cost: 30 bytes.

Option (2) requires less space per cell, just the data for the drawing loop:

    dw attr_addr
    db attr, disp_hi_addr
    db line_1, line_2, ..., line_8
    ; Total cost: 12 bytes.

The winner is...

After trying both approaches, I found option (3) to be costly in memory and costly to set up each frame, leaving little time for game logic. For that reason, I claim option (2) is the optimal strategy provided we are aiming for full-screen full-speed flickerless animation without resorting to beam chasing tricks.

Digression: full cells or part cells

The discussion so far has assumed we are always drawing full cells. Consider a 16x16 sprite, this, when shifted into position, will occupy 3x16 bytes. However, it will (seven times out of eight) cross three cell rows. We can either optimise drawing of complete cells (3x24 bytes) or we can try to draw only what we need to (3x16 bytes). There are two problems with the latter approach. The first is what to do when sprites overlap (see below). With the prepare-first-then-draw-quickly strategy of option (2), we can handle the merging of overlapping images in the preparation period, which is outside the time-sensitive drawing period. With the just-draw-what-you-need-and-no-more strategy, it's not at all clear how you could manage this. You could restrict yourself to just xor-drawing and add the xor-code inline, but that costs you -- here's the code for doing that for one byte pair:

    ; Xor-drawing.
    pop DE      ;  10 Ts - Fetch two lines
    ld A, (HL)  ;   7 Ts
    xor D       ;   4 Ts
    ld (HL), A  ;   7 Ts
    inc H       ;   4 Ts
    ld A, (HL)  ;   7 Ts
    xor E       ;   4 Ts
    ld (HL), A  ;   7 Ts
    inc H       ;   4 Ts
    ; All repeated four times...
    ; Total cost: 27 Ts per byte

Add in the 5 Ts cost for attribute handling et cetera and we're up to 32 Ts per byte, limiting us to 14,336 / (8 * 32) = 56 cells. Not nearly so good compared to the 85 cells we can draw with option (2). Now, you might say, "but in this case we're only going to draw just what we need, so our 16x16 sprites only occupy 6 cells worth of space, giving us 56 / 6 = 9 sprites per frame". That is true, until you consider that each of those sprites will, seven times out of eight, cross two cell row boundaries. You now need to add logic to handle both "drawing from one to eight lines of a cell (top or bottom)" and "updating the display address for the top of the next cell row". Neither of those operations are cheap -- I've tried every trick I can think of -- resulting in a more complex, slower solution. That's why I've decided to stick to drawing complete cells: the overheads involved in drawing partial cells are simply too high to pay off.

Overlapping sprites

When cells from two sprites overlap, we need to decide how to handle the situation. The simplest approach of "one of them wins, the other is never seen" looks awful. Instead, we want to combine them somehow -- typically using or- or xor-merging or even using masking (and-mask then or-image) if we want to be really fancy. The key thing is, if we want to sustain nine sprites per frame, this "compositing" has to occur in the set-up period, not in the drawing period.

One way to do this is to maintain a map, much like the display attribute map, indicating which of the cells on screen is to be drawn in the next frame. Our "used cells" map will, instead, hold zero for unused cells, and positive number n if the nth "draw list" record holds the data (attribute pointer, attribute, display pointer high byte, and eight bitmap bytes) for that cell.

Used cell map:
+-------------------------------------+
|  |  |  |  |  |                      |
|--+--+--+--+--+--                    |
|  | 1| 4| 7|  |                      |
|--+--+--+--+--+--                    |
|  | 2| 5| 8|11|14                    |
|--+--+--+--+--+--                    |
|  | 3| 6| 9|12|15                    |
|--+--+--+--+--+--                    |
|  |  |  |10|13|16 etc.               | 
|                                     |
|                                     |
+-------------------------------------+

Draw list:
1 : attr ptr, attr, disp hi ptr, bits1 ... bits 8
2 : attr ptr, attr, disp hi ptr, bits1 ... bits 8
3 : attr ptr, attr, disp hi ptr, bits1 ... bits 8
4 : attr ptr, attr, disp hi ptr, bits1 ... bits 8
etc.

When we want to add a cell to our draw list, we first examine the corresponding entry in the used cells map. If this is a zero, then we need to set up a new draw list record for this cell and update the used cells map accordingly. If the used cells map contains a non-zero value, that tells us that the cell already has a draw list record and which record we must adjust in our compositing operation.

Erasing sprites

The Speccy allows for a neat, cost effective erasure trick provided you don't have to preserve any background. Simply set the attributes for any cell to be erased to have the same foreground and background colours! No bitmap data needs to be changed at all. This is a single byte write and vastly cheaper than redrawing using xor or any similar shenanigans.

Thankfully, our used cell map provides a convenient mechanism for working out which cells need to be erased from the previous frame (we don't want to blank any cells we are drawing to this frame, just the ones that were drawn to in the previous frame, but not this frame).

Basically, we need to track which cells were used in the previous frame. After drawing the current frame, we see which cells were used in the previous frame, but not in this frame (i.e., we check a list of cells from the previous frame against the cells used in this frame -- via the used cells map -- and write the blank attribute value to those cells).

Empirical testing

Using Simon Brattel's marvellous Zeus assembler/emulator/debugger/profiler I have collected some performance data. Running nine 16x16 pixel (i.e., 3x3 cell) sprites I observe the following T-states per frame:

  • 13,054 Ts spent drawing cells (tidily within our 14,336 T budget);
  • 8,087 Ts spent blanking cells (over our 14,336 T budget);
  • 36,587 Ts spent setting up cells;
  • 9,801 Ts spent managing sprites.
This is rather encouraging. I am somewhat surprised by the amount of time needed for blanking, but there's a fair amount of other bookkeeping going on in there and only a few cells typically need blanking per frame (sprites will typically move less than one cell width per frame). There is plenty of time left over for game logic, sound, and what-have-you.

Further thoughts

Given that so much remaining time is available per frame, it seems quite likely that a similar number of masked sprites could be supported at full frame rate. This would require adjustment to the "compositing" code and sprite layout, but nothing major. If there were a non-blank background to deal with, that would also complicate matters somewhat, but I can imagine at least a couple of plausible approaches.

All that said, I'm happy that my analysis played out in practice. I'm also happy that this is a shape-agnostic solution: any sprite sizes can be accommodated provided they fit within the approximately 100 cells per frame. That would be one huge 72x72 pixel sprite or four 32x32 pixel sprites or any other combination. All at 50Hz, in full colour, with compositing.

Friday, September 04, 2015

Simulating any biased coin with a fair coin

I recently discovered this cutie on the web.
  1. Using a fair coin, you can simulate a coin with any desired bias.
  2. The expected number of tosses you need to do this is just two!
Preliminaries: let's count heads as 1, tails as 0, and we'll write the desired probability of heads in our simulated biased coin as the binary fraction `p = 0.p_1p_2p_3...` where `p_i` is the `i`th binary digit of the probability `p`.

Procedure: keep tossing the fair coin until we get heads, on the `k`th toss.  Return `p_k` as the result and stop.

Proof this works: the probability of seeing a "head" (i.e., a 1) in this process is `P(head) = sum_(1<=k)p_k/2^k` which is exactly `p` by definition.

Expected number of tosses: the expected number of tosses is `E(k) = sum_(1<=k)k/2^k`.  Now, we can rewrite this two different ways.  One way, we can do a "change of variable" from `k` to `k+1`, giving `E(k) = sum_(0<=k)(k+1)/2^(k+1)`.  Let's call this form, `A`.  Another way, we can take the original equation and add a harmless zero term to the front of the sum, giving `E(k) = sum_(0<=k)k/2^k`.  Let's call this form, `B`.  Now, since `E(k) = A = B` we must have
`E(k) = 2A - B`
`qquad = 2sum_(0<=k)(k+1)/2^(k+1) - sum_(0<=k)k/2^k`
`qquad = sum_(0<=k)(k+1)/2^k - sum_(0<=k)k/2^k`
`qquad = sum_(0<=k)(k + 1 - k)/2^k`
`qquad = sum_(0<=k)1/2^k`
`qquad = 2`.

I find it delightful that the expected number of tosses is independent of the target probability!

Sunday, December 14, 2014

Rawb - efficient Knockout-friendly web controls

I've released Rawb (http://rawb.codeplex.com), a library of efficient web controls for use with Knockout (http://www.knockoutjs.com). The grid control is a particularly nice piece of work, in my opinion.

Spanner released

I thought I'd posted this months ago! Oh, well: Spanner is now available for download from http://spanner.codeplex.com . A tutorial site with documentation can be found at http://www.spannerjs.com . In case you have forgotten, Spanner is my attempt to provide an integrated scheme for writing web applications as embedded domain-specific languages in C#. It's rather nice, if I say so myself.

Monday, February 10, 2014

Ahh, JavaScript, how I loathe thee.

Okay, to be fair, this complaint isn't really about JavaScript so much as the JavaScript/DOM interface. Specifically, the ordering of event handlers.

Whenever one finds oneself struggling with interacting event handlers, the order of which is not consistent across browsers, one ends up doing something horrid like this:

    myEventHandler = function (evt) {
        setTimeout(function () {
            ... my intended side-effect ...
        },
        100 // Magic delay in milliseconds, 
            // which we pray will force the 
            // right order of events.
    };

Bleh. A thousand times, bleh. Please write in if you have a good solution to this problem.

Tuesday, October 29, 2013

How to find the parameter names of a C# lamba

Last night I tweaked Spanner so function parameter names in the generated JavaScript match the parameter names of the C# Func from which they were generated. I had a horrible feeling I'd have to stoop to using and parsing Expression values, but it turns out that isn't necessary at all. Behold, the answer: And...

Monday, October 14, 2013

Spanner is released!

I have, this day, made Spanner available on Codeplex. It's an alpha release, which means I intend to make minor changes to the design and major improvements to the documentation, add tutorials, and all that. The ToDoMVC example is temporarily broken. Fixing that is first on my (real) to-do list -- as my old PhD supervisor used to say to me, beware of showing an idiot something half finished.

Friday, September 20, 2013

A taste of Spanner

Spanner is the name of my soon-to-be-released open source statically typed domain specific language for building Knockout web applications in C#. Here is a very brief sample, which I will let stand by itself: Build and run this program and you get the following web page:
+ = which is .

Now, this is a fairly trivial example, but it illustrates some of the key points about Spanner.
  • A Spanner program is completely, strongly, statically typed -- it's just C#. As soon as you make a type error in your program, Visual Studio will list the problem areas in the error window. The generated JavaScript code cannot contain type errors (well, up to the point where you start including third-party JavaScript libraries). This alone makes Spanner valuable.
  • Strong typing means you get strong refactoring support from Visual Studio.
  • You don't need special syntax for expressions: you can freely use +, -, /, *, etc.
  • Because you are writing in C#, you have all the usual mechanisms for abstraction (i.e., functions!). You are not limited to the ad hoc hodge podge of compromises necessary in ordinary HTML + JavaScript development.
  • You don't need special syntax for Knockout observables -- Spanner knows which variables are observables and which are plain old JavaScript variables and generates the appropriate code for reading and writing them. Indeed, observables are much more transparent in Spanner than they are in JavaScript.
  • All the documented, well-typed parts of Knockout are supported.
  • Every HTML element and every well-typed JavaScript construct is represented by a correspondingly named Spanner function.
  • The correspondence between HTML attributes and view model variables is transparent -- you never need to embed code or identifiers in HTML strings. This is another key benefit of Spanner.
  • Spanner handles all the usual types (int, double, string, arrays, enums, POCOs). There are no special cases.
  • Spanner supports modularisation via view/view-models pairs, "global" models (i.e., libraries), strongly typed templates, and use of arbitrary third-party libraries.
  • Spanner will sort all your code dependencies for you and emit modules and variable definitions in the right order.
  • Spanner provides mechanism rather than policy. As long as you are happy using Knockout for your observables, it is entirely up to you how to structure your web application.
  • Spanner makes it easy to mix hand-written JavaScript with Spanner-generated JavaScript. The two worlds work quite comfortably together, provided the non-Spanner JavaScript has a well-typed API (hah!).
  • Building happens in the blink of an eye. If you are used to waiting ages for MVC to do its thing, Spanner's instant turn-around will be a relief.
  • Normal web development is excruciating for anyone used to more sophisticated languages. You spend so much of your working day chasing down trivial bugs and the primitive languages involved practically force you to turn your code into a mess of expedient short cuts. I wrote Spanner as a reaction, to see how far I could Do It Right while using a mainstream programming language (trust me, if we all migrated to F# or Haskell, Spanner would look a lot less cunning).
  • Using Spanner will clearly make you more attractive to members of your favourite sex.
Watch this space. I have the code completed, tested, and documented. I am just putting together a web site with a tutorial and some demonstrations (as my old PhD supervisor said to me, never show an idiot something half finished :-)). Being a family man with a full time job, this may take a week or three...