-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflint.lua
More file actions
1468 lines (1311 loc) · 58.3 KB
/
Copy pathflint.lua
File metadata and controls
1468 lines (1311 loc) · 58.3 KB
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
--[[ Flint Graphics Engine
Flint is a graphics engine for CC:Tweaked (ComputerCraft), written in Lua. The core idea: instead of CC's 16 hardwired colors you can draw with arbitrary 24-bit hex colors (0xff4444, 0x44aaff, etc.) — Flint handles mapping them to the 16 hardware palette slots automatically.
When more than 16 colors appear in a single frame, an agglomerative clustering algorithm kicks in and merges the most similar colors until 16 remain.
For rendering, Flint works on a virtual subpixel canvas that is twice as wide and three times as tall as the terminal. Every two columns and three rows of subpixels share one terminal cell, which is then rendered as a teletext mosaic character — giving significantly higher resolution than regular CC characters. A precomputed LUT covering all 6⁶ possible subpixel color patterns reduces mosaic rendering to three table lookups per cell per frame.
On top of that there is an optional CraftOS-PC pixel mode (setGraphicsMode): each Flint subpixel becomes a real 3×3 pixel block, bypassing the two-colors-per-cell limit entirely. Text stays visible because the original CC bitmap font is embedded directly in flint.lua and rasterized as pixels at runtime.
The layer system supports multiple stacked drawing surfaces with z-index ordering, per-layer dirty rect tracking, and a diff-based present() that only sends changed rows to the terminal via blit().
]]
local flint = {}
--- @diagnostic disable: undefined-global
--- A color value accepted by Flint. Either a single hex-digit CC palette slot
--- ("0".."f") or a 24-bit RGB integer (e.g. 0xff4444). Hex integers are
--- automatically quantized to the 16-slot hardware palette via clustering.
---@alias FlintColor string|integer
local defaultPalette = {
["0"] = 0xf0f0f0,
["1"] = 0xf2b233,
["2"] = 0xe57fd8,
["3"] = 0x99b2f2,
["4"] = 0xdede6c,
["5"] = 0x7ecc19,
["6"] = 0xe599b2,
["7"] = 0x4c4c4c,
["8"] = 0x999999,
["9"] = 0x4c99b2,
["a"] = 0xb266e5,
["b"] = 0x3366cc,
["c"] = 0x7f664c,
["d"] = 0x57a63e,
["e"] = 0xcc3333,
["f"] = 0x111111,
}
local function resolveColor(colorMapping, color, default)
if not color then return default end
local mapped = colorMapping[color]
if mapped then return mapped end
if type(color) == "string" and #color == 1 and color:match("[0-9a-f]") then
return color
end
return default
end
-- ============================================================================
-- 0. MODULE-LEVEL CONSTANTS
-- ============================================================================
local slotHex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }
local slotColor = {}
for i = 0, 15 do slotColor[i] = 2 ^ i end
local hexToIndex = {}
for i = 0, 15 do hexToIndex[slotHex[i + 1]] = i end
-- ============================================================================
-- 0b. CC BITMAP FONT (6x9 px per char, extracted from the original CC font
-- via craftos2). Used only by the CraftOS-PC graphics mode to rasterize
-- text as pixels. 18 hex chars per glyph: 9 rows, bit 5 (0x20) = leftmost.
-- ============================================================================
local fontHex = "0000000000000000001c2236222a221c00001c3e2a3e22361c000000143e3e3e1c080000"
.. "00081c3e1c08000000081c083e3e081c000000081c3e3e081c000000000c1e1e0c000000"
.. "3f3f332121333f3f00000000000000000000000000000000000000000e061a2424180000"
.. "1c2222221c081c0800000000000000000000001e121e1030300000001f111f1133330000"
.. "0020383e382000000000020e3e0e02000000081c3e08083e1c0800121212121200120000"
.. "1e2a2a1a0a0a0a00001e302c221a063c000000000000001e1e0000081c3e083e1c083e00"
.. "081c3e080808080000080808083e1c08000000080c3e0c080000000008183e1808000000"
.. "0000000020203e00000000123f12000000000008081c1c3e000000003e1c1c0808000000"
.. "0000000000000000000808080808000800000a0a1400000000000014143e143e14140000"
.. "081e201c023c0800002224040810122200000814081a2c241a0000040408000000000000"
.. "0608101010080600001804020202041800000000120c12000000000008083e0808000000"
.. "0000000000080808000000003e0000000000000000000008080000020404081010200000"
.. "1c22262a32221c00000818080808083e00001c22020c10223e00001c22020c02221c0000"
.. "060a12223e020200003e203c0202221c00000c10203c22221c00003e2202040808080000"
.. "1c22221c22221c00001c22221e0204180000000808000008080000000808000008080800"
.. "02040810080402000000003e00003e0000001008040204081000001c2202040800080000"
.. "1e212d2d2f201e00001c223e2222222200003c223c2222223c00001c22202020221c0000"
.. "3c22222222223c00003e20382020203e00003e20382020202000001e20262222221c0000"
.. "22223e2222222200001c08080808081c00000202020202221c0000222438242222220000"
.. "2020202020203e000022362a22222222000022322a2622222200001c22222222221c0000"
.. "3c223c2020202000001c22222222241a00003c223c2222222200001e201c0202221c0000"
.. "3e08080808080800002222222222221c0000222222221414080000222222222a36220000"
.. "2214081422222200002214080808080800003e02040810203e00001c10101010101c0000"
.. "2010100804040200001c04040404041c0000081422000000000000000000000000003e00"
.. "08080400000000000000001c021e221e000020202c3222223c000000001c2220221c0000"
.. "02021a2622221e000000001c223e201e000006081e08080808000000001e22221e023c00"
.. "20202c322222220000080008080808080000020002020222221c00101012141814120000"
.. "0808080808080400000000342a2a2222000000003c22222222000000001c2222221c0000"
.. "00002c32223c20200000001a26221e02020000002c32202020000000001e201c023c0000"
.. "08081c0808080400000000222222221e0000000022222214080000000022222a2a1e0000"
.. "00002214081422000000002222221e023c0000003e0408103e0000060808100808060000"
.. "080808080808080000180404020404180000192600000000000000122409122409122409"
.. "0000000000000000003838380000000000000707070000000000003f3f3f000000000000"
.. "0000003838380000003838383838380000000707073838380000003f3f3f383838000000"
.. "0000000707070000003838380707070000000707070707070000003f3f3f070707000000"
.. "0000003f3f3f0000003838383f3f3f0000000707073f3f3f0000003f3f3f3f3f3f000000"
.. "0000000000003838383838380000003838380707070000003838383f3f3f000000383838"
.. "0000003838383838383838383838383838380707073838383838383f3f3f383838383838"
.. "0000000707073838383838380707073838380707070707073838383f3f3f070707383838"
.. "0000003f3f3f3838383838383f3f3f3838380707073f3f3f3838383f3f3f3f3f3f383838"
.. "00000000000000000008000808080808000000081c2220221c08000c12103c10103e0000"
.. "00221c2222221c220022143e083e080800000808080008080800001e302c221a063c0000"
.. "140000000000000000001e252929251e000018041c241c0000000000000a1428140a0000"
.. "0000003e02020000000000003e0000000000001e2d2d2b211e00003e0000000000000000"
.. "1824241800000000000008083e0808003e00201030203000000000301030103000000000"
.. "1020000000000000000000222222223d20201e2a2a1a0a0a0a00000000000c0c00000000"
.. "000000000000040800103010103800000000001c2222221c000000000028140a14280000"
.. "2224040816162200002224040812142600003214340816162200000800081020221c0000"
.. "30001c223e2222000006001c223e222200001c221c223e2222000014281c223e22220000"
.. "14001c223e2222000008001c223e222200001e28283c28282e00001c222020221c040800"
.. "30003e203c203e000006003e203c203e00001c223e203c203e000014003e203c203e0000"
.. "18001c0808081c00000c001c0808081c000008141c0808081c000014001c0808081c0000"
.. "3c22223222223c00000a1422322a26220000301c222222221c0000061c222222221c0000"
.. "1c221c2222221c000014281c2222221c0000141c222222221c0000002214081422000000"
.. "1c22262a32221c00003000222222221c00000600222222221c00000814002222221c0000"
.. "1400222222221c00000600221408080800001c080c0a0c081c00003c222c2222222c2000"
.. "30001c021e221e000006001c021e221e00001c221c021e221e000014281c021e221e0000"
.. "14001c021e221e000008001c021e221e0000000016293e28170000001c2220221c040800"
.. "30001c223e201e000006001c223e201e00001c221c223e201e000014001c223e201e0000"
.. "1800080808080800000c0008080808080000081408080808080000140008080808080000"
.. "08041e2222221c000014283c22222222000030001c2222221c000006001c2222221c0000"
.. "1c221c2222221c000014281c2222221c000014001c2222221c00000008003e0008000000"
.. "00001c262a321c00003000222222221e00000600222222221e00000814002222221e0000"
.. "1400222222221e000006002222221e023c0018080c0a0c081c000014002222221e023c00"
local fontRows = {}
for c = 0, 255 do
local rows = {}
local base = c * 18
for r = 1, 9 do
rows[r] = tonumber(fontHex:sub(base + r * 2 - 1, base + r * 2), 16)
end
fontRows[c] = rows
end
-- ============================================================================
-- 1. Bitwise Mosaic Lookup Initialization (64 states)
-- ============================================================================
local mosaicLut = {}
local function initMosaicLut()
for id = 0, 63 do
local charNum = 128
if bit32.btest(id, 1) then charNum = charNum + 1 end
if bit32.btest(id, 2) then charNum = charNum + 2 end
if bit32.btest(id, 4) then charNum = charNum + 4 end
if bit32.btest(id, 8) then charNum = charNum + 8 end
if bit32.btest(id, 16) then charNum = charNum + 16 end
mosaicLut[id] = string.char(charNum)
end
end
initMosaicLut()
-- ============================================================================
-- 1b. TEXEL PATTERN LUT
-- All 6^6 subpixel color patterns are precompiled at load time. What matters
-- per texel is only the *equality structure* of the 6 colors (which positions
-- share a color), so every pattern is reduced to first-occurrence indices and
-- encoded into a compact id (encoding borrowed from PixelBox). At runtime the
-- whole "find the two dominant colors" pass collapses into 3 table lookups.
-- The LUT is generated with Flint's original tally algorithm, so the output
-- is bit-identical to the previous per-texel computation.
-- ============================================================================
local texelCharLut = {}
local texelFgPosLut = {}
local texelBgPosLut = {}
local function initTexelLut()
local lookup = {}
local vals = {}
for enc = 0, 46655 do -- 6^6 - 1
local d1 = enc % 6
local d2 = math.floor(enc / 6) % 6
local d3 = math.floor(enc / 36) % 6
local d4 = math.floor(enc / 216) % 6
local d5 = math.floor(enc / 1296) % 6
local d6 = math.floor(enc / 7776) % 6
lookup[d6] = 5
lookup[d5] = 4
lookup[d4] = 3
lookup[d3] = 2
lookup[d2] = 1
lookup[d1] = 0
local s2, s3, s4, s5, s6 = lookup[d2], lookup[d3], lookup[d4], lookup[d5], lookup[d6]
local id = s2 + s3 * 3 + s4 * 4 + s5 * 20 + s6 * 100
if not texelCharLut[id] then
vals[1], vals[2], vals[3] = 0, s2, s3
vals[4], vals[5], vals[6] = s4, s5, s6
local colorA, cntA, colorB, cntB
for t = 1, 6 do
local c = vals[t]
if c == colorA then
cntA = cntA + 1
elseif c == colorB then
cntB = cntB + 1
if cntB > cntA then
colorA, cntA, colorB, cntB = colorB, cntB, colorA, cntA
end
elseif not colorA then
colorA, cntA = c, 1
elseif not colorB then
colorB, cntB = c, 1
end
end
colorB = colorB or colorA
cntB = cntB or 0
local fbBit = (cntA <= cntB) and 0 or 1
local p1 = (0 == colorA) and 0 or ((0 == colorB) and 1 or fbBit)
local p2 = (s2 == colorA) and 0 or ((s2 == colorB) and 1 or fbBit)
local p3 = (s3 == colorA) and 0 or ((s3 == colorB) and 1 or fbBit)
local p4 = (s4 == colorA) and 0 or ((s4 == colorB) and 1 or fbBit)
local p5 = (s5 == colorA) and 0 or ((s5 == colorB) and 1 or fbBit)
local p6 = (s6 == colorA) and 0 or ((s6 == colorB) and 1 or fbBit)
local maskId = 0
if p1 ~= p6 then maskId = maskId + 1 end
if p2 ~= p6 then maskId = maskId + 2 end
if p3 ~= p6 then maskId = maskId + 4 end
if p4 ~= p6 then maskId = maskId + 8 end
if p5 ~= p6 then maskId = maskId + 16 end
local fgVal = (p6 == 0) and colorB or colorA
local bgVal = (p6 == 0) and colorA or colorB
texelCharLut[id] = mosaicLut[maskId]
texelFgPosLut[id] = fgVal + 1
texelBgPosLut[id] = bgVal + 1
end
end
end
initTexelLut()
-- ============================================================================
-- 2. THE FLAT COMPOSITE BUFFER (The Canvas)
-- ============================================================================
---@class Buffer
---@field width number Width of the buffer in terminal cells.
---@field height number Height of the buffer in terminal cells.
---@field totalSize number Cached total number of terminal cells (width * height) for efficient iteration.
---@field chars string[] Array of characters for each terminal cell.
---@field fgs FlintColor[] Array of foreground colors for each terminal cell.
---@field bgs FlintColor[] Array of background colors for each terminal cell.
local Buffer = {}
Buffer.__index = Buffer
---Creates a new Buffer instance with the specified width and height. The buffer is initialized with empty character and color data.
---@param width number Width of the buffer in terminal cells.
---@param height number Height of the buffer in terminal cells.
---@return Buffer The newly created Buffer instance.
function Buffer.new(width, height)
local self = setmetatable({}, Buffer)
self.width = width
self.height = height
self.totalSize = width * height
self.chars = {}
self.fgs = {}
self.bgs = {}
self:clear(" ", "0", "f")
return self
end
---Clears the entire buffer by filling it with the specified character and colors. This is a bulk operation that efficiently resets all cells in the buffer to a uniform state.
---@param char string? The character to fill the buffer with.
---@param fg FlintColor? The foreground color to fill the buffer with.
---@param bg FlintColor? The background color to fill the buffer with.
function Buffer:clear(char, fg, bg)
for i = 1, self.totalSize do
self.chars[i] = char
self.fgs[i] = fg
self.bgs[i] = bg
end
end
-- ============================================================================
-- 3. THE LAYER CLASS (Isolated Layer Object)
-- ============================================================================
---@class Layer
---@field engine Engine Reference to the parent engine, for accessing shared state and registering colors.
---@field zIndex number Determines the compositing order of layers; higher zIndex layers are drawn on top of lower ones.
---@field termWidth number Cached reference to engine.termWidth for efficient index calculations.
---@field termHeight number Cached reference to engine.termHeight for efficient index calculations.
---@field vWidth number Cached reference to engine.vWidth for efficient index calculations.
---@field vHeight number Cached reference to engine.vHeight for efficient index calculations.
---@field totalSize number Cached total number of terminal cells (termWidth * termHeight) for efficient iteration.
---@field chars string[] Array of characters for each terminal cell in this layer.
---@field fgs FlintColor[] Array of foreground colors for each terminal cell in this layer.
---@field bgs FlintColor[] Array of background colors for each terminal cell in this layer.
---@field subpixelFgs FlintColor[] Array of foreground colors for each subpixel in the virtual canvas.
---@field subpixelBgs FlintColor[] Array of background colors for each subpixel in the virtual canvas.
---@field subpixelBits number[] Array of bit flags indicating which subpixels are set in the virtual canvas.
local Layer = {}
Layer.__index = Layer
---Creates a new Layer instance with the specified zIndex. The layer is initialized with empty character and color data, and is marked as fully dirty for initial rendering.
---@param engine Engine Reference to the parent engine for accessing shared state and registering colors.
---@param zIndex number Optional zIndex for the layer; defaults to 0 if not provided.
function Layer.new(engine, zIndex)
local self = setmetatable({}, Layer)
self.engine = engine
self.zIndex = zIndex or 0
self.termWidth = engine.termWidth
self.termHeight = engine.termHeight
self.vWidth = engine.vWidth
self.vHeight = engine.vHeight
self.totalSize = self.termWidth * self.termHeight
self.chars = {}
self.fgs = {}
self.bgs = {}
self.subpixelFgs = {}
self.subpixelBgs = {}
self.subpixelBits = {}
self.usedColors = {}
self.subpixelsDirty = false
self.dirtyX1 = math.huge
self.dirtyY1 = math.huge
self.dirtyX2 = 0
self.dirtyY2 = 0
self.spExtX1 = math.huge
self.spExtY1 = math.huge
self.spExtX2 = 0
self.spExtY2 = 0
self:clear()
return self
end
---Registers a color with the engine if it hasn't already been registered by this layer. This ensures that the engine's palette is aware of all colors used by the layer, without redundant registrations.
---@param color FlintColor? The color to register.
function Layer:registerColor(color)
if not color then return end
if not self.usedColors[color] then
self.usedColors[color] = true
self.engine:registerColor(color)
end
end
---Marks a rectangular region of the layer as dirty, indicating that it needs to be re-rendered. The dirty region is expanded to include the specified rectangle, and will be used by the engine to optimize rendering by only redrawing the affected area.
---@param x1 number Left edge of the dirty region.
---@param y1 number Top edge of the dirty region.
---@param x2 number Right edge of the dirty region.
---@param y2 number Bottom edge of the dirty region.
function Layer:markDirty(x1, y1, x2, y2)
if x1 < self.dirtyX1 then self.dirtyX1 = x1 end
if y1 < self.dirtyY1 then self.dirtyY1 = y1 end
if x2 > self.dirtyX2 then self.dirtyX2 = x2 end
if y2 > self.dirtyY2 then self.dirtyY2 = y2 end
end
---Marks a rectangular region of the layer as dirty specifically for subpixel updates. This is used to track which areas of the layer have had their virtual canvas (subpixel) data modified, so that the engine can efficiently update only those areas when compositing subpixels into terminal cells.
---@param x1 number Left edge of the dirty region in terminal cells.
---@param y1 number Top edge of the dirty region in terminal cells.
---@param x2 number Right edge of the dirty region in terminal cells.
---@param y2 number Bottom edge of the dirty region in terminal cells.
function Layer:markSubpixelDirty(x1, y1, x2, y2)
self:markDirty(x1, y1, x2, y2)
if x1 < self.spExtX1 then self.spExtX1 = x1 end
if y1 < self.spExtY1 then self.spExtY1 = y1 end
if x2 > self.spExtX2 then self.spExtX2 = x2 end
if y2 > self.spExtY2 then self.spExtY2 = y2 end
end
---Clears the entire layer: resets all char, fg, bg, and subpixel data.
---Also resets usedColors, dirty rects, and subpixel extent.
---@param char string? Fill character. nil leaves cells without a char set.
---@param fg FlintColor? Foreground color applied to every cell.
---@param bg FlintColor? Background color applied to every cell.
function Layer:clear(char, fg, bg)
self.usedColors = {}
self:registerColor(fg)
self:registerColor(bg)
self:markDirty(1, 1, self.termWidth, self.termHeight)
for i = 1, self.totalSize do
self.chars[i] = char
self.fgs[i] = fg
self.bgs[i] = bg
end
local totalSubpixels = self.vWidth * self.vHeight
for i = 1, totalSubpixels do
self.subpixelFgs[i] = fg
self.subpixelBgs[i] = bg
self.subpixelBits[i] = 0
end
self.hasSubpixels = false
self.subpixelsDirty = false
self.spExtX1, self.spExtY1 = math.huge, math.huge
self.spExtX2, self.spExtY2 = 0, 0
end
---Clears only the subpixel (virtual canvas) data, leaving char/fg/bg intact.
---More efficient than clear() for layers that exclusively use subpixel drawing.
---@param fg FlintColor? Fill foreground for cleared subpixels.
---@param bg FlintColor? Fill background for cleared subpixels.
function Layer:clearVirtual(fg, bg)
self:registerColor(fg)
self:registerColor(bg)
self:markDirty(1, 1, self.termWidth, self.termHeight)
local totalSubpixels = self.vWidth * self.vHeight
for i = 1, totalSubpixels do
self.subpixelFgs[i] = fg
self.subpixelBgs[i] = bg
self.subpixelBits[i] = 0
end
self.hasSubpixels = false
self.subpixelsDirty = false
self.spExtX1, self.spExtY1 = math.huge, math.huge
self.spExtX2, self.spExtY2 = 0, 0
end
-- ============================================================================
-- 4. LAYER CHARACTER PRIMITIVES (Writing directly and live to the Layer Arrays)
-- ============================================================================
---Writes a single character at the given terminal-cell position.
---Silently ignored if the position is outside the engine clip region.
---@param x number Column in terminal cells (1-based).
---@param y number Row in terminal cells (1-based).
---@param char string Single character to write.
---@param fg FlintColor? Foreground color. nil leaves the existing fg.
---@param bg FlintColor? Background color. nil leaves the existing bg.
function Layer:drawChar(x, y, char, fg, bg)
local engine = self.engine
if x < engine.clipTx1 or x > engine.clipTx2 or y < engine.clipTy1 or y > engine.clipTy2 then return end
self:registerColor(fg)
self:registerColor(bg)
self:markDirty(x, y, x, y)
local idx = (y - 1) * self.termWidth + x
if char then self.chars[idx] = char end
if fg then self.fgs[idx] = fg end
if bg then self.bgs[idx] = bg end
end
---Writes a string of characters starting at (x, y) in terminal-cell coordinates.
---Characters clipped by the engine clip region are silently skipped.
---@param x number Starting column in terminal cells (1-based).
---@param y number Row in terminal cells (1-based).
---@param text string The string to write.
---@param fg FlintColor Foreground color for all characters.
---@param bg FlintColor? Background color for all characters.
function Layer:drawText(x, y, text, fg, bg)
local engine = self.engine
if y < engine.clipTy1 or y > engine.clipTy2 then return end
self:registerColor(fg)
self:registerColor(bg)
local lo = math.max(engine.clipTx1, x)
local hi = math.min(engine.clipTx2, x + #text - 1)
if lo <= hi then self:markDirty(lo, y, hi, y) end
local tw = self.termWidth
local rowStart = (y - 1) * tw
local cChars = self.chars
local cFgs = self.fgs
local cBgs = self.bgs
for i = 1, #text do
local cx = x + i - 1
if cx >= engine.clipTx1 and cx <= engine.clipTx2 then
local idx = rowStart + cx
local char = text:sub(i, i)
if char then cChars[idx] = char end
if fg then cFgs[idx] = fg end
if bg then cBgs[idx] = bg end
end
end
end
---Sets a single subpixel on the virtual canvas.
---The virtual canvas is vWidth × vHeight (termWidth×2 × termHeight×3 subpixels).
---In text mode two columns and three rows of subpixels share one terminal cell
---(teletext mosaic); in graphics mode each subpixel maps to a 3×3 real-pixel block.
---@param vx number Subpixel column (1-based, max sys.vWidth).
---@param vy number Subpixel row (1-based, max sys.vHeight).
---@param color FlintColor? Foreground color of the subpixel.
---@param bgColor FlintColor? Optional background color override for this subpixel slot.
function Layer:drawSubpixel(vx, vy, color, bgColor)
local engine = self.engine
if vx < engine.clipVx1 or vx > engine.clipVx2 or vy < engine.clipVy1 or vy > engine.clipVy2 then return end
self:registerColor(color)
local cellX = math.floor((vx + 1) / 2)
local cellY = math.floor((vy + 2) / 3)
self:markSubpixelDirty(cellX, cellY, cellX, cellY)
local idx = (vy - 1) * self.vWidth + vx
self.subpixelFgs[idx] = color
if bgColor then
self:registerColor(bgColor)
self.subpixelBgs[idx] = bgColor
end
self.subpixelBits[idx] = 1
self.hasSubpixels = true
self.subpixelsDirty = true
end
---Fills a rectangle with a character and/or color in terminal-cell coordinates.
---Any of char, fg, bg may be nil to leave that field of existing cells unchanged.
---@param x number Left edge in terminal cells (1-based).
---@param y number Top edge in terminal cells (1-based).
---@param w number Width in terminal cells.
---@param h number Height in terminal cells.
---@param char string Fill character. nil skips updating chars.
---@param fg FlintColor? Foreground color. nil skips updating fg.
---@param bg FlintColor? Background color. nil skips updating bg.
function Layer:drawRect(x, y, w, h, char, fg, bg)
local engine = self.engine
local x1 = math.max(engine.clipTx1, x)
local y1 = math.max(engine.clipTy1, y)
local x2 = math.min(engine.clipTx2, x + w - 1)
local y2 = math.min(engine.clipTy2, y + h - 1)
self:registerColor(fg)
self:registerColor(bg)
if x1 <= x2 and y1 <= y2 then self:markDirty(x1, y1, x2, y2) end
local tw = self.termWidth
local cChars = self.chars
local cFgs = self.fgs
local cBgs = self.bgs
for ty = y1, y2 do
local rowStart = (ty - 1) * tw
for tx = x1, x2 do
local idx = rowStart + tx
if char then cChars[idx] = char end
if fg then cFgs[idx] = fg end
if bg then cBgs[idx] = bg end
end
end
end
---Fills a rectangle on the virtual canvas in subpixel coordinates.
---Clipped to the engine's current subpixel clip region.
---@param vx number Left edge in subpixels (1-based).
---@param vy number Top edge in subpixels (1-based).
---@param vw number Width in subpixels.
---@param vh number Height in subpixels.
---@param color FlintColor? Foreground color for the filled area.
---@param bgColor FlintColor? Optional background color for the filled area.
function Layer:drawSubpixelRect(vx, vy, vw, vh, color, bgColor)
local engine = self.engine
local x1 = math.max(engine.clipVx1, vx)
local y1 = math.max(engine.clipVy1, vy)
local x2 = math.min(engine.clipVx2, vx + vw - 1)
local y2 = math.min(engine.clipVy2, vy + vh - 1)
self:registerColor(color)
if bgColor then self:registerColor(bgColor) end
if x1 <= x2 and y1 <= y2 then
self:markSubpixelDirty(math.floor((x1 + 1) / 2), math.floor((y1 + 2) / 3),
math.floor((x2 + 1) / 2), math.floor((y2 + 2) / 3))
end
local width = self.vWidth
local sFgs = self.subpixelFgs
local sBgs = self.subpixelBgs
local sBits = self.subpixelBits
for cy = y1, y2 do
local rowStart = (cy - 1) * width
for cx = x1, x2 do
local idx = rowStart + cx
sFgs[idx] = color
if bgColor then sBgs[idx] = bgColor end
sBits[idx] = 1
end
end
self.hasSubpixels = true
self.subpixelsDirty = true
end
---Draws a Bresenham line on the virtual canvas between two subpixel coordinates.
---Only the foreground color of each touched subpixel is set; bgColor is not affected.
---@param vx1 number Start column in subpixels (1-based).
---@param vy1 number Start row in subpixels (1-based).
---@param vx2 number End column in subpixels (1-based).
---@param vy2 number End row in subpixels (1-based).
---@param color FlintColor Color of the line.
function Layer:drawSubpixelLine(vx1, vy1, vx2, vy2, color)
local dx = math.abs(vx2 - vx1)
local dy = math.abs(vy2 - vy1)
local sx = (vx1 < vx2) and 1 or -1
local sy = (vy1 < vy2) and 1 or -1
local err = dx - dy
local vWidth = self.vWidth
local sFgs = self.subpixelFgs
local sBits = self.subpixelBits
local engine = self.engine
local cx1, cx2 = engine.clipVx1, engine.clipVx2
local cy1, cy2 = engine.clipVy1, engine.clipVy2
self:registerColor(color)
local bx1 = math.max(cx1, math.min(vx1, vx2))
local bx2 = math.min(cx2, math.max(vx1, vx2))
local by1 = math.max(cy1, math.min(vy1, vy2))
local by2 = math.min(cy2, math.max(vy1, vy2))
if bx1 <= bx2 and by1 <= by2 then
self:markSubpixelDirty(math.floor((bx1 + 1) / 2), math.floor((by1 + 2) / 3),
math.floor((bx2 + 1) / 2), math.floor((by2 + 2) / 3))
end
while true do
if vx1 >= cx1 and vx1 <= cx2 and vy1 >= cy1 and vy1 <= cy2 then
local idx = (vy1 - 1) * vWidth + vx1
sFgs[idx] = color
sBits[idx] = 1
end
if vx1 == vx2 and vy1 == vy2 then break end
local e2 = 2 * err
if e2 > -dy then
err = err - dy; vx1 = vx1 + sx
end
if e2 < dx then
err = err + dx; vy1 = vy1 + sy
end
end
self.hasSubpixels = true
self.subpixelsDirty = true
end
local texelColors = {}
local lutColorMap = {}
---Converts the subpixel buffer into terminal-cell chars/fg/bg for the given cell region.
---Normally called automatically inside Engine:compileSubpixels(); only call directly
---if you need to recompile a specific rect without going through the full engine pass.
---@param rx1 number? Left cell boundary (default 1).
---@param ry1 number? Top cell boundary (default 1).
---@param rx2 number? Right cell boundary (default termWidth).
---@param ry2 number? Bottom cell boundary (default termHeight).
function Layer:compileSubpixels(rx1, ry1, rx2, ry2)
local tw = self.termWidth
local vw = self.vWidth
rx1 = rx1 or 1
ry1 = ry1 or 1
rx2 = rx2 or tw
ry2 = ry2 or self.termHeight
local sFgs = self.subpixelFgs
local sBgs = self.subpixelBgs
local sBits = self.subpixelBits
local lChars = self.chars
local lFgs = self.fgs
local lBgs = self.bgs
for ty = ry1, ry2 do
local compStartIdx = (ty - 1) * tw
local vy1 = (ty - 1) * 3 + 1
local vy2 = vy1 + 1
local vy3 = vy1 + 2
local vIdxStart1 = (vy1 - 1) * vw
local vIdxStart2 = (vy2 - 1) * vw
local vIdxStart3 = (vy3 - 1) * vw
for tx = rx1, rx2 do
local vx1 = (tx - 1) * 2 + 1
local vx2 = vx1 + 1
local i1 = vIdxStart1 + vx1
local i2 = vIdxStart1 + vx2
local i3 = vIdxStart2 + vx1
local i4 = vIdxStart2 + vx2
local i5 = vIdxStart3 + vx1
local i6 = vIdxStart3 + vx2
local c1 = (sBits[i1] == 1) and (sFgs[i1] or "f") or (sBgs[i1] or sFgs[i1] or "f")
local c2 = (sBits[i2] == 1) and (sFgs[i2] or "f") or (sBgs[i2] or sFgs[i2] or "f")
local c3 = (sBits[i3] == 1) and (sFgs[i3] or "f") or (sBgs[i3] or sFgs[i3] or "f")
local c4 = (sBits[i4] == 1) and (sFgs[i4] or "f") or (sBgs[i4] or sFgs[i4] or "f")
local c5 = (sBits[i5] == 1) and (sFgs[i5] or "f") or (sBgs[i5] or sFgs[i5] or "f")
local c6 = (sBits[i6] == 1) and (sFgs[i6] or "f") or (sBgs[i6] or sFgs[i6] or "f")
if c1 == c2 and c1 == c3 and c1 == c4 and c1 == c5 and c1 == c6 then
if sBits[i1] == 1 or sBits[i2] == 1 or sBits[i3] == 1
or sBits[i4] == 1 or sBits[i5] == 1 or sBits[i6] == 1 then
local cIdx = compStartIdx + tx
lChars[cIdx] = "\128"
lFgs[cIdx] = c1
lBgs[cIdx] = c1
end
else
lutColorMap[c6] = 5
lutColorMap[c5] = 4
lutColorMap[c4] = 3
lutColorMap[c3] = 2
lutColorMap[c2] = 1
lutColorMap[c1] = 0
local id = lutColorMap[c2] + lutColorMap[c3] * 3 + lutColorMap[c4] * 4
+ lutColorMap[c5] * 20 + lutColorMap[c6] * 100
texelColors[1], texelColors[2], texelColors[3] = c1, c2, c3
texelColors[4], texelColors[5], texelColors[6] = c4, c5, c6
local cIdx = compStartIdx + tx
lChars[cIdx] = texelCharLut[id]
lFgs[cIdx] = texelColors[texelFgPosLut[id]]
lBgs[cIdx] = texelColors[texelBgPosLut[id]]
end
end
end
end
-- ============================================================================
-- 5. CORE ENGINE STRUCTURE & LAYER LIFECYCLE
-- ============================================================================
---@class Engine
---@field term table The target terminal object for output, must have .blit() and .getSize() methods.
---@field termWidth number Cached terminal width in characters.
---@field termHeight number Cached terminal height in characters.
---@field vWidth number Cached virtual canvas width in subpixels (termWidth * 2).
---@field vHeight number Cached virtual canvas height in subpixels (termHeight * 3).
---@field composite Buffer The flat composite buffer representing the final output state for the current frame.
---@field cacheChars table LUT for caching character patterns during composition.
---@field cacheFgs table LUT for caching foreground color patterns during composition.
---@field cacheBgs table LUT for caching background color patterns during composition.
---@field layers Layer[] Array of registered layers, sorted by zIndex.
---@field frameColors table Set of colors used in the current frame, for palette management.
---@field colorMapping table LUT for mapping logical colors to hardware palette slots.
---@field paletteDirty boolean Flag indicating whether the hardware palette needs to be updated.
---@field hwPalette table Cached hardware palette colors for quick lookup.
---@field presentY1 number Top row of the next present() update region.
---@field presentY2 number Bottom row of the next present() update region.
---@field gfxMode boolean Flag indicating whether the engine is in graphics mode (true) or text mode (false).
---@field gfxRowCache table Cache for storing previously rendered rows in graphics mode to optimize redraws.
---@field nativeRGBs table LUT mapping FlintColor hex codes to native RGB values
local Engine = {}
Engine.__index = Engine
---Creates a new Flint engine attached to the given terminal.
---The engine reads the terminal size once at creation; resize is not tracked.
---@param targetTerm table A CC terminal object with `.blit()` and `.getSize()`.
---@return Engine
function flint.new(targetTerm)
assert(targetTerm and targetTerm.blit and targetTerm.getSize,
"Flint benoetigt ein Objekt mit .blit() und .getSize() Methoden!")
local self = setmetatable({}, Engine)
self.term = targetTerm
local tw, th = self.term.getSize()
self.termWidth = tw
self.termHeight = th
self.composite = Buffer.new(tw, th)
self.vWidth = tw * 2
self.vHeight = th * 3
self.cacheChars = {}
self.cacheFgs = {}
self.cacheBgs = {}
self.layers = {}
self.frameColors = {}
self.colorMapping = {}
self.paletteDirty = true
self.hwPalette = {}
self.presentY1 = 1
self.presentY2 = th
self.gfxMode = false
self.gfxRowCache = {}
self.nativeRGBs = {}
for i = 0, 15 do
local hex = slotHex[i + 1]
local r, g, b
if self.term.getPaletteColor then
r, g, b = self.term.getPaletteColor(slotColor[i])
end
if r then
local ir = math.floor(r * 255 + 0.5)
local ig = math.floor(g * 255 + 0.5)
local ib = math.floor(b * 255 + 0.5)
self.nativeRGBs[hex] = ir * 65536 + ig * 256 + ib
else
self.nativeRGBs[hex] = defaultPalette[hex]
end
end
self:resetClipRegion()
return self
end
---Registers a color with the engine's palette if it hasn't already been registered this frame. The engine maintains a set of colors used in the current frame to optimize palette updates; this method ensures that any color used by layers is included in that set.
---@param color FlintColor The color to register.
function Engine:registerColor(color)
if not color then return end
if not self.frameColors[color] then
self.frameColors[color] = true
self.paletteDirty = true
end
end
-- ============================================================================
-- 6. VIEWPORT / CLIPPING SYSTEM
-- ============================================================================
---Restricts all subsequent draw calls to the given cell rectangle.
---Both character-space and subpixel-space clip regions are updated atomically.
---@param x number Left edge in terminal cells (1-based).
---@param y number Top edge in terminal cells (1-based).
---@param w number Width in terminal cells.
---@param h number Height in terminal cells.
function Engine:setClipRegion(x, y, w, h)
self.clipTx1 = math.max(1, x)
self.clipTy1 = math.max(1, y)
self.clipTx2 = math.min(self.termWidth, x + w - 1)
self.clipTy2 = math.min(self.termHeight, y + h - 1)
self.clipVx1 = (self.clipTx1 - 1) * 2 + 1
self.clipVy1 = (self.clipTy1 - 1) * 3 + 1
self.clipVx2 = self.clipTx2 * 2
self.clipVy2 = self.clipTy2 * 3
end
---Removes the clip region, restoring the full terminal extent for draw calls.
function Engine:resetClipRegion()
self.clipTx1 = 1
self.clipTy1 = 1
self.clipTx2 = self.termWidth
self.clipTy2 = self.termHeight
self.clipVx1 = 1
self.clipVy1 = 1
self.clipVx2 = self.vWidth
self.clipVy2 = self.vHeight
end
-- ============================================================================
-- 7. LAYER MANAGEMENT
-- ============================================================================
---Creates a new Layer, registers it with the engine, and inserts it into the
---sorted draw order. Layers with a lower zIndex are drawn first (further back).
---@param zIndex number Rendering order.
---@return Layer
function Engine:addLayer(zIndex)
local layer = Layer.new(self, zIndex)
table.insert(self.layers, layer)
table.sort(self.layers, function(a, b)
return a.zIndex < b.zIndex
end)
return layer
end
---Clears all layers (chars, subpixels, colors, and dirty state).
---Equivalent to calling layer:clear() on every registered layer.
function Engine:clear()
for i = 1, #self.layers do
self.layers[i]:clear()
end
end
-- ============================================================================
-- 8. THE COMPOSITE PASS
-- ============================================================================
---Resolves the hardware palette, composites all layers into the output buffer,
---and records the dirty row range for the next present() call.
---Must be called once per frame after all draw calls and before present().
function Engine:compileSubpixels()
local active = { ["0"] = true, ["f"] = true }
for i = 1, #self.layers do
for color in pairs(self.layers[i].usedColors) do
active[color] = true
end
end
local changed = false
for color in pairs(active) do
if not self.frameColors[color] then
changed = true
break
end
end
if not changed then
for color in pairs(self.frameColors) do
if not active[color] then
changed = true
break
end
end
end
self.frameColors = active
if changed then self.paletteDirty = true end
local rebuilt = false
if self.paletteDirty then
local function toRGB(rgb)
local r = bit32.band(bit32.rshift(rgb, 16), 0xFF)
local g = bit32.band(bit32.rshift(rgb, 8), 0xFF)
local b = bit32.band(rgb, 0xFF)
return r, g, b
end
local term = self.term
local hwPalette = self.hwPalette
local function setHardwarePalette(slotIndex, rgb)
if hwPalette[slotIndex] == rgb then return end
hwPalette[slotIndex] = rgb
local r = bit32.band(bit32.rshift(rgb, 16), 0xFF) / 255
local g = bit32.band(bit32.rshift(rgb, 8), 0xFF) / 255
local b = bit32.band(rgb, 0xFF) / 255
term.setPaletteColor(slotColor[slotIndex], r, g, b)
end
local uniqueColors = {}
local uniqueCount = 0
for color in pairs(self.frameColors) do
uniqueCount = uniqueCount + 1
table.insert(uniqueColors, color)
end
table.sort(uniqueColors, function(a, b)
local typeA = type(a)
local typeB = type(b)
if typeA ~= typeB then
return typeA < typeB
end
return a < b
end)
self.colorMapping = {}
if uniqueCount <= 16 then
local nativeSlotsUsed = {}
local customColors = {}
for i = 1, #uniqueColors do
local val = uniqueColors[i]
if type(val) == "string" and #val == 1 and val:match("[0-9a-f]") then
nativeSlotsUsed[val] = true
self.colorMapping[val] = val
else
table.insert(customColors, val)
end
end
local freeSlots = {}
for i = 0, 15 do
local hexChar = slotHex[i + 1]
if nativeSlotsUsed[hexChar] then
setHardwarePalette(i, self.nativeRGBs[hexChar])
else
table.insert(freeSlots, i)
end
end
for k = 1, #customColors do
local val = customColors[k]
local slotIndex = freeSlots[k]
self.colorMapping[val] = slotHex[slotIndex + 1]
setHardwarePalette(slotIndex, val)
end
else
local valToRGB = {}
local uniqueRGBs = {}
for i = 1, #uniqueColors do
local val = uniqueColors[i]
local rgb
if type(val) == "string" and #val == 1 and val:match("[0-9a-f]") then
rgb = self.nativeRGBs[val]
else
rgb = val
end
valToRGB[val] = rgb
table.insert(uniqueRGBs, val)
end
local clusters = {}
for i = 1, #uniqueRGBs do
local val = uniqueRGBs[i]
clusters[i] = {
color = valToRGB[val],
members = { val },
alive = true,
}
end
local n = #clusters