-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComputer.opal
379 lines (290 loc) · 10.6 KB
/
Computer.opal
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
package opal: import *;
package time: import sleep;
package sys: import argv, exit;
package math: import ceil;
package scipy: import signal;
package timeit: import default_timer;
package pygame: import Surface, transform, draw, mixer;
import numpy;
$args ["--static", "--disable-notes"]
new Vector RESOLUTION = Vector(256, 256);
new int BITS = 16,
RAM_ADDR_SIZE = 20,
SCREEN_MODE_BITS = 2,
FLAGS_QTY = 3,
INSTRUCTION_BITS = 8,
INTERRUPT_BITS = 4,
GPU_MODE_BITS = 3,
COLOR_BITS = 5,
GPU_MODIFIER_BITS = 1,
CHAR_BITS = 7,
CHAR_COLOR_BITS = 2,
CHAR_BG_COLOR_BITS = 1,
SOUND_FREQ_BITS = 13,
MAX_VOL_MULT = 500,
FREQUENCY_SAMPLE = 30000,
SAWTOOTH_WIDTH_BITS = 4,
SAWTOOTH_AMP_BITS = 4,
SQUARE_PWM_WIDTH_BITS = 4,
SQUARE_AMP_BITS = 4,
ND_SQUARE_AMP_BITS = 5,
SQUARE_DUTY_BITS = 6,
NOISE_AMP_BITS = 5,
SOUND_CHANNELS = 256,
MIXER_WORDS = 1;
new float CLOCK_PULSE_DURATION = 0,
SCREEN_SCALE = 1;
new bool HEX_DUMP = False,
STACK_PROTECTION = True,
NOP_ALERT = True,
UNKNOWN_OPCODE_ALERT = True,
HALT_ON_UNKNOWN = True,
UNHANDLED_INTERRUPT_ALERT = False,
ALWAYS_NOP_WAIT = False,
EXECUTION_TIME = False;
$macro clock
sleep(CLOCK_PULSE_DURATION);
$end
$include os.path.join(HOME_DIR, "compiler", "Compiler.opal")
$include os.path.join(HOME_DIR, "baseComponents", "baseComponents.opal")
$includeDirectory os.path.join(HOME_DIR, "components")
new function prettyPrintTime(n: float) str {
if n < 1 {
n *= 1000;
return str(round(n, 4)) + " ms";
}
return str(round(n, 4)) + " s";
}
new class Computer {
$include os.path.join(HOME_DIR, "microcode", "microcodeMethods.opal")
new method __init__() {
this.bus = BUS(max(BITS, RAM_ADDR_SIZE));
this.regX = Register(this, BITS);
this.regY = Register(this, BITS);
this.regZ = Register(this, BITS);
this.regA = Register(this, BITS);
this.regB = Register(this, BITS);
this.flags = Register(this, FLAGS_QTY, False);
this.alu = ALU(this);
this.mar = MemoryAddressRegister(this);
this.sp = StackPointer(this, RAM_ADDR_SIZE);
this.ram = RAM(this, 2 ** RAM_ADDR_SIZE);
this.display = AlphaNumericDisplay(this);
this.swap = Register(this, BITS, False);
IO.out("Initializing graphics...\n");
this.gpu = GPU(this, RESOLUTION);
this.screenSize = (RESOLUTION * SCREEN_SCALE).getIntCoords();
this.graphics = Graphics(this.screenSize, None, caption = "Emulated computer screen", frequencySample = FREQUENCY_SAMPLE);
this.graphics.drawLoop = this.__draw;
this.graphics.event(KEYDOWN)(this.__keydown);
this.graphics.event(QUIT)(this.__quit);
this.audioChs = this.graphics.getAudioChs()[2];
this.soundChip = SoundChip(this);
this.programCounter = Register(this, RAM_ADDR_SIZE, False);
this.instructionRegister = InstructionRegister(this);
this.interruptRegister = Register(this, INTERRUPT_BITS, False);
this.__onInterrupt = False;
this.interruptHandlers = {};
# data used for stack protection
this.stackBase = 0;
this.stackTop = 0;
this.stackError = False;
this.waiting = False;
this.waitAddress = None;
this.waitEnd = None;
this.time = None;
this.keyBufferAddr = 2 ** RAM_ADDR_SIZE - 1;
$include os.path.join(HOME_DIR, "microcode", "CPUMicrocode.opal")
}
new method generateInterrupt(code) {
this.interruptRegister.data = Compiler.fill(Compiler.decimalToBitarray(code), INTERRUPT_BITS);
}
new method __keydown(event) {
this.generateInterrupt(1);
this.ram.memory[this.keyBufferAddr].data = Compiler.fill(Compiler.decimalToBitarray(event.key));
}
new method __quit(event = None) {
IO.out("CPU Halted.\n");
if EXECUTION_TIME {
this.time = default_timer() - this.time;
IO.out("Execution time: ", prettyPrintTime(this.time), IO.endl);
}
exit(0);
}
new method __memSwap(fromReg, toAddr) {
fromReg.write();
this.swap.load();
$call clock
this.bus.load(Compiler.decimalToBitarray(toAddr));
this.mar.load();
$call clock
this.ram.write();
fromReg.load();
$call clock
this.swap.write();
this.ram.load();
}
new method getProgramCounter() {
if this.waiting {
return this.ram.memory[this.waitAddress];
} else {
return this.programCounter;
}
}
new method __handleInstruction() {
new int instruction = this.instructionRegister.instruction.toDec();
# 255 = HLT
if instruction == 255 or this.stackError {
this.__quit();
} elif instruction == 254 {
this.graphics.restore();
transform.scale(this.gpu.frameBuffer, (this.screenSize.x, this.screenSize.y), this.graphics.screen);
this.graphics.rawUpdate();
return;
} elif instruction == 253 {
this.graphics.loopOnly();
return;
} elif instruction >= len(this.__microcode) and UNKNOWN_OPCODE_ALERT {
new Register tmp = Register(None, RAM_ADDR_SIZE, False);
tmp.data = this.getProgramCounter().data.copy();
tmp.dec();
IO.out(
"WARNING: Unrecognized opcode (0x",
Compiler.bitArrayToHex(this.instructionRegister.instruction.data, ceil(INSTRUCTION_BITS / 4)),
") at address 0x", Compiler.bitArrayToHex(tmp.data, ceil(RAM_ADDR_SIZE / 4)), ".\n"
);
if HALT_ON_UNKNOWN {
this.__quit();
} else {
IO.out(" Skipping address.\n");
return;
}
}
$call clock
this.__microcode[instruction]();
if this.interruptRegister.data != [0 for _ in range(INTERRUPT_BITS)] and not this.__onInterrupt {
new int interrupt = this.interruptRegister.toDec();
if interrupt in this.interruptHandlers {
this.__ps(this.getProgramCounter())();
this.bus.load(this.interruptHandlers[interrupt]);
this.getProgramCounter().load();
this.__onInterrupt = True;
} else {
this.interruptRegister.reset();
if UNHANDLED_INTERRUPT_ALERT {
IO.out("WARNING: Unhandled interrupt received.\n");
}
}
}
}
new method __draw() {
# fetch
this.programCounter.write();
this.mar.load();
$call clock
# save instruction
this.ram.write();
this.instructionRegister.load();
# increment program counter
this.programCounter.inc();
this.__handleInstruction();
}
new method run() {
this.time = default_timer();
this.graphics.run(handleQuit = False, drawBackground = False, autoUpdate = False);
}
}
new function prettyPrintFreq(n: float) str {
if n >= 1000 {
n /= 1000;
if n >= 1000 {
n /= 1000;
return str(round(n, 4)) + " MHz";
}
return str(round(n, 4)) + " KHz";
}
return str(round(n, 4)) + " Hz";
}
new function getFloatArg(name, shName) {
if name in argv {
new int idx = argv.index(name);
argv.pop(idx);
new dynamic value = argv.pop(idx);
try {
value = float(value);
} catch ValueError {
IO.out(f"Invalid {shName} value given. Using default.\n");
} success {
return value;
}
}
}
main {
if "--hex-dump" in argv {
argv.remove("--hex-dump");
HEX_DUMP = True;
}
if "--time" in argv {
argv.remove("--time");
EXECUTION_TIME = True;
}
if "--resolution" in argv {
new int idx = argv.index("--resolution");
argv.pop(idx);
new list res = argv.pop(idx).lower().split("x");
if len(res) != 2 {
IO.out("Invalid resolution value given. Using default.\n");
} else {
new dynamic tmp = Vector().fromList(res);
try {
tmp = tmp.getIntCoords();
} catch ValueError {
IO.out("Invalid resolution value given. Using default.\n");
} success {
RESOLUTION = tmp;
}
}
}
new dynamic tmp = getFloatArg("--scale", "scale");
if tmp is not None {
SCREEN_SCALE = tmp;
}
tmp = getFloatArg("--clock", "clock");
if tmp is not None {
CLOCK_PULSE_DURATION = tmp;
}
tmp = getFloatArg("--mixer-words", "mixer word quantity");
if tmp is not None {
MIXER_WORDS = int(tmp);
}
new Computer computer = Computer();
new Compiler compiler = Compiler();
new dynamic txt;
with open(argv[1], "r") as txt {
computer.ram.init(compiler.compile(txt.read()));
}
computer.sp.data = compiler.decimalToBitarray(compiler.stackPos);
computer.interruptHandlers = compiler.interruptHandlers;
computer.keyBufferAddr = compiler.keyBufferAddr;
computer.waitAddress = compiler.waitAddress;
computer.waitEnd = compiler.waitEnd;
IO.out("Timing clock...\n");
new dynamic sTime = default_timer();
$call clock
sTime = default_timer() - sTime;
IO.out(f"CPU clock is running at ~{prettyPrintFreq(1 / sTime)}.\n");
if not compiler.hadError {
IO.out(
"Stack is located at address 0x", Compiler.bitArrayToHex(computer.sp.data, ceil(RAM_ADDR_SIZE / 4)),
" and has ", compiler.stackSize, f" words allocated ({compiler.stackSize * BITS / 8} bytes)\n"
);
if STACK_PROTECTION {
computer.stackBase = compiler.stackPos;
computer.stackTop = compiler.stackPos + compiler.stackSize;
IO.out("Stack protection is enabled.\n");
}
}
IO.out("Key buffer is located at address 0x", hex(computer.keyBufferAddr)[2:].zfill(ceil(RAM_ADDR_SIZE / 4)), ".\n\n");
mixer.set_num_channels(SOUND_CHANNELS);
computer.run();
}