-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMachine.cpp
360 lines (337 loc) · 10.3 KB
/
Machine.cpp
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
#include <Arduino.h>
#include "PixelRing.h"
#include "Config.h"
#include "ReadWrite.h"
#include "BTN.h"
#include "Wheel.h"
#include "Tape.h"
#include "Machine.h"
Machine machine;
void Machine::Init()
{
Clear();
}
int Machine::Run()
{
// run the machine!
tape.Push();
Labels state = Labels::A;
int head = 0;
pixelRing.SetCursor(-1);
bool halt = false;
bool quit = false;
while (!halt && !quit)
{
tape.Show();
pixelRing.Update();
// read
Labels symbol = tape.Get(head);
Machine::Instruction instruction;
int prevHead = head;
Labels prevState = state;
GetInstruction(state, symbol, instruction);
// write
tape.Set(head, instruction._writeSymbol);
// move
head += instruction._moveHead;
if (head < 0)
head += PixelRing::Count;
if (head >= PixelRing::Count)
head -= PixelRing::Count;
// new state
state = instruction._newState;
if (state == Labels::Halt)
halt = true;
else if (config._AmimateState)
{
// show the (prev) state while waiting
pixelRing.SetPixel(prevHead, tape.SymbolColour(prevState));
pixelRing.Update();
}
int delayCtr = config._MachineStepDelayMS;
if (delayCtr == 0) delayCtr = 1;
// deal with the speed factor, delay between steps, check the wheel for speed changes and the button to stop
while (delayCtr--)
{
wheel.Update();
int rotation = wheel.GetRotation();
if (btn.CheckButtonPress())
{
// quit
quit = true;
break;
}
else if (rotation)
{
// change speed
config._MachineStepDelayMS -= rotation*Config::StepDelayIncrementMS;
if (config._MachineStepDelayMS < Config::MinStepDelayMS)
config._MachineStepDelayMS = Config::MinStepDelayMS;
if (config._MachineStepDelayMS > Config::MaxStepDelayMS)
config._MachineStepDelayMS = Config::MaxStepDelayMS;
config.Save();
break;
}
delay(1);
}
}
pixelRing.Flash();
pixelRing.Update();
return quit?0:head;
}
void Machine::Clear(Labels label)
{
if (IsAState(label, false))
{
// reset the entire state to "not-defined"
::memset(_machineTable + Index(label) - 1, 0, sizeof(PackedState));
}
else if (label == Labels::Machine)
{
// reset the entire machine to "not-defined"
::memset(_machineTable, 0, sizeof(_machineTable));
}
}
bool Machine::GetInstruction(Labels state, Labels symRead, Instruction& instruction, PackedState* pState)
{
// Read the Instruction to execute when in state having read symRead
// From pState is supplied, otherwise from _machineTable
// True if OK
if (IsAState(state, false) && // NOT Halt
IsASymbol(symRead))
{
if (!pState)
pState = _machineTable + (Index(state) - 1);
int symIdx = Index(symRead);
if (((pState->_instructionDirectionBits >> 2*symIdx) & 3UL) == 0)
{
// not-defined
// Be pedantic and init to Blank/None/Halt.
// Hitting an undefined state will Halt, but will change the tape first. Possibly annoying.
// The alternative would be to init to symRead/None/Halt. But I don't
instruction._writeSymbol = Labels::Blank;
instruction._moveHead = 0;
instruction._newState = Labels::Halt;
}
else
{
instruction._writeSymbol = Label(pState->_instructionWriteAndStates[symIdx] >> 4);
instruction._moveHead = ((pState->_instructionDirectionBits >> 2*symIdx) & 3UL) - 1;
if (instruction._moveHead == 2)
instruction._moveHead = -1;
instruction._newState = Label(pState->_instructionWriteAndStates[symIdx] & 0x0F);
}
return true;
}
return false;
}
bool Machine::PutInstruction(Labels state, Labels symRead, Instruction& instruction, PackedState* pState)
{
// Write the Instruction to execute when in state having read symRead
// To pState is supplied, otherwise to _machineTable
// True if OK
if (IsAState(state, false) && // NOT Halt
IsASymbol(symRead))
{
bool writeState = !pState;
if (writeState)
pState = _machineTable + (Index(state) - 1);
int symIdx = Index(symRead);
byte writeAndStates = Index(instruction._writeSymbol) << 4;
// 1/2/3 = N/R/L = 0/+1/-1
uint32_t bits = (instruction._moveHead == -1)?3UL:(uint32_t)(instruction._moveHead + 1);
pState->_instructionDirectionBits &= ~(3UL << 2*symIdx);
pState->_instructionDirectionBits |= (bits << 2*symIdx);
writeAndStates |= Index(instruction._newState);
pState->_instructionWriteAndStates[symIdx] = writeAndStates;
if (writeState)
_machineTable[Index(state) - 1] = *pState;
return true;
}
return false;
}
void Machine::DeSerialise(Reader& reader)
{
// read the machine and tape
Clear();
while (IsAState(StateLabel(reader.Read()), false))
DeSerialiseState(reader);
tape.DeSerialise(reader);
}
void Machine::Serialise(Writer& writer)
{
// serialize the machine (and tape)
for (int state = 0; state < NumberOfStates; state++)
{
bool empty = true;
bool first = true;
for (int symbol = 0; symbol <= Index(Labels::LastLetter); symbol++)
{
Labels sym = Label(symbol);
Instruction instruction;
if (GetInstruction(Label(state + 1), sym, instruction))
{
if (instruction._writeSymbol == Labels::Blank &&
instruction._moveHead == 0 &&
instruction._newState == Labels::Halt)
; // don't write default/not-defined instruction
else
{
if (empty)
{
writer.Write('A' + state);
writer.Write('=');
}
if (!first)
writer.Write(',');
first = empty = false;
writer.Write(tape.SymbolLetter(sym));
writer.Write(':');
writer.Write(tape.SymbolLetter(instruction._writeSymbol));
writer.Write(DirectionLetter(instruction._moveHead));
writer.Write(StateLetter(instruction._newState));
}
}
}
if (!empty)
writer.Write('\n');
}
tape.Serialise(writer);
}
bool Machine::DeSerialiseState(Reader& reader)
{
// "A=a:bLC,b:cLD...\n"
Labels state = Labels::Null;
if (DeSerialiseState(reader, state, false) && DeSerialiseDelimeter(reader, '='))
{
while (reader.Read() != '\n')
{
Instruction instr;
Labels readSymbol = Labels::Null;
if (DeSerialiseSymbol(reader, readSymbol) &&
DeSerialiseDelimeter(reader, ':') &&
DeSerialiseSymbol(reader, instr._writeSymbol) &&
DeSerialiseDirection(reader, instr._moveHead) &&
DeSerialiseState(reader, instr._newState, true) && // can Halt
DeSerialiseDelimeter(reader, ','))
{
PutInstruction(state, readSymbol, instr);
}
}
reader.Next();
return true;
}
return false;
}
byte* Machine::GetPackedData(int& bytes)
{
// return a pointer to, and the size of, the machine table
bytes = (int)sizeof(_machineTable);
return (byte*)(&_machineTable);
}
bool Machine::IsAState(Labels state, bool allowHalt)
{
// true if state is 'A'..<last state>. If allowHalt, true if state is Halt too
return (Labels::A <= state && state <= Labels::LastLetter) || (allowHalt && state == Labels::Halt);
}
bool Machine::IsASymbol(Labels sym)
{
// true is sym is 'a'..<last symbol> or blank
return (Labels::A <= sym && sym <= Labels::LastLetter) || sym == Labels::Blank;
}
Labels Machine::StateLabel(char ch)
{
// returns the Label corresponding to the char, 'X'->Halt, 'A'->A etc
// also allows '0'->Halt, '1'->A etc
if (ch == 'X' || ch == '0')
return Labels::Halt;
else if (StateLetter(Labels::A) <= ch && ch <= StateLetter(Labels::LastLetter))
return Label(ch - 'A' + 1);
else if ('1' <= ch && ch <= '9')
return Label(ch - '1' + 1);
else
return Labels::Null;
}
char Machine::StateLetter(Labels label)
{
// returns the char corresponding to the label, Halt->'X', A->'A' etc
if (label <= Labels::LastLetter && label != Labels::Halt)
return 'A' + Index(label) - 1;
else
return 'X';
}
char Machine::DirectionLetter(char dir)
{
// returns L/N/R for -1/0/+1, R means Clockwise
if (dir < 0)
return 'L';
else if (dir > 0)
return 'R';
else
return 'N';
}
bool Machine::DeSerialiseState(Reader& reader, Labels& state, bool allowHalt)
{
// convert an upper-case letter (or digit) to a state label
// if allowHalt, 'X' is Halt
if (reader.Read() == '\n') return false;
char ch = reader.Read();
state = StateLabel(ch);
if (IsAState(state, allowHalt))
{
reader.Next();
return true;
}
return false;
}
const char* pColourMap = "BlaRedGreBluYelAquFucWhiOraMalPur";
void Machine::CheckSymbolColour(char& ch, Reader& reader)
{
if ('A' <= ch && ch <= 'Z')
{
char colour[4];
colour[0] = ch;
reader.Next();
colour[1] = reader.Read();
reader.Next();
colour[2] = reader.Read();
colour[3] = 0;
const char* pMatch = strstr(pColourMap, colour);
if (pMatch)
ch = (pMatch == pColourMap)?'x':('a' + (pMatch - pColourMap)/3 - 1);
}
}
bool Machine::DeSerialiseSymbol(Reader& reader, Labels& symbol)
{
// convert a lower-case letter to a symbol label
// ' ', or '_' are the same as 'x' (blank)
// Also allows colour names, first three letters, first capital, see pColourMap
if (reader.Read() == '\n') return false;
char ch = reader.Read();
CheckSymbolColour(ch, reader);
reader.Next();
symbol = tape.SymbolLabel(ch);
return IsASymbol(symbol);
}
bool Machine::DeSerialiseDirection(Reader& reader, char& dirn)
{
// read a direction char
if (reader.Read() == '\n') return false;
char ch = reader.Read();
reader.Next();
dirn = 99;
if (ch == '<' || ch == '-' || ch == 'L')
dirn = -1;
else if (ch == '>' || ch == '+' || ch == 'R')
dirn = +1;
else if (ch == '=' || ch == '|' || ch == 'N')
dirn = 0;
return dirn != 99;
}
bool Machine::DeSerialiseDelimeter(Reader& reader, char ch)
{
// read optional delimeter
if (reader.Read() == ch)
reader.Next();
return true;
}