font-out.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/binary"
  5. "flag"
  6. "fmt"
  7. "os"
  8. "strconv"
  9. "strings"
  10. )
  11. var Conversion [][2]int
  12. // copied from tdfont.go, and modified
  13. func thedraw_to_ansi(c int) int {
  14. trans := []int{0, 4, 2, 6, 1, 5, 3, 7}
  15. // 0, 1, 2, 3, 4, 5, 6, 7
  16. return trans[c]
  17. }
  18. func MatchStyle(color byte, look byte) int {
  19. var match int = 0
  20. if ((color >> 4) & 0x07) == look {
  21. // Top
  22. match |= 1
  23. }
  24. if (color & 0x07) == look {
  25. // Bottom
  26. match |= 2
  27. }
  28. return match
  29. }
  30. func PatchColor(color byte, new_color byte, style int) byte {
  31. var c byte = color
  32. if style&1 == 1 {
  33. c = (c & 0x8f) | new_color<<4
  34. }
  35. if style&2 == 2 {
  36. c = (c & 0xf8) | new_color
  37. }
  38. return c
  39. }
  40. type ColorMap map[[2]int][][2]int
  41. func Scan(block [][][]byte, find_color int) ColorMap {
  42. var Targets ColorMap = make(ColorMap, 0)
  43. // Scan the font looking for the given color FG/BG
  44. // Covert color code to TheDraw Color
  45. actual := byte(thedraw_to_ansi(find_color))
  46. for charIndex := range block {
  47. for lineIndex := range block[charIndex] {
  48. var found bool = false
  49. var patches [][2]int = make([][2]int, 0)
  50. for offset := 1; offset < len(block[charIndex][lineIndex]); offset += 2 {
  51. color := block[charIndex][lineIndex][offset]
  52. style := MatchStyle(color, actual)
  53. if style != 0 {
  54. // log.Printf("color: %x actual %x style: %d\n", color, actual, style)
  55. patches = append(patches, [2]int{offset, style})
  56. found = true
  57. }
  58. }
  59. if found {
  60. pos := [2]int{charIndex, lineIndex}
  61. Targets[pos] = make([][2]int, len(patches))
  62. for i := range patches {
  63. Targets[pos][i] = patches[i]
  64. }
  65. // Targets[pos] = patches
  66. }
  67. }
  68. }
  69. return Targets
  70. }
  71. func Modify(block [][][]byte, new_color int, Targets ColorMap) {
  72. // Covert color code to TheDraw Color
  73. actual := byte(thedraw_to_ansi(new_color))
  74. for pos, patch := range Targets {
  75. for _, p := range patch {
  76. block[pos[0]][pos[1]][p[0]] = PatchColor(block[pos[0]][pos[1]][p[0]], actual, p[1])
  77. }
  78. }
  79. }
  80. func ListFonts(filename string) {
  81. f, err := os.Open(filename)
  82. if err != nil {
  83. fmt.Printf("Open(%s): %s\n", filename, err)
  84. panic(err)
  85. }
  86. defer f.Close()
  87. tdfonts := make([]byte, 20)
  88. f.Read(tdfonts)
  89. for true {
  90. fontdef := make([]byte, 4)
  91. read, _ := f.Read(fontdef)
  92. if read != 4 {
  93. fmt.Println("*END*")
  94. break
  95. }
  96. fontname := make([]byte, 13)
  97. f.Read(fontname)
  98. Name := strings.Trim(string(fontname[1:]), "\x00")
  99. // fmt.Printf("Font: %s\n", Name)
  100. f.Read(fontdef)
  101. single := make([]byte, 1)
  102. var FontType int8
  103. binary.Read(f, binary.LittleEndian, &FontType)
  104. // f.Read(single) // FontType
  105. // FontType := int(single[0])
  106. fmt.Printf("Font: %s (type %d)\n", Name, FontType)
  107. f.Read(single) // Spacing
  108. // blocksize := make([]byte, 2)
  109. // f.Read(blocksize)
  110. var BlockSize int16
  111. binary.Read(f, binary.LittleEndian, &BlockSize)
  112. // fmt.Printf("Size: %d / %x\n", BlockSize, BlockSize)
  113. letterOffsets := make([]int16, 94)
  114. binary.Read(f, binary.LittleEndian, &letterOffsets)
  115. if false {
  116. for idx, i := range letterOffsets {
  117. fmt.Printf(" %04X", i)
  118. if (idx+1)%10 == 0 {
  119. fmt.Println("")
  120. }
  121. }
  122. fmt.Println("")
  123. }
  124. data := make([]byte, BlockSize)
  125. binary.Read(f, binary.LittleEndian, &data)
  126. }
  127. }
  128. func byte_to_text(line []byte) string {
  129. var output string
  130. for _, ch := range line {
  131. output += fmt.Sprintf("0x%02x,", ch)
  132. }
  133. if len(output) > 0 {
  134. output = output[:len(output)-1]
  135. }
  136. return output
  137. }
  138. func text_to_hextext(line string) string {
  139. var output string
  140. // output = "\""
  141. for _, ch := range []byte(line) {
  142. // output += fmt.Sprintf("\\x%02x", ch)
  143. output += fmt.Sprintf("0x%02x,", ch)
  144. }
  145. if len(output) > 1 {
  146. output = output[:len(output)-1]
  147. }
  148. // output += "\""
  149. return output
  150. }
  151. func ExtractColor(name string, offsets []uint16, data []byte) {
  152. // fmt.Printf("Extract Color Font: %s\n", name)
  153. var indexes []int
  154. var blocks [][][]byte
  155. var current [][]byte
  156. var line []byte
  157. pos := 0
  158. for pos < len(data) {
  159. indexes = append(indexes, pos)
  160. current = make([][]byte, 0)
  161. line = make([]byte, 0)
  162. // We don't use these.
  163. // w = data[pos]
  164. // h = data[pos+1]
  165. pos += 2
  166. // process this character
  167. for pos < len(data) {
  168. ch := data[pos]
  169. pos++
  170. if ch == 0x00 {
  171. // end of character
  172. current = append(current, line)
  173. blocks = append(blocks, current)
  174. current = make([][]byte, 0)
  175. line = make([]byte, 0)
  176. break
  177. }
  178. if ch == 0x0d {
  179. // end of this character line
  180. current = append(current, line)
  181. line = make([]byte, 0)
  182. continue
  183. }
  184. if ch == 0x26 {
  185. // & descender mark
  186. continue
  187. }
  188. line = append(line, ch)
  189. color := data[pos]
  190. pos++
  191. line = append(line, color)
  192. }
  193. }
  194. // offset optimization:
  195. var single []int
  196. for _, o := range offsets {
  197. if o == 65535 {
  198. single = append(single, -1)
  199. continue
  200. }
  201. for idx, i := range indexes {
  202. if o == uint16(i) {
  203. single = append(single, idx)
  204. break
  205. }
  206. }
  207. }
  208. /*
  209. // Handle Names with spaces
  210. filename := fmt.Sprintf("%s_font.go", strings.Replace(name, " ", "", -1))
  211. fp, err := os.Create(filename)
  212. if err != nil {
  213. panic(err)
  214. }
  215. fmt.Printf("Writing: %s\n", filename)
  216. defer fp.Close()
  217. writer := bufio.NewWriter(fp)
  218. */
  219. writer := bufio.NewWriter(os.Stdout)
  220. // writer.WriteString("package main\n")
  221. writer.WriteString("// " + name + "\n\n")
  222. // Name := strings.ToUpper(name)
  223. Name := strings.Replace(name, " ", "", -1)
  224. writer.WriteString("func Font" + Name + "() door.ColorFont {\n")
  225. var output string
  226. output = " return door.ColorFont{Characters: []int{"
  227. for _, s := range single {
  228. output += strconv.Itoa(s) + ", "
  229. }
  230. output = output[:len(output)-2] + "},\n"
  231. writer.WriteString(output)
  232. writer.Flush()
  233. if len(Conversion) > 0 {
  234. // Color Convert time!
  235. var Maps []map[[2]int][][2]int = make([]map[[2]int][][2]int, len(Conversion))
  236. for idx, codes := range Conversion {
  237. Maps[idx] = Scan(blocks, codes[0])
  238. }
  239. for idx, codes := range Conversion {
  240. Modify(blocks, codes[1], Maps[idx])
  241. }
  242. }
  243. output = " Data: [][][]byte{"
  244. for _, blk := range blocks {
  245. output += "{"
  246. if len(blk) == 0 {
  247. output += "{},"
  248. } else {
  249. for _, inner := range blk {
  250. // output += text_to_hextext(b) + ","
  251. output += "{" + byte_to_text(inner) + "},"
  252. }
  253. output = output[:len(output)-1]
  254. }
  255. output += "},\n"
  256. writer.WriteString(output)
  257. output = " "
  258. }
  259. writer.WriteString(" }}\n")
  260. writer.WriteString("}\n")
  261. writer.Flush()
  262. }
  263. func ExtractBlock(name string, offsets []uint16, data []byte) {
  264. // fmt.Printf("Extract Block Font: %s\n", name)
  265. var indexes []int
  266. var blocks [][][]byte
  267. var current [][]byte
  268. var line []byte
  269. pos := 0
  270. for pos < len(data) {
  271. indexes = append(indexes, pos)
  272. current = make([][]byte, 0)
  273. line = make([]byte, 0)
  274. // We don't use these
  275. // w = data[pos]
  276. // h = data[pos+1]
  277. pos += 2
  278. // process this character
  279. for pos < len(data) {
  280. ch := data[pos]
  281. pos++
  282. if ch == 0x00 {
  283. // end of character
  284. current = append(current, line)
  285. blocks = append(blocks, current)
  286. current = make([][]byte, 0)
  287. line = make([]byte, 0)
  288. break
  289. }
  290. if ch == 0x0d {
  291. // end of this character line
  292. current = append(current, line)
  293. line = make([]byte, 0)
  294. continue
  295. }
  296. if ch == 0x26 {
  297. // & descender mark
  298. continue
  299. }
  300. line = append(line, ch)
  301. }
  302. }
  303. // offset optimization:
  304. var single []int
  305. for _, o := range offsets {
  306. if o == 65535 {
  307. single = append(single, -1)
  308. continue
  309. }
  310. for idx, i := range indexes {
  311. if o == uint16(i) {
  312. single = append(single, idx)
  313. break
  314. }
  315. }
  316. }
  317. /*
  318. // Handle Names with spaces
  319. filename := fmt.Sprintf("%s_font.go", strings.Replace(name, " ", "", -1))
  320. fp, err := os.Create(filename)
  321. if err != nil {
  322. panic(err)
  323. }
  324. fmt.Printf("Writing: %s\n", filename)
  325. defer fp.Close()
  326. writer := bufio.NewWriter(fp)
  327. */
  328. writer := bufio.NewWriter(os.Stdout)
  329. // Should this output routine be part of the BlockFont?
  330. // I think so!
  331. // writer.WriteString("package main\n")
  332. writer.WriteString("// " + name + "\n\n")
  333. // Name := strings.ToUpper(name)
  334. Name := strings.Replace(name, " ", "", -1)
  335. writer.WriteString("func Font" + Name + "() door.BlockFont {\n")
  336. var output string
  337. output = " return door.BlockFont{Characters: []int{"
  338. for _, s := range single {
  339. output += strconv.Itoa(s) + ", "
  340. }
  341. output = output[:len(output)-2] + "},\n"
  342. writer.WriteString(output)
  343. writer.Flush()
  344. output = " Data: [][][]byte{"
  345. for _, blk := range blocks {
  346. output += "{"
  347. if len(blk) == 0 {
  348. output += "{},"
  349. } else {
  350. for _, inner := range blk {
  351. output += "{" + byte_to_text(inner) + "},"
  352. }
  353. output = output[:len(output)-1]
  354. }
  355. output += "},\n"
  356. // output = output[:len(output)-1]
  357. // output += "},\n"
  358. writer.WriteString(output)
  359. output = " "
  360. }
  361. writer.WriteString(" }}\n")
  362. writer.WriteString("}\n")
  363. writer.Flush()
  364. }
  365. func ExtractFonts(filename string, fonts []string) {
  366. f, err := os.Open(filename)
  367. if err != nil {
  368. fmt.Printf("Open(%s): %s\n", filename, err)
  369. panic(err)
  370. }
  371. defer f.Close()
  372. tdfonts := make([]byte, 20)
  373. f.Read(tdfonts)
  374. for true {
  375. fontdef := make([]byte, 4)
  376. read, _ := f.Read(fontdef)
  377. if read != 4 {
  378. break
  379. }
  380. fontname := make([]byte, 13)
  381. f.Read(fontname)
  382. Name := strings.Trim(string(fontname[1:]), "\x00")
  383. // fmt.Printf("Font: %s\n", Name)
  384. f.Read(fontdef)
  385. single := make([]byte, 1)
  386. var FontType int8
  387. binary.Read(f, binary.LittleEndian, &FontType)
  388. // fmt.Printf("Font: %s (type %d)\n", Name, FontType)
  389. f.Read(single) // Spacing
  390. var BlockSize int16
  391. binary.Read(f, binary.LittleEndian, &BlockSize)
  392. letterOffsets := make([]uint16, 94)
  393. binary.Read(f, binary.LittleEndian, &letterOffsets)
  394. if false {
  395. for idx, i := range letterOffsets {
  396. fmt.Printf(" %04X", i)
  397. if (idx+1)%10 == 0 {
  398. fmt.Println("")
  399. }
  400. }
  401. fmt.Println("")
  402. }
  403. data := make([]byte, BlockSize)
  404. binary.Read(f, binary.LittleEndian, &data)
  405. // Special case where they are asking for all fonts
  406. if len(fonts) == 1 && fonts[0] == "*" {
  407. switch FontType {
  408. case 1:
  409. ExtractBlock(Name, letterOffsets, data)
  410. case 2:
  411. ExtractColor(Name, letterOffsets, data)
  412. default:
  413. fmt.Printf("// Sorry, I can't handle Font: %s Type %d!\n", Name, FontType)
  414. }
  415. } else {
  416. for _, f := range fonts {
  417. if Name == f {
  418. switch FontType {
  419. case 1:
  420. ExtractBlock(Name, letterOffsets, data)
  421. case 2:
  422. ExtractColor(Name, letterOffsets, data)
  423. default:
  424. fmt.Printf("// Sorry, I can't handle Font: %s Type %d!\n", Name, FontType)
  425. }
  426. break
  427. }
  428. }
  429. }
  430. }
  431. }
  432. // Created so that multiple inputs can be accecpted
  433. type arrayFlags []string
  434. func (i *arrayFlags) String() string {
  435. // change this, this is just can example to satisfy the interface
  436. result := ""
  437. for _, str := range *i {
  438. if result != "" {
  439. result += ", "
  440. }
  441. result += str
  442. }
  443. return result
  444. }
  445. func (i *arrayFlags) Set(value string) error {
  446. *i = append(*i, strings.TrimSpace(value))
  447. return nil
  448. }
  449. func ParseColorConvert(convert arrayFlags) {
  450. Conversion = make([][2]int, 0)
  451. if len(convert) > 0 {
  452. // Something to do
  453. for _, color := range convert {
  454. split := strings.Split(color, ",")
  455. v1, _ := strconv.Atoi(split[0])
  456. v2, _ := strconv.Atoi(split[1])
  457. Conversion = append(Conversion, [2]int{v1, v2})
  458. }
  459. }
  460. }
  461. func main() {
  462. var fonts string
  463. var defaultPackage string = "main"
  464. var listFonts bool
  465. var allFonts bool
  466. var convert arrayFlags
  467. flag.StringVar(&fonts, "f", "", "Font(s) to extract")
  468. flag.BoolVar(&allFonts, "a", false, "Extract All Fonts")
  469. flag.StringVar(&defaultPackage, "p", "main", "Package name to use")
  470. flag.BoolVar(&listFonts, "l", false, "List Fonts")
  471. flag.Var(&convert, "c", "Convert Color to Color n,n")
  472. flag.Parse()
  473. ParseColorConvert(convert)
  474. // fmt.Printf("Convert: %#v\n", convert)
  475. // fmt.Printf("Conversion: %#v\n", Conversion)
  476. if flag.NArg() == 0 {
  477. fmt.Println("Font-Out - A TDF (TheDraw Font) file processor.")
  478. fmt.Println("No TDF filenames given.")
  479. flag.PrintDefaults()
  480. os.Exit(2)
  481. }
  482. if !listFonts {
  483. fmt.Printf("package %s\n\n", defaultPackage)
  484. fmt.Println("import (")
  485. fmt.Println(" \"red-green/door\"")
  486. fmt.Println(")")
  487. fmt.Println("")
  488. } else {
  489. fmt.Println("Font-Out - A TDF (TheDraw Font) file processor.")
  490. }
  491. var fontList []string
  492. if len(fonts) > 0 {
  493. fontList = strings.Split(fonts, ",")
  494. }
  495. if allFonts {
  496. fontList = make([]string, 0)
  497. fontList = append(fontList, "*")
  498. }
  499. if !listFonts && len(fontList) == 0 {
  500. fmt.Println("Default to -l (List Fonts)")
  501. listFonts = true
  502. }
  503. for _, fontfile := range flag.Args() {
  504. if listFonts {
  505. ListFonts(fontfile)
  506. } else {
  507. if len(fontList) > 0 {
  508. ExtractFonts(fontfile, fontList)
  509. }
  510. }
  511. }
  512. }