-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitmapfont.r
1416 lines (1355 loc) · 60.7 KB
/
bitmapfont.r
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
#' The S3 AmigaBitmapFont and AmigaBitmapFontSet classes
#'
#' A comprehensive representation of monochromous Amiga bitmap fonts.
#'
#' Nowadays fonts are represented by vector graphics an computer systems.
#' On the original Commodore Amiga, the screen resolution, system memory
#' and cpu speed were limited. On those systems, it was more efficient
#' to use bitmap images to represent the glyphs in fonts. The
#' `AmigaBitmapFontSet` and `AmigaBitmapFont` classes can be used
#' to represent Amiga bitmap fonts.
#'
#' The Commodore Amiga had a directory named 'FONTS' located in the
#' root, where (bitmap) fonts were stored. Font sets were stored
#' under the font name with a *.font extension. Files with the *.font
#' extension did not contain the bitmap images of the font. Rather
#' the *.font file contained information on which font heights (in
#' pixels) are available, in addition to some other meta-information.
#'
#' The bitmap images were stored in separate files for each individual
#' height. The `AmigaBitmapFontSet` is an S3 class that forms
#' a comprehensive format (named `list`) to represent the *.font
#' files. The `AmigaBitmapFont` is an S3 class is a comprehensive
#' format (named `list`) that represent each font bitmap and glyph
#' information. The `AmigaBitmapFontSet` objects will hold one or more
#' `AmigaBitmapFont` objects.
#'
#' The `AmigaBitmapFont` and `AmigaBitmapFontSet` objects are
#' essentially named `list`s. Their structure and most important
#' elements are described below. Although it is possible to replace
#' elements manually, it is only advisable when you know what you
#' are doing as it may break the validity of the font.
#'
#' @section AmigaBitmapFontSet:
#' * `fch_FileID`: A `factor` with levels 'FontContents', 'TFontContents' and
#' 'ScalableOutline'. It specifies the type of font.
#' Currently only the first level is supported.
#' * `fch_NumEntries`: number of font heights available for this font. It should
#' match with the length of `FontContents`. Do not change
#' this value manually.
#' * `FontContents`: This is a `list` with bitmap entries for each specific font
#' height (in pixels). The name of each element in this list is
#' 'pt' followed by the height. Each element in this list holds
#' the elements:
#' * Miscellaneous: Miscellaneous information from the \*.font file
#' * `fc_FileName`: This element represents the filename of the
#' nested font bitmap images. Note that it should be a valid
#' Commodore Amiga filename. It is best to modify this name
#' using [fontName()]. Note that this field could cause
#' problems as Commodore Amiga filenames can contain characters
#' that most modern platforms would not allow (such as the
#' question mark).
#' * `BitmapFont`: This element is of type `AmigaBitmapFont` and is structured
#' as described in the following section. The information in this
#' element is no longer part of the *.font file.
#'
#' @section AmigaBitmapFont:
#' Information represented by a `AmigaBitmapFont` is not stored
#' in *.font files. Rather it is stored in sub-directories of the font
#' in separate files. It has the following structure:
#' * Miscellaneous: Elements with information on the font
#' properties and style, and also relative file pointers.
#' * `glyph.info`: A `data.frame` containing glyph info with information
#' for specific glyphs on each row. Each row matches with a specific
#' ASCII code, ranging from `tf_LoChar` up to `tf_HiChar`. There is an additional
#' row that contains information for the default glyph that is
#' out of the range of the `tf_LoChar` and `tf_HiChar`. The `data.frame`
#' thus has `2 + tf_HiChar - tf_LoChar` rows. This
#' table is used to extract and plot a glyph from the
#' `bitmap` image correctly.
#' * `bitmap`: Is a monochromous bitmap image of all the font's glyphs in a
#' single line. It is a simple `raster` object
#' (see [grDevices::as.raster()]) with an additional
#' attribute 'palette', which lists the two colours in the image. In
#' this palette, the first colour is the background colour and the
#' second colour is interpreted as the foregroundcolour.
#'
#' @section Useful functions:
#' For importing and exporting the following functions are useful:
#' [read.AmigaBitmapFont()], [read.AmigaBitmapFontSet()],
#' [write.AmigaBitmapFont()] and [write.AmigaBitmapFontSet()].
#'
#' The following generic functions are implemented for these objects:
#' [AmigaFFH::plot()], `print`,
#' [AmigaFFH::as.raster()] and [AmigaFFH::as.raw()].
#'
#' Use [AmigaFFH::c()] to combine one or more
#' `AmigaBitmapFont` objects into a `AmigaBitmapFontSet`.
#'
#' @docType class
#' @aliases AmigaBitmapFontSet
#' @name AmigaBitmapFont
#' @rdname AmigaBitmapFont
#' @family AmigaBitmapFont.operations
#' @family raster.operations
#' @author Pepijn de Vries
#' @references
#' <http://amigadev.elowar.com/read/ADCD_2.1/Libraries_Manual_guide/node03E0.html>
#' <http://amigadev.elowar.com/read/ADCD_2.1/Libraries_Manual_guide/node03DE.html>
#' <http://amigadev.elowar.com/read/ADCD_2.1/Libraries_Manual_guide/node05BA.html>
#' @examples
#' \dontrun{
#' ## 'font_example' is an example of the AmigaBitmapFontSet object:
#' data(font_example)
#'
#' ## An AmigaBitmapFont object can also be extracted from this object:
#' font_example_9 <- getAmigaBitmapFont(font_example, 9)
#'
#' ## the objects can be printed, plotted, converted to raw data or a raster:
#' print(font_example)
#' plot(font_example)
#' font_example_raw <- as.raw(font_example)
#' font_example_raster <- as.raster(font_example)
#'
#' ## You can also format text using the font:
#' formated_raster <- as.raster(font_example, text = "Foo bar", style = "bold")
#' plot(font_example, text = "Foo bar", style = "underlined", interpolate = F)
#' }
NULL
.print_to_raster <- function(text, font, style = NULL, palette = NULL) {
if (inherits(font, "AmigaBitmapFontSet")) {
h <- availableFontSizes(font)
font <- getAmigaBitmapFont(font, h[length(h)])
}
if (!inherits(font, "AmigaBitmapFont")) stop("'font' should be of class AmigaBitmapFont or AmigaBitmapFontSet.")
if (!is.null(style)) {
style <- match.arg(style, c("bold", "italic", "underlined"), T)
## You can't apply styles to a font that is already styled:
style <- style[!font$tf_Style[toupper(style)]]
}
if (length(text) > 1) {
warning("'text' has multiple elements, only using the first.")
text <- text[1]
}
# split text along lines:
text <- strsplit(text, "\n")[[1]]
pal <- attr(font$bitmap, "palette")
bm <- as.matrix(font$bitmap)
bm <- apply(bm, 2, function(y) y == pal[[2]])
if (!is.null(palette)) pal <- palette
result <- lapply(text, function(y) {
## get ascii codes:
y <- utf8ToInt(enc2utf8(y))
## the final glyph is the default glyph when it is out of range
y[y < font$tf_LoChar] <- font$tf_HiChar + 1
y[y > font$tf_HiChar] <- font$tf_HiChar + 1
y <- 1 + y - font$tf_LoChar
positions <- apply(
font$glyph.info[y,][,names(font$glyph.info) %in% c("glyphWidth", "charSpace"), drop = F],
1, max
)
if (!is.null(font$glyph.info$charKern)) positions <- positions + c(font$glyph.info$charKern[y][-1], 0)
positions <- cumsum(c(0, positions))[1:length(positions)]
positions <- 1 + positions - min(positions)
h <- font$tf_YSize
glyphs <- mapply(function(loc, w, sp, kern) {
result <- matrix(F, h + 2,
max(c(sp, w)) +
ifelse("bold" %in% style, font$tf_BoldSmear, 0) +
ifelse(kern > 0, kern, 0) +
ifelse("italic" %in% style, ceiling((h + 1)/2), 0))
if (w > 0) {
for (i in 0:ifelse("bold" %in% style, font$tf_BoldSmear, 0)) {
result[1:h, i + (1:w)] <- result[1:h, i + (1:w)] | bm[,(loc + 1):(loc + w)]
}
if ("italic" %in% style) {
for (j in 1:(h - ifelse(h > 15, 2, 1))) { ## The displacement seems to shift for h > 15
displacement <- floor((h - j + ifelse(h > 15, 0, 1))/2)
result[j,] <- c(rep(F, displacement), utils::head(result[j,], -displacement))
}
}
}
if (ncol(result) > 0) {
if ("underlined" %in% style) {
result[font$tf_Baseline + 2,] <- result[font$tf_Baseline + 2,] |
(c(!result[font$tf_Baseline + 2,][-1], T) & c(T, !result[font$tf_Baseline + 2,][-ncol(result)]))
}
}
result
},
loc = font$glyph.info$glyphLocation[y],
w = font$glyph.info$glyphWidth[y],
sp = if(is.null(font$glyph.info$charSpace)) rep(0, length(y)) else
font$glyph.info$charSpace[y],
kern = if(is.null(font$glyph.info$charKern)) rep(0, length(y)) else
c(font$glyph.info$charKern[y][-1], 0),
SIMPLIFY = F)
widths <- unlist(lapply(glyphs, ncol))
result <- matrix(F, nrow = h + 2, ncol = max(positions + widths))
lapply(1:length(glyphs), function(i) {
result[,positions[i]:(positions[i] + widths[i] - 1)] <<-
result[,positions[i]:(positions[i] + widths[i] - 1)] |
glyphs[[i]]
})
## make background transparent if no palette is specified
if (is.null(palette)) pal[1] <<- grDevices::adjustcolor(pal[1], alpha.f = 0)
result <- apply(result, 2, function(y) pal[1 + as.numeric(y)])
return(result)
})
result2 <- matrix(pal[1],
sum(unlist(lapply(result, nrow))),
sum(unlist(lapply(result, ncol))))
lapply(1:length(result), function(i) {
result2[(i - 1)*(font$tf_YSize + 2) + 1:(font$tf_YSize + 2),][,1:ncol(result[[i]])] <<- result[[i]]
NULL
})
result2 <- as.raster(result2)
return(result2)
}
.amiga.node <- data.frame(
byte = c(4, 4, 1, 1, 4),
signed = c(F, F, F, T, F),
par.names = c("ln_Succ", "ln_Pred", "ln_Type", "ln_Pri", "ln_Name"),
stringsAsFactors = F
)
.amiga.node.types <- c("NT_UNKNOWN", "NT_TASK", "NT_INTERRUPT", "NT_DEVICE", "NT_MSGPORT", "NT_MESSAGE",
"NT_FREEMSG", "NT_REPLYMSG", "NT_RESOURCE", "NT_LIBRARY", "NT_MEMORY", "NT_SOFTINT",
"NT_FONT", "NT_PROCESS", "NT_SEMAPHORE", "NT_SIGNALSEM", "NT_BOOTNODE", "NT_KICKMEM",
"NT_GRAPHICS", "NT_DEATHMESSAGE", "NT_USER", "NT_EXTENDED")
.amiga.font.sets <- data.frame(
byte = c(2, 2),
signed = c(F, F),
par.names = c("fch_FileID", "fch_NumEntries"),
stringsAsFactors = F
)
.amiga.font.types <- c("FontContents", "TFontContents", "ScalableOutline")
.read.amiga.node <- function(dat) {
## Currently only works for simple nodes as included in font files
result <- with(.amiga.node, .read.amigaData(dat, byte, signed, par.names))
if (result$ln_Type < 22 || result$ln_Type >= 254) {
result$ln_Type <- result$ln_Type + 1
if (result$ln_Type > 254) result$ln_Type <- result$ln_Type - 234
result$ln_Type <- .match.factor(result, "ln_Type", 1:length(.amiga.node.types),
.amiga.node.types)
}
return(result)
}
.amiga.node.to.raw <- function(node) {
node <- node[.amiga.node$par.names]
node$ln_Type <- match(as.character(node$ln_Type), .amiga.node.types)
if (node$ln_Type >= 22) node$ln_Type <- node$ln_Type + 234
node$ln_Type <- node$ln_Type - 1
node <- with(.amiga.node, .write.amigaData(node, byte, signed, par.names))
node
}
.amiga.font.header <- data.frame(
byte = c(-36, -14, 2, 2, 4, -32, -14, 4, 2, 2, -1, -1, 2, 2, 2, 2, 1, 1, 4, 2, 4, 4, 4),
signed = c( F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F),
par.names = c("leadingHunks", "node.disklink", "dfh_FileID", "dfh_Revision", "dfh_Segment",
"fontName", "node.message", "mn_ReplyPort", "mn_Length", "tf_YSize",
"tf_Style", "tf_Flags", "tf_XSize", "tf_Baseline", "tf_BoldSmear",
"tf_Accessors", "tf_LoChar", "tf_HiChar", "tf_CharData", "tf_Modulo",
"tf_CharLoc", "tf_CharSpace", "tf_CharKern"),
stringsAsFactors = F
)
#' Read AmigaBitmapFontSet from *.font file
#'
#' Reads [AmigaBitmapFontSet()] from *.font file including
#' all nested bitmap images for all font heights.
#'
#' The *.font file only holds meta-information. The bitmap images for
#' each font height are stored in separate files, which are listed
#' in the *.font file. The function reads the *.font file, including
#' all nested bitmap files and returns it as a
#' [AmigaBitmapFontSet()].
#'
#' It can also read *.font files
#' from [adfExplorer::amigaDisk-class()] objects,
#' but that requires the adfExplorer package to be installed.
#' @rdname read.AmigaBitmapFontSet
#' @name read.AmigaBitmapFontSet
#' @param file A `character` string of the filename of the *.font file to be read.
#' @param disk A virtual Commodore Amiga disk from which the `file` should be
#' read. This should be an [`amigaDisk()`][adfExplorer::amigaDisk-class] object. Using
#' this argument requires the adfExplorer package.
#' When set to `NULL`, this argument is ignored.
#' @param ... Currently ignored.
#' @returns Returns an [AmigaBitmapFontSet()] object read from the specified file.
#' @examples
#' \dontrun{
#' data(font_example)
#'
#' ## in order to read, we first need to write a file"
#' write.AmigaBitmapFontSet(font_example, tempdir())
#'
#' ## The font is written as 'AmigaFFH.font' as that name
#' ## is embedded in the AmigaBitmapFontSet object 'font_example'.
#' ## We can read it as follows:
#' font.read <- read.AmigaBitmapFontSet(file.path(tempdir(), "AmigaFFH.font"))
#'
#' ## similarly, the file can also be written and read from and to
#' ## a virtual amiga disk. The following codes requires the 'adfExplorer'
#' ## package:
#' adf <- adfExplorer::blank.amigaDOSDisk("font.disk")
#' adf <- adfExplorer::dir.create.adf(adf, "FONTS")
#' adf <- write.AmigaBitmapFontSet(font_example, "DF0:FONTS", adf)
#' font.read <- read.AmigaBitmapFontSet("DF0:FONTS/AmigaFFH.font", adf)
#' }
#' @family AmigaBitmapFont.operations
#' @family io.operations
#' @author Pepijn de Vries
#' @export
read.AmigaBitmapFontSet <- function(file, disk = NULL, ...) {
dat <- .read.generic(file, disk)
rawToAmigaBitmapFontSet(dat, file, disk)
}
#' Coerce raw data into an AmigaBitmapFontSet class object
#'
#' [AmigaBitmapFontSet()] objects are comprehensive representations of binary Amiga
#' font files (*.font). Use this function to convert `raw` data from
#' such a file to an [AmigaBitmapFontSet] object.
#'
#' This function converts `raw` data as stored in *.font
#' files. The function also needs the file location, in order
#' to load the nested bitmap images for each font height.
#' This function is effectively the inverse of [AmigaFFH::as.raw()].
#'
#' @rdname rawToAmigaBitmapFontSet
#' @name rawToAmigaBitmapFontSet
#' @param x A `vector` of `raw` data that needs to be
#' converted into an [AmigaBitmapFontSet()].
#' @param file The `raw` version of the [AmigaBitmapFontSet()]
#' does not contain the nested font bitmap images. In order to correctly
#' construct an [AmigaBitmapFontSet()] the file location of the
#' original *.font file is required in order to read and include the
#' font bitmap image information. `file` should thus be a `character`
#' string specifying the file location of the *.font file.
#' @param disk A virtual Commodore Amiga disk from which the `file` should be
#' read. This should be an [`amigaDisk()`][adfExplorer::amigaDisk-class] object. Using
#' this argument requires the adfExplorer package.
#' When set to `NULL`, this argument is ignored.
#' @returns Returns an [AmigaBitmapFontSet()] object.
#' @examples
#' \dontrun{
#' data(font_example)
#'
#' ## First create raw font set data. Note that this raw data
#' ## does not include the nested font bitmap images.
#' fontset.raw <- as.raw(font_example)
#'
#' ## Therefore it is necesary to have the entire font stored as files:
#' write.AmigaBitmapFontSet(font_example, tempdir())
#'
#' font.restored <- rawToAmigaBitmapFontSet(fontset.raw, file.path(tempdir(), "AmigaFFH.font"))
#' }
#' @family AmigaBitmapFont.operations
#' @family raw.operations
#' @author Pepijn de Vries
#' @export
rawToAmigaBitmapFontSet <- function(x, file, disk = NULL) {
result <- with(.amiga.font.sets, .read.amigaData(x[1:4], byte, signed, par.names))
result$fch_FileID <- .match.factor(result, "fch_FileID", c(0x0f00, 0x0f02, 0x0f03),
.amiga.font.types)
if (result$fch_FileID != "FontContents") stop(sprintf("%s font type is not (yet) supported.", as.character(result$fch_FileID)))
result[["FontContents"]] <- lapply(result$fch_NumEntries:1, function(i) {
if (result$fch_FileID == "FontContents") {
offset <- 260*(i - 1)
result <- list(
fc_FileName = .rawToCharNull(x[-1:-4][offset + 1:256]),
fc_YSize = .rawToAmigaInt(x[-1:-4][offset + 257:258], 16, F),
fc_Style = x[-1:-4][offset + 259],
fc_Flags = x[-1:-4][offset + 260]
)
result$fc_Style <- as.logical(.rawToBitmap(result$fc_Style, F, F))
names(result$fc_Style) <- c("UNDERLINED", "BOLD", "ITALIC", "EXTENDED", "RESERVED1", "RESERVED2", "COLORFONT", "TAGGED")
result$fc_Flags <- as.logical(.rawToBitmap(result$fc_Flags, F, F))
names(result$fc_Flags) <- c("ROMFONT", "DISKFONT", "REVPATH", "TALLDOT", "WIDEDOT", "PROPORTIONAL", "DESIGNED", "REMOVED")
if (is.null(disk)) {
result[["BitmapFont"]] <-
## replace the file amiga file separator with the platform dependent file separator,
## and read font from file:
read.AmigaBitmapFont(file.path(dirname(file), gsub("[/]", .Platform$file.sep, result$fc_FileName)))
} else {
result[["BitmapFont"]] <-
read.AmigaBitmapFont(paste(c(utils::head(strsplit(file, "/", T)[[1]], -1), result$fc_FileName), collapse = "/"), disk)
}
if (any(result$fc_Style != result$BitmapFont$tf_Style)) warning(sprintf("Styles defined in main font (*.font) and bitmap file (%s) do not match.", result$fc_FileName))
if (any(result$fc_Flags != result$BitmapFont$tf_Flags)) warning(sprintf("Flags defined in main font (*.font) and bitmap file (%s) do not match.", result$fc_FileName))
result
} else {
stop("This bitmap font type is not (yet) supported")
}
})
pt.size <- as.numeric(unlist(lapply(strsplit(unlist(lapply(result$FontContents, function(x) x$fc_FileName)), "/"),
function(x) x[[2]])))
result$FontContents <- result$FontContents[order(pt.size)]
names(result$FontContents) <- paste0("pt", sort(pt.size))
class(result) <- "AmigaBitmapFontSet"
return(result)
}
#' Read an AmigaBitmapFont class object from a file
#'
#' Amiga Font Bitmaps of distinctive font heights are stored in separate
#' files, which in combination form a font collection or set. This
#' function can be used to read a specific bitmap from a set and returns
#' it as an [AmigaBitmapFont()] class object.
#'
#' Individual font bitmaps are stored in a font's subdirectory where
#' the file name is usually equal to the font height in pixels. This
#' function will read such a font bitmap file and return it as an
#' [AmigaBitmapFont()] class object. It can also read such
#' files from [adfExplorer::amigaDisk-class()] objects,
#' but that requires the adfExplorer package to be installed.
#'
#' @rdname read.AmigaBitmapFont
#' @name read.AmigaBitmapFont
#' @param file The file name of a font subset is usually simply a numeric number
#' indicating the font height in pixels. Use `file` as a `character`
#' string representing that file location.
#' @param disk A virtual Commodore Amiga disk from which the `file` should be
#' read. This should be an [`amigaDisk()`][adfExplorer::amigaDisk-class] object. Using
#' this argument requires the adfExplorer package.
#' When set to `NULL`, this argument is ignored.
#' @param ... Arguments passed on to [rawToAmigaBitmapFont()].
#' @returns Returns an [AmigaBitmapFont()] object read from the specified file.
#' @examples
#' \dontrun{
#' data(font_example)
#'
#' ## Let's store the example font first:
#' write.AmigaBitmapFontSet(font_example, tempdir())
#'
#' ## Now read a specific subset from the font files:
#' font.sub <- read.AmigaBitmapFont(file.path(tempdir(), "AmigaFFH", "9"))
#'
#' ## The same can be done with a virtual Amiga disk. The following
#' ## examples require the 'adfExplorer' package.
#' font.disk <- adfExplorer::blank.amigaDOSDisk("font.disk")
#' font.disk <- adfExplorer::dir.create.adf(font.disk, "FONTS")
#' font.disk <- write.AmigaBitmapFontSet(font_example, "DF0:FONTS", font.disk)
#' font.sub <- read.AmigaBitmapFont("DF0:FONTS/AmigaFFH/9", font.disk)
#' }
#' @family AmigaBitmapFont.operations
#' @family io.operations
#' @author Pepijn de Vries
#' @export
read.AmigaBitmapFont <- function(file, disk = NULL, ...) {
dat <- .read.generic(file, disk)
rawToAmigaBitmapFont(dat, file, ...)
}
#' Write an AmigaBitmapFont(set) file
#'
#' Functions to write [AmigaBitmapFont()] and [AmigaBitmapFontSet()]
#' class objects to files.
#'
#' [AmigaBitmapFontSet()] class objects are written to a *.font
#' file. The filename used for this purpose is obtained from the object
#' itself using [fontName()]. In addition, a subdirectory is
#' created automatically (when it doesn't already exist)
#' to which al the separate bitmap images for each font height are written
#' to individual files.
#'
#' [AmigaBitmapFont()] class objects can also be written to a
#' file. In order to use it on a Commodore Amiga or emulator, it is better
#' to embed the font bitmap in a font set (using [AmigaFFH::c()])
#' and write the set to corresponding files.
#' @rdname write.AmigaBitmapFont
#' @name write.AmigaBitmapFont
#' @param x Respectively an [AmigaBitmapFont()] or a
#' [AmigaBitmapFontSet()] object depending on which of the
#' write-functions is called. This is the object that will be written
#' to the specified file.
#' @param file A `character` string specifying the file location
#' to which `x` (an [AmigaBitmapFont()] object) needs to be written.
#' It is common practice on the Amiga to use the font height in pixels as
#' file name.
#' @param path A `character` string specifying the path where
#' `x` (an [AmigaBitmapFontSet()] object) needs to be stored.
#' The filename for the font set will be extracted from `x` using
#' [fontName()] followed by the *.font extension. A subdirectory
#' will be created with the same name (without the extension) if it doesn't
#' already exists. In this subdirectory all the nested [AmigaBitmapFont()]
#' objects are stored.
#' @param disk A virtual Commodore Amiga disk to which the `file` should be
#' written. This should be an [`amigaDisk()`][adfExplorer::amigaDisk-class] object. Using
#' this argument requires the adfExplorer package.
#' When set to `NULL`, this argument is ignored.
#' @returns Invisibly returns the result of the call of `close` to the
#' file connection. Or, when `disk` is specified, a copy of
#' `disk` is returned to which the file(s) is/are written.
#' @examples
#' \dontrun{
#' ## obtain a bitmap font set:
#' data(font_example)
#'
#' ## write the font set to their files. The file name
#' ## is extracted from the font object, so you only have
#' ## to provide the path:
#' write.AmigaBitmapFont(font_example, temp.dir())
#'
#' ## extract a font bitmap:
#' font <- getAmigaBitmapFont(font_example, 9)
#'
#' ## and write it to the temp dir:
#' write.AmigaBitmapFont(font, file.path(temp.dir(), "9"))
#'
#' ## The following examples require the 'adfExplorer' package:
#' font.disk <- adfExplorer::blank.amigaDOSDisk("font.disk")
#' font.disk <- adfExplorer::dir.create.adf(font.disk, "FONTS")
#' font.disk <- write.AmigaBitmapFontSet(font_example, "DF0:FONTS", font.disk)
#' }
#' @family AmigaBitmapFont.operations
#' @family io.operations
#' @author Pepijn de Vries
#' @export
write.AmigaBitmapFont <- function(x, file, disk = NULL) {
if (!inherits(x, "AmigaBitmapFont")) stop("x should be of class AmigaBitmapFont.")
.write.generic(x, file, disk)
}
#' @rdname write.AmigaBitmapFont
#' @name write.AmigaBitmapFontSet
#' @export
write.AmigaBitmapFontSet <- function(x, path = getwd(), disk = NULL) {
if (!inherits(x, "AmigaBitmapFontSet")) stop("x should be of class AmigaBitmapFontSet.")
filenames <- unlist(lapply(x$FontContents, function(y) y$fc_FileName))
filenames <- do.call(rbind, strsplit(filenames, "/"))
if (ncol(filenames) != 2) stop("Unexpected file structure.")
if (length(unique(filenames[,1])) != 1) stop("Not a single base name for the font.")
fn <- sprintf("%s.font", filenames[1, 1])
if (is.null(disk)) {
if (path != "") fn <- file.path(path, fn)
} else {
if (path != "") fn <- paste(path, fn, sep = ifelse(substr(path, nchar(path), nchar(path)) == "/", "", "/"))
}
disk <- .write.generic(x, fn, disk)
dr <- filenames[1, 1]
if (is.null(disk)) {
if (path != "") dr <- file.path(path, dr)
if (!dir.exists(dr))
dir.create(dr)
result <- lapply(1:nrow(filenames), function(y) {
fn <- file.path(filenames[y, 1], filenames[y, 2])
if (path != "") fn <- file.path(path, fn)
write.AmigaBitmapFont(x$FontContents[[y]]$BitmapFont, fn)
})
return(invisible(result[[length(result)]]))
} else {
if (path != "") dr <- paste(path, dr, sep = ifelse(substr(path, nchar(path), nchar(path)) == "/", "", "/"))
if (!adfExplorer::adf.file.exists(disk, dr)) ## better to use 'dir.exists', this needs to be implemented in adfExplorer
disk <- adfExplorer::dir.create.adf(disk, dr)
lapply(1:nrow(filenames), function(y) {
fn <- paste(filenames[y, 1], filenames[y, 2], sep = "/")
if (path != "") fn <- paste(path, fn, sep = ifelse(substr(path, nchar(path), nchar(path)) == "/", "", "/"))
disk <<- write.AmigaBitmapFont(x$FontContents[[y]]$BitmapFont, fn, disk = disk)
})
return(disk)
}
}
#' Coerce raw data into an AmigaBitmapFont class object
#'
#' [AmigaBitmapFont()] objects are comprehensive representations of binary Amiga
#' font subset files. The file name is usually simply a numeric number
#' indicating the font height in pixels. Use this function to convert
#' `raw` content from such a file to an [AmigaBitmapFont()] object.
#'
#' This function converts `raw` data as stored in font bitmap
#' files. These files are stored in subdirectories with the font's
#' name and usually have the font height in pixels as file name.
#' This function is effectively the inverse of [AmigaFFH::as.raw()].
#'
#' @rdname rawToAmigaBitmapFont
#' @name rawToAmigaBitmapFont
#' @param x An [AmigaBitmapFont()] object which needs to be converted
#' into `raw` data.
#' @param ... Currently ignored.
#' @returns A `vector` of `raw` data representing `x`.
#' @examples
#' \dontrun{
#' ## first create raw data that can be converted into a AmigaBitmapFont
#' data(font_example)
#' font.raw <- as.raw(getAmigaBitmapFont(font_example, 9))
#'
#' ## Convert it back into an AmigaBitmapFont object:
#' font <- rawToAmigaBitmapFont(font.raw)
#' }
#' @family AmigaBitmapFont.operations
#' @family raw.operations
#' @author Pepijn de Vries
#' @export
rawToAmigaBitmapFont <- function(x, ...) {
result <- with(.amiga.font.header, .read.amigaData(x, byte, signed, par.names))
index.trailing.hunks <- (1 + 4*(.rawToAmigaInt(result$leadingHunks[21:24], 32, F) + 8))
## remove first part as it is not required for interpreting the data
## Check the leading hunks
result$leadingHunks[c(-21:-24, -29:-32)]
idx.check <- c(3,4,12,27,28,33,35,36)
if (any(result$leadingHunks[idx.check] != as.raw(c(0x03, 0xf3, 0x01, 0x03, 0xe9, 0x70, 0x4e, 0x75))) ||
any(result$leadingHunks[c(-21:-24, -29:-32, -34, -idx.check)] != raw(1)) ||
!(result$leadingHunks[34] %in% as.raw(c(0x00, 0x64, 0xff)))) {
warning("Unexpected file header. This file may not be a font bitmap.")
}
## remove leading hunks after checks. They are no longer needed...
result$leadingHunks <- NULL
if (index.trailing.hunks > length(x)) stop("Unexpected end of file")
## remove trailing hunks from data
trailing.hunks <- x[index.trailing.hunks:length(x)]
x <- x[1:(index.trailing.hunks - 1)]
result$dfh_FileID <- .match.factor(result, "dfh_FileID", 0xf80, "DFH_ID") ## Disk Font Header
result$tf_Style <- as.logical(.rawToBitmap(result$tf_Style, F, F))
names(result$tf_Style) <- c("UNDERLINED", "BOLD", "ITALIC", "EXTENDED", "RESERVED1", "RESERVED2", "COLORFONT", "TAGGED")
result$tf_Flags <- as.logical(.rawToBitmap(result$tf_Flags, F, F))
names(result$tf_Flags) <- c("ROMFONT", "DISKFONT", "REVPATH", "TALLDOT", "WIDEDOT", "PROPORTIONAL", "DESIGNED", "REMOVED")
result$node.disklink <- .read.amiga.node(result$node.disklink)
result$node.message <- .read.amiga.node(result$node.message)
result$fontName <- .rawToCharNull(result$fontName)
## mn_ReplyPort points to FontExtension. Current implementation ignores these extensions
n.glyphs <- 2 + result$tf_HiChar - result$tf_LoChar # +1 for difference in index base; another +1 for the default character
glyph.info <- .rawToAmigaInt(x[result$tf_CharLoc + 32 + (1:(4*n.glyphs))],
16, F)
# glyph.info <- as.data.frame(matrix(glyph.info, ncol = 2, byrow = T))
glyph.info <- as.data.frame(matrix(glyph.info, ncol = 2, byrow = T))
names(glyph.info) <- c("glyphLocation", "glyphWidth")
if (result$tf_CharSpace != 0) {
glyph.info$charSpace <- .rawToAmigaInt(x[result$tf_CharSpace + 32 + (1:(2*n.glyphs))],
16, T)
}
if (result$tf_CharKern != 0) {
glyph.info$charKern <- .rawToAmigaInt(x[result$tf_CharKern + 32 + (1:(2*n.glyphs))],
16, T)
}
result[["glyph.info"]] <- glyph.info
## trailing.hunks
trailing.hunks <- .rawToAmigaInt(trailing.hunks, 32, F)
hunk.dat <- c(2, 7, 19, 21, if(result$tf_CharSpace != 0) 22, if(result$tf_CharKern != 0) 23)
hunk.dat <- cumsum(abs(.amiga.font.header$byte[-1]))[hunk.dat - 1]
if (any(trailing.hunks[c(1, length(trailing.hunks))] != c(1004, 1010)) ||
trailing.hunks[2] != (length(trailing.hunks) - 5) ||
any(trailing.hunks[c(3, length(trailing.hunks) - 1)] != 0) ||
!all(trailing.hunks[4:(length(trailing.hunks) - 2)] %in% hunk.dat))
warning("Unexpected trailing file hunks.")
font.bitmap.data <- x[result$tf_CharData + 32 + (1:(result$tf_Modulo*result$tf_YSize))]
result[["bitmap"]] <- bitmapToRaster(font.bitmap.data,
w = result$tf_Modulo*8,
h = result$tf_YSize,
depth = 1, palette = c("white", "black"))
attr(result[["bitmap"]], "palette") <- c("white", "black")
class(result) <- "AmigaBitmapFont"
return(result)
}
#' @rdname plot
#' @name plot
#' @export
plot.AmigaBitmapFont <- function(x, y, ...) {
if (!inherits(x, "AmigaBitmapFont")) stop("x should be of class AmigaBitmapFont.")
args <- list(...)
raster.args <- list(x = x)
for (elm in c("text", "palette", "style")) {
raster.args[[elm]] <- args[[elm]]
args[[elm]] <- NULL
}
args$x <- do.call(as.raster, raster.args)
if (is.null(args$asp)) {
args$asp <- 1
if (x$tf_Flags["TALLDOT"]) args$asp <- args$asp*2
if (x$tf_Flags["WIDEDOT"]) args$asp <- args$asp/2
}
do.call(plot, args)
}
#' @rdname plot
#' @name plot
#' @export
plot.AmigaBitmapFontSet <- function(x, y, ...) {
if (!inherits(x, "AmigaBitmapFontSet")) stop("x should be of class AmigaBitmapFontSet.")
if (missing(y)) {
args <- list(...)
raster.args <- list(x = x)
for (elm in c("text", "palette", "style")) {
raster.args[[elm]] <- args[[elm]]
args[[elm]] <- NULL
}
args$x <- do.call(as.raster, raster.args)
if (is.null(args$asp)) {
dot <- do.call(rbind, lapply(x$FontContents, function(z) z$fc_Flags[c("TALLDOT", "WIDEDOT")]))
dot <- as.data.frame(table(as.data.frame(dot)))
dot <- dot[which(dot$Freq == max(dot$Freq))[[1]],]
args$asp <- 1
if (dot$TALLDOT == "TRUE") args$asp <- args$asp*2
if (dot$WIDEDOT == "TRUE") args$asp <- args$asp/2
}
do.call(plot, args)
} else {
plot(getAmigaBitmapFont(x, y), ...)
}
}
#' @export
print.AmigaBitmapFont <- function(x, ...) {
if (!inherits(x, "AmigaBitmapFont")) stop("x should be of class AmigaBitmapFont.")
cat(sprintf(" y-size %i, %s",
x$tf_YSize,
paste(tolower(c(names(x$tf_Flags)[x$tf_Flags],
names(x$tf_Style)[x$tf_Style])), collapse = ", ")))
cat("\n")
invisible(NULL)
}
#' @export
print.AmigaBitmapFontSet <- function(x, ...) {
if (!inherits(x, "AmigaBitmapFontSet")) stop("x should be of class AmigaBitmapFontSet.")
cat(fontName(x))
cat("\n")
lapply(x$FontContents, function(y) print(y$BitmapFont))
invisible(NULL)
}
#' @rdname as.raw
#' @name as.raw
#' @export
as.raw.AmigaBitmapFont <- function(x, ...) {
withCallingHandlers({ ## TODO remove handlers when replace functions are implemented
## initial checks. Throw errors when checks are unsuccessful
if (!inherits(x, "AmigaBitmapFont")) stop("x should be of class AmigaBitmapFont.")
max.loc <- max(x$glyph.info$glyphLocation)
if (max.loc + max(x$glyph.info$glyphWidth[x$glyph.info$glyphLocation == max.loc]) > dim(x$bitmap)[2]) {
stop("Glyph information exceeds bitmap dimensions!")
}
rm(max.loc)
if (x$tf_YSize != dim(x$bitmap)[1]) stop ("tf_YSize does not bitmap height.")
if (x$dfh_FileID != "DFH_ID") stop("Unexpected file ID...")
if ((x$tf_HiChar - x$tf_LoChar + 2) != nrow(x$glyph.info)) stop("Glyph information does not match the number of characters...")
if (x$tf_Modulo*8 != dim(x$bitmap)[2]) stop("tf_Modulo*8 does not equal the bitmap width.")
x$leadingHunks <- raw(36)
x$leadingHunks[c(3:4, 12, 27:28, 33:36)] <- as.raw(c(0x03, 0xF3, 0x01, 0x03, 0xE9, 0x70, 0x64, 0x4E, 0x75))
header <- x[.amiga.font.header$par.names]
header$node.disklink <- .amiga.node.to.raw(header$node.disklink)
header$node.message <- .amiga.node.to.raw(header$node.message)
header$dfh_FileID <- 0xF80
header$fontName <- charToRaw(header$fontName)[1:32]
header$tf_Style <- .bitmapToRaw(header$tf_Style, F, F)
header$tf_Flags <- .bitmapToRaw(header$tf_Flags, F, F)
header$tf_CharLoc <- 110 # This is where the first data always start
addToPointer <- 2*prod(dim(x$glyph.info[,c("glyphLocation", "glyphWidth"), drop = F]))
if (is.null(x$glyph.info$charSpace)) {
header$tf_CharSpace <- 0
} else {
header$tf_CharSpace <- header$tf_CharLoc + addToPointer
addToPointer <- 2*prod(dim(x$glyph.info[,"charSpace", drop = F]))
}
if (is.null(x$glyph.info$charKern)) {
header$tf_CharKern <- 0
} else {
header$tf_CharKern <- max(c(header$tf_CharLoc, header$tf_CharSpace)) + addToPointer
addToPointer <- 2*prod(dim(x$glyph.info[,"charKern", drop = F]))
}
header$tf_CharData <- max(with(header, c(tf_CharLoc, tf_CharSpace, tf_CharKern))) + addToPointer
## create HUNK_RELOC32 trailing relocator hunk. Points to relative
## addresses that contain relative pointers and should be reallocated when loaded in memory
## they are the nodes, the tf_CharData, tf_CharLoc, tf_CharSpace and tf_CharKern
## (the latter two are optional, and should only be included when not equal to 0)
trailing.hunks <- c(2, 7, 19, 21, if(header$tf_CharSpace != 0) 22, if(header$tf_CharKern != 0) 23)
trailing.hunks <- cumsum(abs(.amiga.font.header$byte[-1]))[trailing.hunks - 1]
trailing.hunks <- c(1004, # HUNK_RELOC32 id
length(trailing.hunks), # number of addresses to relocate
0, # hunk id number
trailing.hunks, # adresses
0, # terminator (no more data follows)
1010) # stop loading HUNKS
trailing.hunks <- .amigaIntToRaw(trailing.hunks, 32, F)
header <- with(.amiga.font.header,
.write.amigaData(header, byte, signed, par.names))
font.data <- .amigaIntToRaw(unlist(c(t(x$glyph.info[,c("glyphLocation", "glyphWidth")])), use.names = F), 16, F)
if (!is.null(x$glyph.info$charSpace))
font.data <- c(font.data, .amigaIntToRaw(x$glyph.info$charSpace, 16, T))
if (!is.null(x$glyph.info$charKern))
font.data <- c(font.data, .amigaIntToRaw(x$glyph.info$charKern, 16, T))
palette <- attr(x$bitmap, "palette")
bm <- apply(as.matrix(x$bitmap), 1, function(y) c(F, T)[match(y, palette)])
bm <- .bitmapToRaw(bm, invert.bytes = T, invert.longs = F)
font.data <- c(header, font.data, bm)
## Add padding bytes to align the data along 32 bit.
font.data <- font.data[1:(4*ceiling(length(font.data)/4))]
## specify in the leading hunks where the trailing hunks start:
font.data[c(21:24, 29:32)] <- .amigaIntToRaw(ceiling((length(font.data) - 32)/4), 32, F)
return(c(font.data, trailing.hunks))
},
warning=function(w) {
if (startsWith(conditionMessage(w), "Replacement operator for AmigaBitmapFont"))
invokeRestart("muffleWarning")
})
}
#' @rdname as.raw
#' @name as.raw
#' @export
as.raw.AmigaBitmapFontSet <- function(x, ...) {
withCallingHandlers({ ## TODO remove handlers when replace functions are implemented
if (!inherits(x, "AmigaBitmapFontSet")) stop("x should be of class AmigaBitmapFontSet.")
if (x$fch_FileID != "FontContents") stop("Sorry, currently only 'FontContents' font sets are supported.")
## put list in correct order...
x <- x[c("fch_FileID", "fch_NumEntries", "FontContents")]
.as.raw.FontContents <- function(y) {
y <- y[c("fc_FileName", "fc_YSize", "fc_Style", "fc_Flags")]
y$fc_FileName <- charToRaw(y$fc_FileName)[1:256]
y$fc_YSize <- .amigaIntToRaw(y$fc_YSize, 16, F)
y$fc_Style <- .bitmapToRaw(y$fc_Style, F, F)
y$fc_Flags <- .bitmapToRaw(y$fc_Flags, F, F)
unlist(y, use.names = F)
}
x$FontContents <- unlist(lapply(x$FontContents, .as.raw.FontContents), use.names = F)
x$fch_FileID <- c(0x0f00, 0x0f02, 0x0f03)[match(as.character(x$fch_FileID), .amiga.font.types)]
x$fch_FileID <- .amigaIntToRaw(x$fch_FileID, 16, F)
x$fch_NumEntries <- .amigaIntToRaw(x$fch_NumEntries, 16, F)
return(unlist(x, use.names = F))
},
warning=function(w) {
if (startsWith(conditionMessage(w), "Replacement operator for AmigaBitmapFont"))
invokeRestart("muffleWarning")
})
}
#' @param text Text (a `character` string) to be formated
#' with `x` (when `x` is an [AmigaBitmapFont()]
#' or an [AmigaBitmapFontSet()].
#' @param style Argument is only valid when `x` is an [AmigaBitmapFont()]
#' or an [AmigaBitmapFontSet()]. No styling is applied
#' when missing or `NULL`. One or more of the following styles
#' can be used '`bold`', '`italic` or '`underlined`'.
#' @param palette Argument is only valid when `x` is an [AmigaBitmapFont()]
#' or an [AmigaBitmapFontSet()]. Should be a `vector` of
#' two colours. The first is element is used as background colour, the
#' second as foreground. When missing, transparent white and black are used.
#' @family raster.operations
#' @rdname as.raster
#' @name as.raster
#' @export
as.raster.AmigaBitmapFont <- function(x, text, style, palette, ...) {
if (!inherits(x, "AmigaBitmapFont")) stop("x should be of class AmigaBitmapFont.")
if (missing(text)) return(x$bitmap)
if (missing(style)) style <- NULL
if (missing(palette)) palette <- NULL
.print_to_raster(text, x, style, palette)
}
#' @family raster.operations
#' @rdname as.raster
#' @name as.raster
#' @export
as.raster.AmigaBitmapFontSet <- function(x, text, style, palette, ...) {
if (!inherits(x, "AmigaBitmapFontSet")) stop("x should be of class AmigaBitmapFontSet.")
if (missing(text)) {
dims <- do.call(rbind, lapply(x$FontContents, function(y) dim(y$BitmapFont$bitmap)))
pals <- do.call(rbind, lapply(x$FontContents, function(y) attr(y$BitmapFont$bitmap, "palette")))
if (!all(apply(pals, 2, function(y) all(y == y[1])))) stop("No consitent palettes used for bitmaps in the font set")
result <- matrix(pals[1,1], sum(dims[,1]), max(dims[,2]))
y.offset <- c(0, cumsum(dims[,1]))
lapply(1:length(x$FontContents), function(y) {
ys <- x$FontContents[[y]]$BitmapFont$tf_YSize
xs <- ncol(x$FontContents[[y]]$BitmapFont$bitmap)
result[y.offset[y] + (1:ys), 1:xs] <<- as.matrix(x$FontContents[[y]]$BitmapFont$bitmap)
})
result <- grDevices::as.raster(result)
return(result)
}
if (missing(style)) style <- NULL
if (missing(palette)) palette <- NULL
.print_to_raster(text, x, style, palette)
}
#' Combine multiple AmigaFFH objects
#'
#' Use this function to correctly combine one or more [AmigaBitmapFont()]
#' class objects into a single [AmigaBitmapFontSet()] class
#' object, or to combine multiple [AmigaBasic()] class objects.
#'
#' In case `...` are one or more [AmigaBasic()] class objects:
#'
#' [AmigaBasic()] class objects are combined into a single
#' [AmigaBasic()] class object in the same order as they
#' are given as argument to this function. for this purpose the lines of
#' Amiga Basic codes are simply concatenated.
#'
#' In case `...` are one or more [AmigaBitmapFont()] class objects:
#'
#' [AmigaBitmapFontSet()] class objects can hold multiple
#' [AmigaBitmapFont()] class objects. Use this method to
#' combine font bitmaps into such a font set. Make sure each bitmap
#' represents a unique font height (in pixels). When heights are duplicated
#' an error will be thrown.
#'
#' You can also specify a `name` for the font, that will be embeded
#' in the object. As this name will also be used as a file name when
#' writing the font to a file, make sure that it is a valid filename.
#'
#' @rdname c
#' @name c
#' @param ... Either [AmigaBasic()] or [AmigaBitmapFont()]
#' class objects. In case of [AmigaBitmapFont()] objects:
#' Each [AmigaBitmapFont()] object should have a
#' unique Y-size.
#' @param name This argument is only valid when `...` are one or more
#' [AmigaBitmapFont()] class objects.
#'
#' A `character` string specifying the name that needs to be
#' applied to the font set. When unspecified, the default name 'font' is
#' used. Note that this name will also be used as a file name when writing
#' the font to a file. So make sure the name is also a valid file name. This
#' will not be checked for you and may thus result in errors.
#' @returns Returns an [AmigaBitmapFontSet()] in which the
#' [AmigaBitmapFont()] objects are combined. Or when [AmigaBasic()]
#' objects are combined, an [AmigaBasic()] object is returned
#' in which the lines of Amiga Basic code are combined.
#' @examples
#' \dontrun{
#' data(font_example)
#'
#' ## first get some AmigaBitmapFont objects:
#' font8 <- getAmigaBitmapFont(font_example, 8)
#' font9 <- getAmigaBitmapFont(font_example, 9)
#'
#' ## now bind these bitmaps again in a single set
#' font.set <- c(font8, font9, name = "my_font_name")
#'
#' ## Amiga Basic codes can also be combined:
#' bas1 <- as.AmigaBasic("LET a = 1")
#' bas2 <- as.AmigaBasic("PRINT a")
#' bas <- c(bas1, bas2)
#' }
#' @family AmigaBitmapFont.operations
#' @author Pepijn de Vries
#' @export
c.AmigaBitmapFont <- function(..., name = "font") {
fonts <- list(...)
lapply(fonts, function(f) {
if (!inherits(f, "AmigaBitmapFont")) stop("'...' should be all of class AmigaBitmapFont.")
})
sz <- unlist(lapply(fonts, function(x) x$tf_YSize))
if (any(duplicated(sz))) stop("The font Y-sizes are not unique.")
fonts <- fonts[order(sz)]
result <- list(
fch_FileID = factor(.amiga.font.types[1],
.amiga.font.types),
fch_NumEntries = length(fonts),
FontContents = lapply(fonts, function(x) {
list(
fc_FileName = paste(name, x$tf_YSize, sep = "/"),
fc_YSize = x$tf_YSize,
fc_Style = x$tf_Style,
fc_Flags = x$tf_Flags,
BitmapFont = x
)
})
)
names(result$FontContents) <- sprintf("pt%i", sort(sz))
class(result) <- "AmigaBitmapFontSet"
result
}
#' Extract or replace a font name
#'
#' Extract or replace a font name from an [AmigaBitmapFontSet()]
#' object.
#'
#' The name of a font is embeded at multiple locations of an [AmigaBitmapFontSet()]
#' object. This function can be used to extract or replace the font name
#' correctly. This is also the name that will be used when writing the
#' font to a file with [write.AmigaBitmapFontSet()].