-
Notifications
You must be signed in to change notification settings - Fork 0
/
sz80em.nw
4053 lines (3315 loc) · 131 KB
/
sz80em.nw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[10pt]{article}
\usepackage[margin=1.45in]{geometry}
\usepackage{graphicx}
\usepackage{noweb}
\usepackage{mflogo}
\usepackage{amsmath}
\usepackage{textcomp}
\noweboptions{smallcode,longchunks}
\usepackage{multirow}
\begin{document}
\pagestyle{myheadings}\markright{Simple Z80 Emulator\hfill \today\hfill}
\vskip 1in
\centerline{\bf Simple Z80 Emulator}
\centerline{Roman Valiu\v{s}enko}
\centerline{roman.valiusenko@gmail.com}
\begin{abstract}
This is a simple program that emulates Z80 microprocessor and hardware
interaction such as keyboard input and display output as in ZX Spectrum. The
program is written in {\tt F\#} programming language. The main objective was to
run ZX Spectrum operating system Sinclair BASIC. The undocumented instructions
and sound routines were not implemented.
\end{abstract}
\tableofcontents
\section{About ZX Spectrum}
Sinclair Research Ltd was a British electronics company founded by Sir Clive
Sinclair in Cambridge. The company was incorporated in 1973, and in 1980
presented a home computer ZX80, which cost \pounds99.95. Two years later, on 23
April 1982, the legendary ZX Spectrum was launched. It was priced at \pounds125
for the 16KB version, and \pounds175 for the 48KB version\cite{ZXS}. (Later
these prices were reduced to \pounds99 and \pounds129 respectively.)
ZX Spectrum was an 8-bit personal home computer that used Zilog Z80 CPU running
at 3.5MHZ. It ran Sinclair BASIC operating system, which was a dialect of the
BASIC programming language. The operating system was developed by Nine Tiles
Networks Ltd (by Steve Vickers\cite{ZXSB}).
\section{Program layout}
We will keep the structure of the program very simple. We will have only two
files of the program: One for the types that will be necessary to emulate ZX
Spectrum, and the other file that will act a launcher.
All types will be located in {\tt sz80em.fs} file. Everything is going to be
in [[FSpectrum]] namespace.
<<*>>=
<<sz80em.fs>>
<<sz80emr.fs>>
@
<<sz80em.fs>>=
namespace FSpectrum
<<References>>
<<Types>>
@
The program launcher is very simple:
<<sz80emr.fs>>=
namespace FSpectrum
open System
open System.Windows.Forms
module Spectrum =
[<EntryPoint>]
<<Application execution loop>>
@
We are going to need quite a few references, so let's define them straight
away:
<<References>>=
open System
open System.IO
open System.Drawing
open System.Drawing.Imaging
open Microsoft.FSharp.NativeInterop
open System.Windows.Forms
open System.Threading
@
[[IO]] is needed to read ZX Spectrum ROM image and load it into memory. Drawing
is required to emulate screen output. Forms are necessary for the GUI.
[[NativeInterop]] is required to do efficient screen drawing routines.
\section{Keyboard Input}
In ZX Spectrum there's only one I/O port, addressed by two bytes, which can be
read or written to. In this implementation we will only implement reading from
the port, so let's define an abstract port:
<<Types>>=
type IPort =
abstract read: uint16 -> byte
@
That is we can read from port addressed by two bytes, and get a byte as a
result. We will need this to implement keyboard routines.
When a program running on ZX Spectrum wants to read keyboard input, it reads
port [[0xFE]]. A zero in highest eight address lines selects a row of five keys
as defined in the table \ref{table:keyboard_map}\cite{48KREF}.
\begin{table}[h]
\centering
\begin{tabular}{ | l | l | l | l | l | l | l | l |}
\hline
Row & High Address Lines & Port & Bit 0 & Bit 1 & Bit 2 & Bit 3 & Bit 4 \\ \hline
0 & 0x11111110 & 0xFEFE & SHIFT & Z & X & C & V \\
1 & 0x11111101 & 0xFDFE & A & S & D & F & G \\
2 & 0x11111011 & 0xFBFE & Q & W & E & R & T \\
3 & 0x11110111 & 0xF7FE & 1 & 2 & 3 & 4 & 5 \\
4 & 0x11101111 & 0xEFFE & 0 & 9 & 8 & 7 & 6 \\
5 & 0x11011111 & 0xDFFE & P & O & I & U & Y \\
6 & 0x10111111 & 0xBFFE & ENTER & L & K & J & H \\
7 & 0x01111111 & 0x7FFE & SPACE & SYM SHIFT & M & N & B \\
\hline
\end{tabular}
\caption{Port addresses}
\label{table:keyboard_map}
\end{table}
The byte as result of port [[0xFE]] read will have zero in one of the five
lowest bits if a corresponding key is pressed.
We will implement a physical keyboard device as a class that reacts to keyboard
key presses of our GUI application and sets corresponding bits for each of
[[0xFEFE]]---[[0x7FFE]] ports of which we have 8 in total. Then, programs
running on our ZX Spectrum will be able to read ports [[0XFEFE]]---[[0x7FFE]]
and get these bytes as results. The result bytes will have bits set
appropriately depending on keys currently being pressed.
First, let's define an auxiliary type\footnote{In this document words "type" and
"class" are used interchangeably.} [[KeyCode]] as a record:
<<Types>>=
type KeyCode = { row: int; bit: uint8; }
@
Instances of this type will tell us which row this key correspond to (see Table
\ref{table:keyboard_map} on page \pageref{table:keyboard_map}), and also the
corresponding bit, set as a number, e.g. [0b00000001]. For example if we wanted
to define key [[A]] we would have \{ row = 1; bit = 0x01uy \}.
Before we do the mapping of the keys, let's define an interface of our keyboard
as something that has two methods, which are called when a key is pressed, and
when a key is released:
<<Types>>=
type public IKeyboard =
abstract KeyPressed: Keys -> unit
abstract KeyReleased: Keys -> unit
@
Keys is the type that defines the keyboard key in {\tt F\#}.
Our keyboard will react to messages, so let's define keyboard message as a
discriminated union:
<<Types>>=
type KeyboardMsg =
| KeyPressed of Keys
| KeyReleased of Keys
| ReadKeys of uint16 * AsyncReplyChannel<byte>
@
Now we are good to define the actual keyboard class, which implements both
[[IKeyboard]] and [[IPort]] interfaces:
<<Types>>=
type Keyboard() = class
let ports = Array.create 8 0xFFuy
let keyMap =
<<Key map initialization>>
let processor =
<<KeyboardMsg event processing logic>>
interface IKeyboard with
member x.KeyPressed e = processor.Post(KeyPressed(e))
member x.KeyReleased e = processor.Post(KeyReleased(e))
interface IPort with
member x.read port = processor.PostAndReply(
(fun reply -> ReadKeys(port, reply)),
timeout = 200)
end
@
The array [[ports]] will maintain results of corresponding eight keyboard
ports.
Using Table \ref{table:keyboard_map} on page \pageref{table:keyboard_map}, we
can now define key mappings as follows:
<<Key map initialization>>=
Map.empty.
Add(Keys.ShiftKey, [ { row = 0; bit = 0x01uy } ]).
Add(Keys.Z, [ { row = 0; bit = 0x02uy } ]).
Add(Keys.X, [ { row = 0; bit = 0x04uy } ]).
Add(Keys.C, [ { row = 0; bit = 0x08uy } ]).
Add(Keys.V, [ { row = 0; bit = 0x10uy } ]).
Add(Keys.A, [ { row = 1; bit = 0x01uy } ]).
Add(Keys.S, [ { row = 1; bit = 0x02uy } ]).
Add(Keys.D, [ { row = 1; bit = 0x04uy } ]).
Add(Keys.F, [ { row = 1; bit = 0x08uy } ]).
Add(Keys.G, [ { row = 1; bit = 0x10uy } ]).
Add(Keys.Q, [ { row = 2; bit = 0x01uy } ]).
Add(Keys.W, [ { row = 2; bit = 0x02uy } ]).
Add(Keys.E, [ { row = 2; bit = 0x04uy } ]).
Add(Keys.R, [ { row = 2; bit = 0x08uy } ]).
Add(Keys.T, [ { row = 2; bit = 0x10uy } ]).
Add(Keys.D1, [ { row = 3; bit = 0x01uy } ]).
Add(Keys.D2, [ { row = 3; bit = 0x02uy } ]).
Add(Keys.D3, [ { row = 3; bit = 0x04uy } ]).
Add(Keys.D4, [ { row = 3; bit = 0x08uy } ]).
Add(Keys.D5, [ { row = 3; bit = 0x10uy } ]).
Add(Keys.D0, [ { row = 4; bit = 0x01uy } ]).
Add(Keys.D9, [ { row = 4; bit = 0x02uy } ]).
Add(Keys.D8, [ { row = 4; bit = 0x04uy } ]).
Add(Keys.D7, [ { row = 4; bit = 0x08uy } ]).
Add(Keys.D6, [ { row = 4; bit = 0x10uy } ]).
Add(Keys.P, [ { row = 5; bit = 0x01uy } ]).
Add(Keys.O, [ { row = 5; bit = 0x02uy } ]).
Add(Keys.I, [ { row = 5; bit = 0x04uy } ]).
Add(Keys.U, [ { row = 5; bit = 0x08uy } ]).
Add(Keys.Y, [ { row = 5; bit = 0x10uy } ]).
Add(Keys.Enter, [ { row = 6; bit = 0x01uy} ]).
Add(Keys.L, [ { row = 6; bit = 0x02uy } ]).
Add(Keys.K, [ { row = 6; bit = 0x04uy } ]).
Add(Keys.J, [ { row = 6; bit = 0x08uy } ]).
Add(Keys.H, [ { row = 6; bit = 0x10uy } ]).
Add(Keys.Space, [ { row = 7; bit = 0x01uy } ]).
Add(Keys.ControlKey, [ { row = 7; bit = 0x02uy } ]).
Add(Keys.M, [ { row = 7; bit = 0x04uy } ]).
Add(Keys.N, [ { row = 7; bit = 0x08uy } ]).
Add(Keys.B, [ { row = 7; bit = 0x10uy } ]).
Add(Keys.Escape, [ { row = 0; bit = 0x01uy };
{ row = 7; bit = 0x01uy } ]).
Add(Keys.Back, [ { row = 0; bit = 0x01uy };
{ row = 4; bit = 0x01uy } ]).
Add(Keys.Capital, [ { row = 0; bit = 0x01uy };
{ row = 3; bit = 0x02uy } ]).
Add(Keys.Oemplus, [ { row = 7; bit = 0x02uy };
{ row = 6; bit = 0x02uy } ]) // ctrl + L
@
Note that [[keyMap]] is a map from [[Keys]] to an array of [[KeyCode]]. Some
keys, such as [[Escape]], [[Back]] etc. are represented as a combination of
[[KeyCode]] instances.
Now let's write keyboard processor logic. It's going to be a pretty
straightforward asynchronous events processor, a pattern matching on message:
<<KeyboardMsg event processing logic>>=
MailboxProcessor.Start(fun inbox ->
let rec nextMsg =
async {
let! msg = inbox.Receive()
match msg with
| KeyPressed key ->
<<Key pressed>>
| KeyReleased key ->
<<Key released>>
| ReadKeys (port, reply) ->
<<Read keys>>
}
nextMsg
)
@
When a key is pressed, we need to lookup our map for the key, get [[KeyCodes]],
and set corresponding bits in the bytes in the [[ports]] array:
<<Key pressed>>=
if keyMap.ContainsKey(key) then
for k in keyMap.Item(key) do
ports.[k.row] <- ports.[k.row] &&& (k.bit ^^^ 0xFFuy)
return! nextMsg
@
Similarly, when a key is released, we do the reverse:
<<Key released>>=
if keyMap.ContainsKey(key) then
for k in keyMap.Item(key) do
ports.[k.row] <- ports.[k.row] ||| k.bit
return! nextMsg
@
When reading keyboard ports we need to identify which rows are requested to be
read. To do that we shift the [[port]] value by eight bits to the right,
because higher eight bits actually identify rows to read, i.e. zero bit in one
of eight positions identifies a row (see the table above). Then we create a
sequence of shifts to the right by one bit, producing tuples which have index
as its first component, and shifted value as its second component. We take
eight of such tuples. Next, we iterate on each of those tuples and identify
which of those have 0 as their 0th bit in the second tuple's value. If it is 0,
we know that row [[i]] is requested. Finally, we take that row as [[ports.[i]]]
and [[AND]] all such rows. This is captured in the following code chunk:
<<Read keys>>=
let result =
(byte (port >>> 8))
|> Seq.unfold (fun i -> Some(i, i >>> 1))
|> Seq.take 8
|> Seq.mapi (fun i port -> if port &&& 0x01uy = 0uy then ports.[i] else 0uy)
|> Seq.filter(fun i -> i > 0uy)
|> Seq.fold (fun r v -> r &&& v) 0xFFuy
reply.Reply(result)
return! nextMsg
@
Forward pipe operator [[|>]] is used to chain operations on sequences above.
Its definition is very simple:
{\tt let (|>) x f = f x},
and its type is
{\tt val (|>) : 'T -> ('T -> 'U) -> 'U}.
\section{Display Output}
\label{sec:display}
The Spectrum has the memory size of [[0xFFFF]] bytes. 16K ROM in the lowest
part of the address space, and 48K of RAM which occupies the rest of the
address space.
The screen memory map starts at [[0x4000]] and is of 6144 bytes long. 768 bytes
that follow right after that, i.e. starting at address [[0x6500]], are colour
attributes.
The bitmap is made of 192 lines, each of 32 bytes length. Each byte represents
8 pixels, so 32 bytes account for 256 pixels. Therefore, we have a resolution of
256 by 192 pixels.
The interesting thing is that how column and row are addressed. This is encoded
using the scheme shown in Table \ref{table:address_scheme}. (Also see
\cite{SRC} and \cite{ZXDESIGN}.)
\begin{table}
\centering
\begin{tabular}{ | c | c | c | c | c | c | c | c | c | c | c | c | c | c | c | c | }
\hline
15 & 14 & 13 & 12 & 11 & 10 & 9 & 8 & 7 & 6 & 5 & 4 & 3 & 2 & 1 & 0 \\ \hline
0 & 1 & 0 & $Y_7$ & $Y_6$ & $Y_2$ & $Y_1$ & $Y_0$ & $Y_5$ & $Y_4$ & $Y_3$ & $X_4$ & $X_3$ & $X_2$ & $X_1$ & $X_0$ \\
\hline
\end{tabular}
\caption{Row/Column Address Scheme}
\label{table:address_scheme}
\end{table}
Basically column and row cal be obtained like this:
\begin{verbatim}
row = ((address &&& 0b0001100000000000) >>> 8) ||| ((address &&& 0b11100000) >>> 5)
col = (address &&& 0b11111)
\end{verbatim}
Colour attribute byte is encoded as shown in Table
\ref{table:colour_attr_scheme}. (See \cite{ZXDESIGN}.)
\begin{table}[h]
\centering
\begin{tabular}{ | c | c | c | c | c | c | c | c | }
\hline
7 & 6 & 5 & 4 & 3 & 2 & 1 & 0 \\ \hline
F & B & $P_2$ & $P_1$ & $P_0$ & $I_2$ & $I_1$ & $I_0$ \\
\hline
\end{tabular}
\caption{Colour Attribute Scheme}
\label{table:colour_attr_scheme}
\end{table}
Here F is attribute Flash mode, which makes Paper and Ink colours to alternate
periodically). B sets Brightness mode (in original ZX Spectrum was generated
using the video display's maximum voltage levels for each RGB component).
$P_2$--$P_0$ is Paper colour, and $I_2$--$I_0$ is Ink colour. Paper colour is
background colour, so is used where corresponding pixel has 0 bit set, while
[Ink colour is used where the bit is set to 1.
Colours are as follows\cite{CLR}:
\begin{table}[h]
\centering
\begin{tabular}{ | l | l | l | l | l | }
\hline
Colour \# & Binary value & Bright 0 & Bright 1 & Colour Name \\ \hline
0 & 000 & \#{\tt 000000} & \#{\tt 000000} & Black \\ \hline
1 & 001 & \#{\tt 0000CD} & \#{\tt 0000FF} & Blue \\ \hline
2 & 010 & \#{\tt CD0000} & \#{\tt FF0000} & Red \\ \hline
3 & 011 & \#{\tt CD00CD} & \#{\tt FF00FF} & Magenta \\ \hline
4 & 100 & \#{\tt 00CD00} & \#{\tt 00FF00} & Green \\ \hline
5 & 101 & \#{\tt 00CDCD} & \#{\tt 00FFFF} & Cyan \\ \hline
6 & 110 & \#{\tt CDCD00} & \#{\tt FFFF00} & Yellow \\ \hline
7 & 111 & \#{\tt CDCDCD} & \#{\tt FFFFFF} & White \\ \hline
\end{tabular}
\caption{Colour Table}
\label{table:colour_table}
\end{table}
We have 8 base colours, each of which has an additional bright mode, making 15
colours in total (Black colour doesn't have bright mode.)
Each coulour attribute is applied to 8 by 8 pixels area, which we will
references as character area.
OK, before starting with display routines, let's write a helper
type to work with bitmaps more efficiently.
{\tt .NET} supports the LockBits method allowing us to manipulate a bitmap's
array of pixels in an efficient way.
The implementation of the helper type is very straightforward. The type takes a
bitmap as constructor's argument. Then we use [[LockBits]] method of the
[[bitmap]] to obtain [[BitmapData]]. We set [[ImageLockMode.WriteOnly]] and
[[PixelFormat]] from the [[bitmap]]. Then we define [[setPixel]] method that
takes as argument $x$ and $y$ coordinates and an RGB tuple defining the colour
we want to set at $(x, y)$. The method obtains an address by using
[[data.Scan0]] which returns the address of the first line and adding a shift
value, calculated by multiplying $y$ coordinate by the stride (got from
[[data.Stride]]), and adding $x * 3$ (three bytes account for RGB components).
Then, using [[NativePtr]] [[write]] and [[set]] methods we set corresponding
RGB components.
This is captured in the following code chunk:
<<Types>>=
type DirectBitmapAccess(bitmap: Bitmap) =
let data = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.WriteOnly,
bitmap.PixelFormat)
let setPixel x y (r,g,b) =
let address =
NativePtr.add<byte> (NativePtr.ofNativeInt data.Scan0)
((y * data.Stride) + (x * 3))
NativePtr.write address b
NativePtr.set address 1 g
NativePtr.set address 2 r
member this.SetPixel(x, y, color: Color) =
setPixel x y (color.R, color.G, color.B)
interface IDisposable with
member this.Dispose() =
bitmap.UnlockBits(data)
@
Now as we have a small helper class that allows us to work with bitmaps in an
efficient way, let's write the video processor type. This type will have three
methods: [[DrawImage]], [[GetImage]], and [[Flash]]. So let's define an
interface first:
<<Types>>=
type IVideoMemoryProcessor =
abstract ChangeFlash: unit
abstract DrawImage: byte[] -> unit
abstract GetImage: Image
@
And also let's define [[VideoMemoryProcessorMsg]] type as discriminated union:
<<Types>>=
type VideoMemoryProcessorMsg =
| DrawImage of byte[]
| GetImage of AsyncReplyChannel<Bitmap>
| Flash
@
This will be used to send messages to our video processor.
The video memory processor type goes next, which implements
[[IVideoMemoryProcessor]] interface:
<<Types>>=
type VideoMemoryProcessor() as this = class
<<VMP Constants>>
<<VMP Variables>>
let processor =
<<VideoMemoryProcessorMsg processor>>
let COLORS =
<<Colors table initialization>>
member private x.drawFrame(memory: byte[]) =
<<Frame rendering>>
interface IVideoMemoryProcessor with
member x.ChangeFlash = processor.Post(Flash)
member x.DrawImage bitmap = processor.Post(DrawImage bitmap)
member x.GetImage =
processor.PostAndReply(
(fun reply -> GetImage(reply)), timeout = 200) :> Image
end
@
First, according to Table \ref{table:colour_table} on page
\pageref{table:colour_table}, let's define colors map:
<<Colors table initialization>>=
Map.empty.
Add(0b0000, Color.FromArgb(0xFF, 0x00, 0x00, 0x00)).
Add(0b1110, Color.FromArgb(0xFF, 0xFF, 0xFF, 0x00)).
Add(0b0001, Color.FromArgb(0xFF, 0x00, 0x00, 0xC0)).
Add(0b1001, Color.FromArgb(0xFF, 0x00, 0x00, 0xFF)).
Add(0b0010, Color.FromArgb(0xFF, 0xC0, 0x00, 0x00)).
Add(0b1010, Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)).
Add(0b0011, Color.FromArgb(0xFF, 0xC0, 0x00, 0xC0)).
Add(0b1011, Color.FromArgb(0xFF, 0xFF, 0x00, 0xFF)).
Add(0b0100, Color.FromArgb(0xFF, 0x00, 0xC0, 0x00)).
Add(0b1000, Color.FromArgb(0xFF, 0x00, 0x00, 0x00)).
Add(0b0101, Color.FromArgb(0xFF, 0x00, 0xC0, 0xC0)).
Add(0b1101, Color.FromArgb(0xFF, 0x00, 0xFF, 0xFF)).
Add(0b0110, Color.FromArgb(0xFF, 0xC0, 0xC0, 0x00)).
Add(0b1100, Color.FromArgb(0xFF, 0x00, 0xFF, 0x00)).
Add(0b0111, Color.FromArgb(0xFF, 0xC0, 0xC0, 0xC0)).
Add(0b1111, Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF))
@
We need a few constants, so let's define them next. We define constants such as
height and width of the screen, character height (and width; they are the same,
as character area is a square) and screen memory size in bytes. All of them
will be useful when rendering video frame:
<<VMP Constants>>=
let WIDTH = 256;
let HEIGHT = 192;
let CHAR_WIDTH_HEIGHT = 8;
let WIDTH_IN_CHARS = WIDTH / CHAR_WIDTH_HEIGHT;
let HEIGHT_IN_CHARS = HEIGHT / CHAR_WIDTH_HEIGHT;
let SCREEN_MEMORY_SIZE = WIDTH * HEIGHT / CHAR_WIDTH_HEIGHT;
let CONTENDED_MEMORY_START = 0x4000
@
We will also need a couple of variables. One of those will be an array of two
bitmaps. We will alternate bitmaps in such a way that if [[GetImage]] message
comes through, we return a bitmap that is fully rendered, and we render another
frame into a different bitmap. Once another bitmap is fully rendered, the other
will be selected for rendering, and so on. It's a kind of double-buffer
technique.
So let's define an array of two bitmaps, each of [[WIDTH]] and [[HEIGHT]] size.
We will need a [[screen\_index]] variable to alternate bitmaps. We also need
another variable [[flash]], that will be used to implement Flash mode. We set
its value to [[0b01111111]], that is [[0x7F]]. Then, we alternate it between
[[0x7F]] and [[0xFF]] upon each [[Flash]] message.
<<VMP Variables>>=
let screens =
Array.init 2 (fun i -> new Bitmap(WIDTH, HEIGHT, PixelFormat.Format24bppRgb))
let mutable screen_index = 0
let mutable flash = 0x7Fuy;
@
So let's write a processor now. In here we implement the alternating bitmaps
and the Flash mode. The Flash mode simply changes the value of [[flash]]
variable from [[0x7F]] to [[0xFF]] and vice versa by toggling the 8th bit. The
[[flash]] value will be used when rendering the actual frame later.
<<VideoMemoryProcessorMsg processor>>=
MailboxProcessor.Start(fun inbox ->
let rec nextMsg =
async {
let! msg = inbox.Receive()
match msg with
| GetImage(reply) ->
reply.Reply(screens.[(screen_index + 1) % 2])
return! nextMsg
| DrawImage bitmap ->
this.drawFrame bitmap
screen_index <- (screen_index + 1) % 2
return! nextMsg
| Flash ->
flash <- if flash = 0x7Fuy then 0xFFuy else 0x7Fuy
return! nextMsg
}
nextMsg
)
@
Now we are ready to start implementing the rendering method. The method takes
as argument an array of bytes, which will be the whole ZX Spectrum memory. We
will read only portion of it, that is video memory plus colour attributes.
First, we will obtain the lock on the bitmap that is currently used to render
the frame. We use [[using]] construct here to release the lock once we exit the
scope:
<<Frame rendering>>=
using (new DirectBitmapAccess(screens.[screen_index])) (fun lockContext ->
<<Render the bitmap>>
)
@
To render the pixels we iterate on each vide memory byte, starting from address
[[0x4000]] and continuing for [[SCREEN_MEMORY_SIZE]]:
<<Render the bitmap>>=
for i in CONTENDED_MEMORY_START..(CONTENDED_MEMORY_START + SCREEN_MEMORY_SIZE - 1) do
<<Calculate row, col and line>>
<<Obtain ink and paper values for this row and col>>
<<Flash mode: Alternate ink and paper>>
<<Render pixels>>
@
Using the encoding scheme described earlier, we can obtain column and row, and
line values.
<<Calculate row, col and line>>=
let address = i - CONTENDED_MEMORY_START // 0x4000
let row = ((address &&& 0b0001100000000000) >>> 8) ||| ((address &&& 0b11100000) >>> 5)
let col = (address &&& 0b11111)
let line = ((address &&& 0b11100000000) >>> 8)
@
Colours attributes follow immediately after the video memory segment, so we get
the attribute we want by using value of [[col]] and [[row]] calculated earlier
in a straightforward way:
<<Obtain ink and paper values for this row and col>>=
let attribute = memory.[CONTENDED_MEMORY_START
+ SCREEN_MEMORY_SIZE + row * WIDTH_IN_CHARS + col] &&& flash
let mutable ink = int ((attribute &&& 0b111uy) ||| ((attribute &&& 0b1000000uy) >>> 3))
let mutable paper = int ((attribute &&& 0b1111000uy) >>> 3)
@
Note how we use [[flash]] variable to set the 8th bit of [[attribute]]. [[ink]]
and [[paper]] attributes are calculated using the scheme described earlier.
Now if the 8th bit of the attribute is non-zero, we swap [[ink]] and [[paper]]
values. This implements Flash mode.
<<Flash mode: Alternate ink and paper>>=
if (attribute &&& 0x80uy) <> 0uy then
let tmp = ink
ink <- paper
paper <- tmp
@
Finally, we are ready to start rendering the actual image. Each byte addressed
by [[address]] encodes 8 pixels. We initialize a [[mask]] variable and shift it
to the right by one, allowing us to inspect each of those 8 pixels in order. If
currently inspected bit is 1, we set [[ink]] colour, otherwise we set [[paper]]
colour. We shift [[mask]] by one to the right, and move on to next bit. This is
implemented in the following chunk:
<<Render pixels>>=
let mutable x = 0
let mutable mask = 0b10000000uy
while mask > 0uy do
let xx = (col * CHAR_WIDTH_HEIGHT + x);
let yy = row * CHAR_WIDTH_HEIGHT + line;
let clr = COLORS.[if (memory.[i] &&& mask) = 0uy then paper else ink]
lockContext.SetPixel(xx, yy, clr)
mask <- mask >>> 1
x <- x + 1
@
This finishes the implementation of our [[VideoMemoryProcessor]] type.
And the last thing for the Video Output would be the GUI component that will be
displaying the image on our GUI form.
Let's define an interface first. It will have one method [[draw]] taking byte
array as argument. This array is the whole memory of our ZX Spectrum machine:
<<Types>>=
type IDisplay =
abstract draw: byte[] -> uint16 -> unit
@
We implement this interface as a class inheriting from [[Panel]]. We pass in
the implementation of [[IVideoMemoryProcessor]] to its constructor, because the
actual rendering is done by the [[VideoMemoryProcessor]], while this class only
displays what's been rendered. Note how we also issue [[ChangeFlash]] message
every 16th frame.
<<Types>>=
type Display(videoProcessor: IVideoMemoryProcessor) as this = class
inherit Panel(Dock = DockStyle.Fill)
do
this.DoubleBuffered <- true
this.Visible <- true
override x.OnPaint e =
e.Graphics.DrawImage(videoProcessor.GetImage, 0, 0)
interface IDisplay with
member x.draw (memory: byte[]) frame =
if frame % 16us = 0us then
videoProcessor.ChangeFlash
videoProcessor.DrawImage memory
x.Invalidate()
end
@
We are done with the Video Output.
\section{Microprocessor}
The Z80 microprocessor is an 8-bit microprocessor by Zilog. It was launched in
1976 and was used in many desktop computers and other systems, such as video
games, musical instruments etc\cite{Z80}.
\subsection{Registers set}
Z80 has 208 bits of read/write memory that are available via the registers.
There are eighteen 8-bit registers and four 16-bit registers. All registers are
implemented using static RAM. There are six general purpose registers ([[B]],
[[C]], [[D]], [[E]], [[H]], [[L]]) and an accumulator ([[A]]) and flags
register ([[F]]). All eight registers have alternate (shadow) register
counterparts, which are not directly accessible though. There are also 6
special purpose registers ([[I]], [[R]], [[IX]], [[IY]], [[SP]], [[PC]]).
\begin{description}
\item [AF] formed by two 8 bit registers: accumulator register [[A]] and flag
bits register [[F]].
\item [BC] formed by two 8 bit registers: [[B]] and [[C]].
\item [DE] formed by two 8 bit registers: [[D]] and [[E]].
\item [HL] formed by two 8 bit registers: [[H]] and [[L]].
\item [SP] 16-bit stack pointer.
\item [PC] 16-bit program counter.
\item [IX] 16-bit index register.
\item [IY] 16-bit index register.
\item [I] 8-bit interrupt page address register.
\item [R] 8-bit refresh counter.
\item [AF'] shadow [[AF]] register.
\item [BC'] shadow [[BC]] register.
\item [DE'] shadow [[DE]] register.
\item [HL'] shadow [[HL]] register.
\end{description}
[[PC]] register points to the current instruction being fetched from memory.
[[PC]] is automatically incremented after its contents are transferred to the
address lines.
[[SP]] register points to the location in memory, which indicates top of a
stack. The stack can be located anywhere in external system RAM memory. Data
can be pushed onto the stack from specific registers or popped off of the stack
to specific registers.
[[IX]] and [[IY]] registers hold 16-bit base addresses that are used in indexed
addressing modes, and additional byte is included in indexed instructions to
specify a displacement (as a two's compliment signed integer) from the base.
The Z80 CPU can be operated in a mode in which an indirect call to any memory
location can be achieved in response to an interrupt. The [[I]] register is
used for this purpose and stores the high-order eight bits of the indirect
address while the interrupting device provides the lower eight bits of the
address. This feature allows interrupt routines to be dynamically located
anywhere in memory with minimal access time to the routine\cite{Z80UM}.
The Z80 CPU contains a memory refresh counter, enabling dynamic memories to be
used with the same ease as static memories. Seven bits of this 8-bit register
are automatically incremented after each instruction fetch. The eighth bit
remains as programmed, resulting from an [[LD R, A]] instruction. The data in
the refresh counter is sent out on the lower portion of the address bus along
with a refresh control signal while the CPU is decoding and executing the
fetched instruction. This mode of refresh is transparent to the programmer and
does not slow the CPU operation. The programmer can load the [[R]] register for
testing purposes, but this register is normally not used by the programmer.
During refresh, the contents of the I Register are placed on the upper eight
bits of the address bus\cite{Z80UM}.
The flag bits register [[F]] has the following fields:
\begin{table}[h]
\centering
\begin{tabular}{ | c | c | c | c | c | c | c | c | }
\hline
7 & 6 & 5 & 4 & 3 & 2 & 1 & 0 \\ \hline
S & Z & - & H & - & P & N & C \\
\hline
\end{tabular}
\caption{Flags register}
\label{table:flags}
\end{table}
\begin{description}
\item [S] Sign flag.
\item [Z] Zero flag.
\item [H] Half-carry flag.
\item [P] Parity/overflow flag.
\item [N] Add/Subtract flag.
\item [C] Carry flag.
\end{description}
\subsection{The Main Class}
We are going to define [[Z80]] class, which will take [[IPort]] as constructor
parameter (which is going to be our Keyboard).
We will define an exception that will be thrown when an
instruction\footnote{Words "instruction" and "operation" are used
interchengeably throughout this program.} is not supported.
<<Types>>=
exception InstructionNotSupported of string
@
<<Types>>=
type Z80(keyboard: IPort) as this = class
<<Registers>>
<<Registers set>>
<<Index registers>>
<<Flags>>
<<Registers 16-bit>>
<<Register arrays>>
<<Memory>>
<<Precomputed flags>>
<<Overflow/Half-carry tables>>
<<Video related contants>>
<<Mutables>>
<<Constants>>
<<Instruction tables>>
<<Type initialization>>
<<Getters/Setters>>
<<Members>>
end
@
We will keep all register in an array of 16 bytes, initialized with all the
items to 0:
<<Register arrays>>=
let register = Array.create 16 0uy
@
Then, we define constants to address registers in the array (e.g.
[[register.[A]]]). Register names that have suffixes [[S]] are the shadow
registers.
<<Registers>>=
let A = 0
let F = 1
let B = 2
let C = 3
let D = 4
let E = 5
let H = 6
let L = 7
let AS = 8
let FS = 9
let BS = 10
let CS = 11
let DS = 12
let ES = 13
let HS = 14
let LS = 15
@
We will also need an array of 2 16-bit registers, namely [[IX]] and [[IY]], so
let's define those:
<<Register arrays>>=
let index_register = Array.create 2 0us
@
And also we define constants to address them:
<<Index registers>>=
let IX = 0
let IY = 1
@
Next create a set of constants that will allow us to read/set bits in our flags
register [[F]]. Those are pretty straightforward:
<<Flags>>=
let S_FLAG = 0b10000000uy
let Z_FLAG = 0b01000000uy
let X5_FLAG = 0b00100000uy
let H_FLAG = 0b00010000uy
let X3_FLAG = 0b00001000uy
let P_FLAG = 0b00000100uy
let V_FLAG = 0b00000100uy
let N_FLAG = 0b00000010uy
let C_FLAG = 0b00000001uy
let X53_FLAGS = X5_FLAG ||| X3_FLAG
let SZ_FLAGS = S_FLAG ||| Z_FLAG
let SZP_FLAGS = SZ_FLAGS ||| P_FLAG
let SZHN_FLAGS = SZ_FLAGS ||| H_FLAG ||| N_FLAG
@
Note that [[X5_FLAG]] and [[X3_FLAG]] are not officially documented, still Z80
sets them.
We also have a few 16-bit registers along with [[IX]] and [[IY]], namely [[SP]]
and [[PC]], and let's put [[IR]] here too (even though it is formed using two
8-bit registers [[I]] and [[R]]):
<<Registers 16-bit>>=
let mutable ir = 0us
let mutable sp = 0us
let mutable pc = 0us
@
We will set various flags, like sign flag or zero flag, so let's precompute
these values:
<<Precomputed flags>>=
let precomputed_flags =
Array.create 256 0uy |> Array.mapi (
fun i v -> (if i > 0x7F then S_FLAG else 0uy) |||
((byte i) &&& X53_FLAGS) |||
(if i = 0 then Z_FLAG else 0uy))
@ %def precomputed_flags
Note that we also set flag 5 and 3 which are officially not documented,
although Z80 copies these bits from the operand value. We could have written
something like [[i &&& S_FLAG]] instead of explicit [[if]], but it seems to be
more readable.
The [[N]] is used by the [[DAA]] (Decimal Adjust Accumulator) instruction to
distinguish between the [[ADD]] and [[SUB]] instructions. For [[SUB]]
instructions, [[N]] is set to 1, otherwise it's zero. So let's create two sets
of precomputed flags, one for [[ADD]] operations, and the other for [[SUB]]
operations:
<<Precomputed flags>>=
let sz53n_add = precomputed_flags
let sz53n_sub = precomputed_flags |> Array.map (fun v -> v ||| N_FLAG)
@ %def sz53n_add sz53n_sub
Basically, that's the same expect [[N]] flag is set.
The flag [[P]], which is parity/overflow flag, has different uses depending on
operations. For arithmetic operations this flag is set if the result is
overflown. Such situation can be detected if both operands have the same sign
bits and the result has a different sign bit. The overflow doesn't occur if
operands have different sign bits.
However, when a logical operations or rotate instructions are executed, this
flag indicates parity of the result. That is, if the result parity is even, the
flag's set to 1. If the number of 1 bits in a byte is odd, the [[P]] flag is
unset, otherwise it is set.
So let's write a helper function that calculates that:
<<Precomputed flags>>=
let powers_of_two = 1 |> Seq.unfold (fun i -> Some(i, i <<< 1))
let parity v len = powers_of_two |>
Seq.take len |>
Seq.fold (fun e i -> if i &&& v <> 0 then not e else e) true
let parityByte v = parity v 8
@
Now let's have another two arrays with parity bits pre-calculated:
<<Precomputed flags>>=
let sz53pn_add = sz53n_add |> Array.mapi (fun i v -> v ||| (if parityByte i then P_FLAG else 0uy))
let sz53pn_sub = sz53n_sub |> Array.mapi (fun i v -> v ||| (if parityByte i then P_FLAG else 0uy))