This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathledctrl.js
1769 lines (1663 loc) · 66 KB
/
ledctrl.js
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
/**
* @fileoverview Simulates an LED controller
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2019 Jeff Parsons
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* PCjs is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* PCjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCjs. If not,
* see <http://www.gnu.org/licenses/gpl.html>.
*
* You are required to include the above copyright notice in every modified copy of this work
* and to display that copyright notice when the software starts running; see COPYRIGHT in
* <https://www.pcjs.org/modules/devices/machine.js>.
*
* Some PCjs files also attempt to load external resource files, such as character-image files,
* ROM files, and disk image files. Those external resource files are not considered part of PCjs
* for purposes of the GNU General Public License, and the author does not claim any copyright
* as to their contents.
*/
"use strict";
/**
* @typedef {Config} LCConfig
* @property {string} class
* @property {Object} [bindings]
* @property {number} [version]
* @property {Array.<string>} [overrides]
* @property {boolean} [wrap]
* @property {string} [font]
* @property {string} [rule]
* @property {string} [pattern]
* @property {Object} [patterns]
* @property {string} [message]
* @property {boolean} [toggleColor]
* @property {Object} [colors]
*/
/**
* LED Controller CPU
*
* @class {CPU}
* @unrestricted
* @property {boolean} fWrap
* @property {string} sFont
* @property {string} sRule
* @property {string} sPattern
* @property {string} sMessage
* @property {string} sMessageInit
* @property {boolean} fToggleColor
* @property {LED} leds
* @property {Object} colorPalette
* @property {string} colorDefault (obtained from the leds)
* @property {string} colorSelected (set by updateColorSelection())
* @property {Array.<string>} colors
*/
class CPU extends Device {
/**
* CPU(idMachine, idDevice, config)
*
* @this {CPU}
* @param {string} idMachine
* @param {string} idDevice
* @param {LCConfig} [config]
*/
constructor(idMachine, idDevice, config)
{
super(idMachine, idDevice, config);
/*
* These are grid "behavior" properties. If 'wrap' is true, then any off-grid neighbor cell
* locations are mapped to the opposite edge; otherwise, they are mapped to the LED "scratch" row.
*/
this.fWrap = this.getDefaultBoolean('wrap', false);
this.sFont = this.getDefaultString('font', "");
this.font = this.sFont && CPU.FONTS[this.sFont] || CPU.FONTS["Helvetica"];
this.sRule = this.getDefaultString('rule', "");
this.sPattern = this.getDefaultString('pattern', "");
this.setMessage(this.sMessageInit = this.getDefaultString('message', ""));
/*
* The 'toggleColor' property currently affects only grids that have a color palette: if true,
* then only an LED's color is toggled; otherwise, only its state (ie, ON or OFF) is toggled.
*/
this.fToggleColor = this.getDefaultBoolean('toggleColor', false);
/*
* Since all bindings should have been completed by super(), we can make a preliminary call
* to getCounts() to determine how many counts are stored per LED, to preallocate a count buffer.
*/
this.countBuffer = new Array(this.getCounts().length);
/*
* Get access to the LED device, so we can update its display.
*/
let leds = /** @type {LED} */ (this.findDeviceByClass(Machine.CLASS.LED));
if (leds) {
this.leds = leds;
/*
* If loadPattern() didn't load anything into the LED array, then call
* clearBuffer(true), which performs a combination of clearBuffer() and drawBuffer().
*/
if (!this.loadPattern()) leds.clearBuffer(true);
/*
* Get access to the Input device, so we can propagate its properties as needed.
*/
this.input = /** @type {Input} */ (this.findDeviceByClass(Machine.CLASS.INPUT));
let configInput = {
"class": "Input",
"location": [0, 0, leds.widthView, leds.heightView, leds.colsView, leds.rowsView],
"drag": !!(this.input && this.input.fDrag),
"scroll": !!(this.input && this.input.fScroll),
"hexagonal": leds.fHexagonal,
"bindings": {"surface": leds.getBindingID(LED.BINDING.CONTAINER)}
};
let cpu = this;
this.ledInput = new Input(idMachine, idDevice + "Input", configInput);
this.ledInput.addInput(function onLEDInput(col, row) {
cpu.onInput(col, row);
});
this.colors = [];
this.colorDefault = leds.getDefaultColor();
this.updateColorSelection(this.colorDefault);
this.updateColorSwatches();
this.updateBackgroundImage(this.config[CPU.BINDING.IMAGE_SELECTION]);
/*
* Get access to the Time device, so we can give it our clockLEDs() function.
*/
this.time = /** @type {Time} */ (this.findDeviceByClass(Machine.CLASS.TIME));
this.time.addClock(this.clockLEDs.bind(this));
this.time.addUpdate(this.updateLEDs.bind(this));
/*
* This is not a conventional CPU with a conventional program counter, but the Device class
* has evolved to expect these things....
*/
this.regPC = this.regPCLast = 0;
/*
* Establish an onCommand() handler.
*/
this.addHandler(WebIO.HANDLER.COMMAND, this.onCommand.bind(this));
}
}
/**
* addBinding(binding, element)
*
* @this {CPU}
* @param {string} binding
* @param {Element} element
*/
addBinding(binding, element)
{
let cpu = this, elementInput, patterns;
switch(binding) {
case CPU.BINDING.COLOR_PALETTE:
case CPU.BINDING.COLOR_SELECTION:
element.onchange = function onSelectChange() {
cpu.updateColorPalette(binding);
};
this.updateColorPalette();
break;
case CPU.BINDING.IMAGE_SELECTION:
element.onchange = function onImageChange() {
cpu.updateBackgroundImage();
};
break;
case CPU.BINDING.PATTERN_SELECTION:
this.addBindingOptions(element, this.buildPatternOptions(this.config[CPU.BINDING.PATTERN_SELECTION]), false, this.config['pattern']);
element.onchange = function onPatternChange() {
cpu.updatePattern();
};
break;
case CPU.BINDING.SAVE:
element.onclick = function onClickSave() {
let sPattern = cpu.savePattern(true);
let elementSymbol = cpu.bindings[CPU.BINDING.SYMBOL_INPUT];
if (elementSymbol) {
sPattern = '"' + elementSymbol.value + '":"' + sPattern.replace(/^([0-9]+\/)*/, "") + '",';
}
cpu.println(sPattern);
};
break;
case CPU.BINDING.SAVE_TO_URL:
element.onclick = function onClickSaveToURL() {
let sPattern = cpu.savePattern();
cpu.println(sPattern);
let href = window.location.href;
if (href.indexOf('pattern=') >= 0) {
href = href.replace(/(pattern=)[^&]*/, "$1" + sPattern.replace(/\$/g, "$$$$"));
} else {
href += ((href.indexOf('?') < 0)? '?' : '&') + "pattern=" + sPattern;
}
window.location = href;
};
break;
case CPU.BINDING.SYMBOL_INPUT:
elementInput = /** @type {HTMLInputElement} */ (element);
elementInput.onkeypress = function onChangeSymbol(event) {
elementInput.value = String.fromCharCode(event.charCode);
let elementPreview = cpu.bindings[CPU.BINDING.SYMBOL_PREVIEW];
if (elementPreview) elementPreview.textContent = elementInput.value;
event.preventDefault();
};
break;
default:
if (binding.startsWith(CPU.BINDING.COLOR_SWATCH)) {
element.onclick = function onClickColorSwatch() {
cpu.updateColorSwatches(binding);
};
break;
}
/*
* This code allows you to bind a specific control (ie, a button) to a specific pattern;
* however, it's preferable to use the PATTERN_SELECTION binding above, and use a single list.
*/
patterns = this.config[CPU.BINDING.PATTERN_SELECTION];
if (patterns && patterns[binding]) {
element.onclick = function onClickPattern() {
cpu.loadPattern(binding);
};
}
}
super.addBinding(binding, element);
}
/**
* buildPatternOptions(patterns)
*
* @this {CPU}
* @param {Object} patterns
* @return {Object}
*/
buildPatternOptions(patterns)
{
let options = {};
for (let id in patterns) {
let name = id;
let lines = patterns[id];
for (let i = 0; i < lines.length; i++) {
if (lines[i].indexOf("#N") == 0) {
name = lines[i].substr(2).trim();
break;
}
}
options[name] = id;
}
return options;
}
/**
* clockLEDs(nCyclesTarget)
*
* @this {CPU}
* @param {number} nCyclesTarget (0 to single-step)
* @return {number} (number of cycles actually "clocked")
*/
clockLEDs(nCyclesTarget = 0)
{
let nCyclesClocked = 0;
if (nCyclesTarget >= 0) {
let nActive, nCycles = 1;
do {
switch(this.sRule) {
case CPU.RULES.ANIM4:
nActive = this.doCycling();
break;
case CPU.RULES.LEFT1:
nCycles = nCyclesTarget || nCycles;
nActive = this.doShifting(nCycles);
break;
case CPU.RULES.LIFE1:
nActive = this.doCounting();
break;
}
if (!nCyclesTarget) this.println("active cells: " + nActive);
nCyclesClocked += nCycles;
} while (nCyclesClocked < nCyclesTarget);
}
return nCyclesClocked;
}
/**
* doCounting()
*
* Implements rule LIFE1 (straight-forward implementation of Conway's Game of Life rule "B3/S23").
*
* This iterates row-by-row and column-by-column. It takes advantage of the one-dimensional LED
* buffer layout to move through the entire grid with a "master" cell index (iCell) and corresponding
* indexes for all 8 "neighboring" cells (iNO, iNE, iEA, iSE, iSO, iSW, iWE, and iNW), incrementing
* them all in unison.
*
* The row and col variables are used only to detect when we are at the "edges" of the grid, and whether
* (depending on the wrap setting) any north, east, south, or west indexes that are now "off the grid"
* should be adjusted to the other side of the grid (or set to the dead "scratch" row at the end of the
* grid if wrap is disabled). Similarly, when we leave an "edge", those same indexes must be restored
* to their normal positions, relative to the "master" index (iCell).
*
* The inline tests for whether iCell is at an edge are unavoidable, unless we break the logic up into
* 5 discrete steps: one for the rectangle just inside the edges, and then four for each of the north,
* east, south, and west edge strips. But unless we really need that (presumably tiny) speed boost,
* I'm inclined to keep the logic simple.
*
* The logic is still a bit cluttered by the all the edge detection checks (and the wrap checks within
* each edge case), and perhaps I should have written two versions of this function (with and without wrap),
* but again, that would produce more repetition of the rest of the game logic, so I'm still inclined to
* leave it as-is.
*
* @this {CPU}
* @return {number}
*/
doCounting()
{
let cActive = 0;
let leds = this.leds;
let buffer = leds.getBuffer();
let bufferClone = leds.getBufferClone();
let nCols = leds.colsView;
let nRows = leds.rows;
/*
* The number of LED buffer elements per cell is an LED implementation detail that should not be
* assumed, so we obtain it from the LED object, and use it to calculate the per-cell increment,
* per-row increment, and per-grid increment; the latter gives us the offset of the LED buffer's
* scratch row, which we rely upon when wrap is turned off.
*
* NOTE: Since we're only processing colsView, not cols, we must include nBufferIncExtra in nIncPerRow.
*/
let nInc = leds.nBufferInc;
let nIncPerRow = nCols * nInc + leds.nBufferIncExtra;
let nIncPerGrid = nRows * nIncPerRow;
let iCell = 0;
let iCellDummy = nIncPerGrid;
let iNO = iCell - nIncPerRow;
let iNW = iNO - nInc;
let iNE = iNO + nInc;
let iWE = iCell - nInc;
let iEA = iCell + nInc;
let iSO = iCell + nIncPerRow;
let iSW = iSO - nInc;
let iSE = iSO + nInc;
for (let row = 0; row < nRows; row++) {
if (!row) { // at top (north) edge; restore will be done after the col loop ends
if (!this.fWrap) {
iNO = iNW = iNE = iCellDummy;
} else {
iNO += nIncPerGrid; iNW += nIncPerGrid; iNE += nIncPerGrid;
}
} else if (row == nRows - 1) { // at bottom (south) edge
if (!this.fWrap) {
iSO = iSW = iSE = iCellDummy;
} else {
iSO -= nIncPerGrid; iSW -= nIncPerGrid; iSE -= nIncPerGrid;
}
}
for (let col = 0; col < nCols; col++) {
if (!col) { // at left (west) edge
if (!this.fWrap) {
iWE = iNW = iSW = iCellDummy;
} else {
iWE += nIncPerRow; iNW += nIncPerRow; iSW += nIncPerRow;
}
} else if (col == 1) { // just finished left edge, restore west indexes
if (!this.fWrap) {
iWE = iCell - nInc; iNW = iNO - nInc; iSW = iSO - nInc;
} else {
iWE -= nIncPerRow; iNW -= nIncPerRow; iSW -= nIncPerRow;
}
} else if (col == nCols - 1) { // at right (east) edge; restore will be done after the col loop ends
if (!this.fWrap) {
iEA = iNE = iSE = iCellDummy;
} else {
iEA -= nIncPerRow; iNE -= nIncPerRow; iSE -= nIncPerRow;
}
}
let state = buffer[iCell];
let nNeighbors = buffer[iNW]+buffer[iNO]+buffer[iNE]+buffer[iEA]+buffer[iSE]+buffer[iSO]+buffer[iSW]+buffer[iWE];
this.assert(!isNaN(nNeighbors));
if (nNeighbors == 3) {
state = LED.STATE.ON;
} else if (nNeighbors != 2) {
state = LED.STATE.OFF;
}
bufferClone[iCell] = state;
bufferClone[iCell+1] = buffer[iCell+1];
bufferClone[iCell+2] = buffer[iCell+2];
bufferClone[iCell+3] = buffer[iCell+3] | ((buffer[iCell] !== state)? LED.FLAGS.MODIFIED : 0);
iCell += nInc; iNW += nInc; iNO += nInc; iNE += nInc; iEA += nInc; iSE += nInc; iSO += nInc; iSW += nInc; iWE += nInc;
if (state == LED.STATE.ON) cActive++;
}
if (!this.fWrap) {
if (!row) {
iNO = iCell - nIncPerRow; iNW = iNO - nInc; iNE = iNO + nInc;
}
iEA = iCell + nInc; iNE = iNO + nInc; iSE = iSO + nInc;
} else {
if (!row) {
iNO -= nIncPerGrid; iNW -= nIncPerGrid; iNE -= nIncPerGrid;
}
iEA += nIncPerRow; iNE += nIncPerRow; iSE += nIncPerRow;
}
}
this.assert(iCell == nIncPerGrid);
/*
* swapBuffers() takes care of setting the buffer-wide modified flags (leds.fBufferModified), so we don't have to.
*/
leds.swapBuffers();
return cActive;
}
/**
* doCycling()
*
* Implements rule ANIM4 (animation using 4-bit counters for state/color cycling).
*
* @this {CPU}
* @return {number}
*/
doCycling()
{
let cActive = 0;
let leds = this.leds;
let nCols = leds.colsView, nRows = leds.rows;
let counts = this.countBuffer;
for (let row = 0; row < nRows; row++) {
for (let col = 0; col < nCols; col++) {
if (!leds.getLEDCounts(col, row, counts)) continue;
cActive++;
/*
* Here's the layout of each cell's counts (which mirrors the CPU.COUNTS layout):
*
* [0] is the "working" count
* [1] is the ON count
* [2] is the OFF count
* [3] is the color-cycle count
*
* Whenever the working count is zero, we examine the cell's state and advance it to
* the next state: if it was ON, it goes to OFF (and the OFF count is loaded into
* the working count); if it was OFF, then color-cycle count (if any) is applied, and
* the state goes to ON (and the ON count is loaded).
*/
if (counts[0]) {
counts[0]--;
}
else {
let state = leds.getLEDState(col, row), stateNew = state || 0;
switch(state) {
case LED.STATE.ON:
stateNew = LED.STATE.OFF;
counts[0] = counts[2];
if (counts[0]) {
counts[0]--;
break;
}
/* falls through */
case LED.STATE.OFF:
if (counts[3]) {
let color = leds.getLEDColor(col, row);
let iColor = this.colors.indexOf(color);
if (iColor >= 0) {
iColor = (iColor + counts[3]);
while (iColor >= this.colors.length) iColor -= this.colors.length;
leds.setLEDColor(col, row, this.colors[iColor]);
}
}
stateNew = LED.STATE.ON;
counts[0] = counts[1];
if (counts[0]) {
counts[0]--;
}
break;
}
if (stateNew !== state) leds.setLEDState(col, row, stateNew);
}
leds.setLEDCounts(col, row, counts);
}
}
return cActive;
}
/**
* doShifting()
*
* Implements rule LEFT1 (shift left one cell).
*
* Some of the state we maintain outside of the LED array includes the number of columns of data remaining
* in the "offscreen" portion of the array (nMessageCount). Whenever we see that it's zero, we load it with the
* next chuck of data (ie, the LED pattern for the next symbol in sMessage).
*
* @this {CPU}
* @param {number} [shift] (default is 1, for a leftward shift of one cell)
* @return {number}
*/
doShifting(shift = 1)
{
let cActive = 0;
let leds = this.leds;
let nCols = leds.cols, nRows = leds.rows;
/*
* If nShiftedLeft is already set, we can't allow another shift until the display has been redrawn.
*/
if (leds.nShiftedLeft) {
return 0;
}
/*
* The way the code is currently written, shifting more than two cells at a time creates gap issues.
*/
this.assert(shift <= 2);
if (!this.processMessageCmd(shift)) {
return 0;
}
//
// This is a very slow and simple shift-and-exchange loop, which through a series of exchanges,
// also migrates the left-most column to the right-most column. Good for testing but not much else.
//
// for (let row = 0; row < nRows; row++) {
// for (let col = 0; col < nCols - 1; col++) {
// let stateLeft = leds.getLEDState(col, row) || LED.STATE.OFF;
// let stateRight = leds.getLEDState(col + 1, row) || LED.STATE.OFF;
// if (stateRight) cActive++;
// leds.setLEDState(col, row, stateRight);
// leds.setLEDState(col + 1, row, stateLeft);
// }
// }
// leds.nShiftedLeft = 1;
//
let buffer = leds.getBuffer();
let nInc = leds.nBufferInc * shift;
let nIncPerRow = leds.nBufferInc * nCols;
let col = 0, nEmptyCols = 0, iCell = 0;
this.nLeftEmpty = this.nRightEmpty = -1;
while (col < nCols - shift) {
let isEmptyCol = 1;
let iCellOrig = iCell;
for (let row = 0; row < nRows; row++) {
let stateOld = buffer[iCell];
let stateNew = (buffer[iCell] = buffer[iCell + nInc]);
let flagsNew = ((stateNew !== stateOld)? LED.FLAGS.MODIFIED : 0);
buffer[iCell + 1] = buffer[iCell + nInc + 1];
buffer[iCell + 2] = buffer[iCell + nInc + 2];
buffer[iCell + 3] = buffer[iCell + nInc + 3] | flagsNew;
if (stateNew) {
cActive++;
isEmptyCol = 0;
}
iCell += nIncPerRow;
}
iCell = iCellOrig + leds.nBufferInc;
if (col++ < leds.colsView) {
if (isEmptyCol) {
nEmptyCols++;
} else {
if (this.nLeftEmpty < 0) this.nLeftEmpty = nEmptyCols;
nEmptyCols = 0;
}
}
}
if (this.nLeftEmpty < 0) this.nLeftEmpty = nEmptyCols;
this.nRightEmpty = nEmptyCols;
while (col < nCols) {
let iCellOrig = iCell;
for (let row = 0; row < nRows; row++) {
leds.initCell(buffer, iCell);
iCell += nIncPerRow;
}
iCell = iCellOrig + leds.nBufferInc;
col++;
}
leds.fBufferModified = true;
leds.nShiftedLeft = shift;
return cActive;
}
/**
* getCount(binding)
*
* @this {CPU}
* @param {string} binding
* @return {number}
*/
getCount(binding)
{
let count = 0;
let element = this.bindings[binding];
if (element && element.options) {
let option = element.options[element.selectedIndex];
count = option && +option.value || 0;
}
return count;
}
/**
* getCounts()
*
* @this {CPU}
* @param {boolean} [fAdvance]
* @return {Array.<number>}
*/
getCounts(fAdvance)
{
let init = 0;
if (fAdvance) {
let element = this.bindings[CPU.BINDING.COUNT_INIT];
if (element && element.options) {
let option = element.options[element.selectedIndex];
if (option) {
init = +option.value || 0;
/*
* A more regular pattern results if we stick to a range of counts equal to the
* sum of the ON and OFF counts. Let's get that sum now. However, this assumes
* that the user is starting with an initial count of ZERO. Also, we're only going
* to do this if the sum of ON and OFF counts is EVEN; if it's odd, then we'll let
* the user do their thing.
*/
element.selectedIndex++;
let range = this.getCount(CPU.BINDING.COUNT_ON) + this.getCount(CPU.BINDING.COUNT_OFF);
let fReset = (!(range & 1) && init == range - 1);
if (fReset || element.selectedIndex < 0 || element.selectedIndex >= element.options.length) {
element.selectedIndex = 0;
}
}
}
}
let counts = [init];
for (let i = 1; i < CPU.COUNTS.length; i++) {
counts.push(this.getCount(CPU.COUNTS[i]));
}
return counts;
}
/**
* loadPattern(id)
*
* If no id is specified, load the initialization pattern, if any, set via the LCConfig
* "pattern" property (which, in turn, can be set as URL override, if desired).
*
* NOTE: Our initialization pattern is a extended single-string version of the RLE pattern
* file format: "col/row/width/height/tokens". The default rule is assumed.
*
* @this {CPU}
* @param {string} [id]
* @return {boolean}
*/
loadPattern(id)
{
let leds = this.leds;
let iCol = -1, iRow = -1, width, height, rule, sPattern = "";
if (!id) {
/*
* If no id is provided, then we fallback to sPattern, which can be either an
* id (if it doesn't start with a digit) or one of our own extended pattern strings.
*/
if (!this.sPattern.match(/^[0-9]/)) id = /** @type {string} */ (this.sPattern);
}
if (!id) {
if (!this.sPattern) {
return false;
}
let i = 0;
let aParts = this.sPattern.split('/');
if (aParts.length == 5) { // extended pattern string
iCol = +aParts[i++];
iRow = +aParts[i++];
}
if (aParts.length == 3 || aParts.length == 5) {
width = +aParts[i++]; // conventional pattern string
height = +aParts[i++];
sPattern = aParts[i];
}
else {
this.println("unrecognized pattern: " + this.sPattern);
return false;
}
rule = this.sRule; // TODO: If we ever support multiple rules, then allow rule overrides, too
}
else {
let patterns = this.config[CPU.BINDING.PATTERN_SELECTION];
let lines = patterns && patterns[id];
if (!lines) {
this.println("unknown pattern: " + id);
return false;
}
this.println("loading pattern '" + id + "'");
for (let i = 0, n = 0; i < lines.length; i++) {
let sLine = lines[i];
if (sLine[0] == '#') {
this.println(sLine);
continue;
}
if (!n++) {
let match = sLine.match(/x\s*=\s*([0-9]+)\s*,\s*y\s*=\s*([0-9]+)\s*(?:,\s*rule\s*=\s*(\S+)|)/i);
if (!match) {
this.println("unrecognized header line");
return false;
}
width = +match[1];
height = +match[2];
rule = match[3];
continue;
}
let end = sLine.indexOf('!');
if (end >= 0) {
sPattern += sLine.substr(0, end);
break;
}
sPattern += sLine;
}
}
if (rule != this.sRule) {
this.println("unsupported rule: " + rule);
return false;
}
if (iCol < 0) iCol = (leds.cols - width) >> 1;
if (iRow < 0) iRow = (leds.rows - height) >> 1;
if (iCol < 0 || iCol + width > leds.cols || iRow < 0 || iRow + height > leds.rows) {
this.printf("pattern too large (%d,%d)\n", width, height);
return false;
}
return this.loadPatternString(iCol, iRow, sPattern) > 0;
}
/**
* loadPatternString(col, row, sPattern, fOverwrite)
*
* @this {CPU}
* @param {number} col
* @param {number} row
* @param {string} sPattern
* @param {boolean} [fOverwrite]
* @return {number} (number of columns changed, 0 if none)
*/
loadPatternString(col, row, sPattern, fOverwrite = false)
{
let leds = this.leds;
let rgb = [0, 0, 0, 1], counts = 0;
let fColors = false, fCounts = false;
/*
* TODO: Cache these pattern splits.
*/
let aTokens = sPattern.split(/([a-z$])/i);
if (!fOverwrite) leds.clearBuffer();
/*
* We could add checks that verify that col and row stay within the bounds of the specified
* width and height of the pattern, but it's possible that there are some legit patterns out
* there that didn't get their bounds quite right. And in any case, no harm can come of it,
* because setLEDState() will ignore any parameters outside the LED's array bounds.
*/
let i = 0, iCol = col, colMax = 0;
while (i < aTokens.length - 1) {
let n = aTokens[i++];
let token = aTokens[i++];
let v = +n, nRepeat = (n === ""? 1 : v);
while (nRepeat--) {
let nAdvance = 0, fModified = false;
switch(token) {
case '$':
fColors = fCounts = false;
col = iCol;
row++;
break;
case 'C':
counts = v;
fCounts = true;
break;
case 'R':
rgb[0] = v;
fColors = true;
break;
case 'G':
rgb[1] = v;
fColors = true;
break;
case 'B':
rgb[2] = v;
fColors = true;
break;
case 'A':
rgb[3] = v;
fColors = true;
break;
case 'b':
fModified = leds.setLEDState(col, row, LED.STATE.OFF);
nAdvance++;
break;
case 'o':
fModified = leds.setLEDState(col, row, LED.STATE.ON);
nAdvance++;
break;
default:
this.printf("unrecognized pattern token: %s\n", token);
break;
}
if (fModified == null) {
this.printf("invalid pattern position (%d,%d)\n", col, row);
} else {
if (fColors) {
let color = leds.getRGBColorString(rgb);
leds.setLEDColor(col, row, color);
}
if (fCounts) {
leds.setLEDCountsPacked(col, row, counts);
}
if (colMax < col) colMax = col;
col += nAdvance;
}
}
}
if (!fOverwrite) leds.drawBuffer(true);
return ((colMax -= (iCol - 1)) < 0? 0 : colMax);
}
/**
* loadState(state)
*
* If any saved values don't match (possibly overridden), abandon the given state and return false.
*
* @this {CPU}
* @param {Array|Object} state
* @return {boolean}
*/
loadState(state)
{
let stateCPU = state['stateCPU'] || state[0];
if (!stateCPU || !stateCPU.length) {
this.println("Invalid saved state");
return false;
}
let version = stateCPU.shift();
if ((version|0) !== (+VERSION|0)) {
this.printf("Saved state version mismatch: %3.2f\n", version);
return false;
}
try {
this.sMessage = stateCPU.shift();
this.iMessageNext = stateCPU.shift();
this.sMessageCmd = stateCPU.shift();
this.nMessageCount = stateCPU.shift();
} catch(err) {
this.println("CPU state error: " + err.message);
return false;
}
if (!this.getURLParms()['message'] && !this.getURLParms()['pattern'] && !this.getURLParms()[CPU.BINDING.IMAGE_SELECTION]) {
let stateLEDs = state['stateLEDs'] || state[1];
if (stateLEDs && this.leds) {
if (!this.leds.loadState(stateLEDs)) return false;
}
}
return true;
}
/**
* onCommand(aTokens)
*
* Processes commands for our "mini-debugger".
*
* @this {CPU}
* @param {Array.<string>} aTokens
* @return {string|undefined}
*/
onCommand(aTokens)
{
let result = "";
let s = aTokens.shift();
let c = aTokens.shift();
switch(c[0]) {
case 's':
this.setMessage(aTokens.join(' '));
break;
case '?':
result = "";
CPU.COMMANDS.forEach((cmd) => {result += cmd + '\n';});
if (result) result = "additional commands:\n" + result;
break;
default:
if (s) result = "unrecognized command '" + s + "' (try '?')\n";
break;
}
return result;
}
/**
* onInput(col, row)
*
* @this {CPU}
* @param {number} col
* @param {number} row
*/
onInput(col, row)
{
let leds = this.leds;
if (col >= 0 && row >= 0) {
if (this.colorSelected) {
if (!leds.setLEDColor(col, row, this.colorSelected)) {
if (this.fToggleColor) {
leds.setLEDColor(col, row);
} else {
leds.setLEDState(col, row, LED.STATE.ON - leds.getLEDState(col, row));
}
} else {
leds.setLEDState(col, row, LED.STATE.ON);
}
}
else {
leds.setLEDState(col, row, LED.STATE.ON - leds.getLEDState(col, row));
}
let fAdvance = !!leds.getLEDState(col, row);
leds.setLEDCounts(col, row, this.getCounts(fAdvance));
leds.drawBuffer();
}
}
/**
* onLoad(state)
*
* Automatically called by the Machine device if the machine's 'autoSave' property is true.
*
* @this {CPU}
* @param {Array|Object} state
* @return {boolean}
*/
onLoad(state)
{
return state && this.loadState(state)? true : false;
}
/**
* onPower(on)
*
* Called by the Machine device to provide notification of a power event.
*
* @this {CPU}
* @param {boolean} on (true to power on, false to power off)
*/
onPower(on)
{
if (on) {
this.time.start();
} else {
this.time.stop();
}
}
/**
* onReset()
*
* Called by the Machine device to provide notification of a reset event.
*
* @this {CPU}
*/
onReset()
{
this.println("reset");
this.leds.clearBuffer(true);