Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/checkout@v4

- name: Download artifacts
uses: actions/download-artifact@v4
with:
Expand All @@ -89,13 +91,42 @@ jobs:
mkdir -p release
find dist -maxdepth 3 -type f -print -exec cp {} release/ \;

- name: Package release archives
run: |
set -euo pipefail

version="${GITHUB_REF_NAME}"
mkdir -p packaged

for file in release/*; do
base="$(basename "${file}")"
stem="${base%.exe}"
stage_dir="$(mktemp -d)"

cp "${file}" "${stage_dir}/"
cp README.md LICENSE THIRD_PARTY_NOTICES.md "${stage_dir}/"

if [[ "${base}" == *.exe ]]; then
asset="packaged/${stem}-${version}.zip"
(
cd "${stage_dir}"
zip -q -r "${GITHUB_WORKSPACE}/${asset}" .
)
else
asset="packaged/${stem}-${version}.tar.gz"
tar -C "${stage_dir}" -czf "${asset}" .
fi

rm -rf "${stage_dir}"
done

- name: Publish GitHub release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: ${{ github.ref_name }}
generate_release_notes: true
fail_on_unmatched_files: true
files: release/*
files: packaged/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.vscode/*
out_font/*
*.xnb
*.fnt
/ra2fnt
/ra2fnt.exe
Expand Down
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ Create `.fnt` from PNG set:
./ra2fnt create -in out_font -out rebuilt.fnt
```

Create an experimental LZ4-compressed `SpriteFont XNB v5` font file compatible with [`xna-cncnet-client`](https://github.com/CnCNet/xna-cncnet-client) from PNG set:

```bash
./ra2fnt create -in out_font -out SpriteFont.xnb --format spritefont-xnb
```

Create without glyph deduplication:

```bash
Expand Down Expand Up @@ -107,7 +113,7 @@ Zero-width glyphs are listed only in `metadata.json` (`symbol_width`).

## Create behavior

`create` reconstructs a `.fnt` from PNG files in the input directory:
`create` reconstructs a font file from PNG files in the input directory:

- PNG files are discovered recursively (subdirectory names are ignored by parser).
- Files must be named as fixed-length hex codepoints (for example `0x0041.png`, `0x30A1.png`).
Expand All @@ -120,6 +126,9 @@ Zero-width glyphs are listed only in `metadata.json` (`symbol_width`).
- `ideograph_width` is taken from `metadata.json`.
- `scale` is taken from `metadata.json`; when `scale > 1`, PNG dimensions are downscaled by this factor during `create` (back to normal font size).
- Identical glyphs are deduplicated, so multiple codepoints can reference the same symbol index.
- Output format is selected by `--format`:
- `fnt` (default): writes Westwood Unicode BitFont `.fnt`
- `spritefont-xnb`: writes an experimental LZ4-compressed `SpriteFont XNB v5` `.xnb` font file compatible with [`xna-cncnet-client`](https://github.com/CnCNet/xna-cncnet-client)
- Use `--no-dedup` to disable deduplication.
- Unicode table is rebuilt from filenames (`0xXXXX` -> symbol index in sorted codepoint order).

Expand All @@ -141,3 +150,11 @@ Because unicode mapping order/tail bytes are rebuilt, the resulting `.fnt` is no
- At least one non-zero-width PNG is required to infer `symbol_height`.
- Zero-width glyphs are represented only in `metadata.json` and have no PNG files.
- Unicode table order is rebuilt from sorted codepoints.
- `spritefont-xnb` always writes LZ4-compressed `SpriteFont XNB v5`.
- `spritefont-xnb` is an experimental feature.
- When `?` is present, `spritefont-xnb` writes it as `defaultChar` fallback.

## License

- Project license: `MIT` (see `LICENSE`)
- Third-party notices: `THIRD_PARTY_NOTICES.md`
41 changes: 41 additions & 0 deletions THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Third-Party Notices

This project is licensed under the MIT License. It also includes or depends on third-party components under their own licenses.

## `github.com/pierrec/lz4/v4`

- Project: `github.com/pierrec/lz4/v4`
- License: `BSD-3-Clause`
- Source: `https://github.com/pierrec/lz4`

License text:

```text
Copyright (c) 2015, Pierre Curto
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of xxHash nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module ra2fnt

go 1.22

require github.com/pierrec/lz4/v4 v4.1.26
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=
github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
29 changes: 21 additions & 8 deletions src/cmd/ra2fnt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"

"ra2fnt/src/internal/fnt"
"ra2fnt/src/internal/fontout"
"ra2fnt/src/internal/pngset"
)

Expand Down Expand Up @@ -75,6 +76,7 @@ func (bar *progressBar) Update(stage string, done, total int) {
func (bar *progressBar) Finish() {
if bar.printed {
fmt.Fprintln(os.Stderr)
bar.printed = false
}
}

Expand Down Expand Up @@ -168,6 +170,7 @@ func runExport(args []string) error {
}); err != nil {
return err
}
progress.Finish()

mappedCodepoints := 0
for _, symbolIndex := range font.UnicodeTable {
Expand All @@ -176,8 +179,9 @@ func runExport(args []string) error {
}
}

fmt.Printf(
" exported %d codepoints to %s (source symbols: %d)\n",
fmt.Fprintf(
os.Stderr,
"exported %d codepoints to %s (source symbols: %d)\n",
mappedCodepoints,
*outDir,
font.SymbolsCount,
Expand Down Expand Up @@ -224,7 +228,8 @@ func ensureExportOutDir(outDir string, input io.Reader, output io.Writer, force
func runCreate(args []string) error {
fs := flag.NewFlagSet("create", flag.ContinueOnError)
inDir := fs.String("in", "", "input directory created by export")
outPath := fs.String("out", "", "output .fnt file")
outPath := fs.String("out", "", "output font file")
format := fs.String("format", fontout.FormatFNT, "create output format: fnt, spritefont-xnb")
noDedup := fs.Bool("no-dedup", false, "disable glyph deduplication")
fs.SetOutput(os.Stderr)

Expand All @@ -235,6 +240,10 @@ func runCreate(args []string) error {
fs.Usage()
return fmt.Errorf("-in and -out are required")
}
outputFormat, err := fontout.NormalizeFormat(*format)
if err != nil {
return err
}

options := pngset.ImportOptions{}
options.DisableDedup = *noDedup
Expand All @@ -247,15 +256,18 @@ func runCreate(args []string) error {
if err != nil {
return err
}
if err := fnt.WriteFile(*outPath, font); err != nil {
if err := fontout.WriteFile(*outPath, font, outputFormat); err != nil {
return err
}
progress.Finish()

fmt.Printf(
"created %d symbols from %d codepoints in %s (deduplicated: %d)\n",
fmt.Fprintf(
os.Stderr,
"created %d symbols from %d codepoints in %s (%s, deduplicated: %d)\n",
report.UniqueSymbols,
report.Codepoints,
*outPath,
outputFormat,
report.DeduplicatedSymbols,
)
return nil
Expand All @@ -282,7 +294,8 @@ func runValidate(args []string) error {
return err
}

fmt.Printf(
fmt.Fprintf(
os.Stderr,
"validation passed: codepoints=%d, png=%d, zero_width=%d, symbols=%d, deduplicated=%d\n",
report.Codepoints,
report.PNGFiles,
Expand All @@ -296,7 +309,7 @@ func runValidate(args []string) error {
func usage() {
fmt.Fprintf(os.Stderr, "Usage:\n")
fmt.Fprintf(os.Stderr, " %s export -in game.fnt -out out_dir [--scale N] [--force]\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s create -in out_dir -out rebuilt.fnt\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s create -in out_dir -out output_file [--format fnt|spritefont-xnb]\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s validate -in out_dir\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s version\n", os.Args[0])
fmt.Fprintf(os.Stderr, " %s --version\n", os.Args[0])
Expand Down
105 changes: 105 additions & 0 deletions src/cmd/ra2fnt/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ package main

import (
"bytes"
"encoding/binary"
"image/png"
"io"
"os"
"path/filepath"
"strings"
"testing"

"github.com/pierrec/lz4/v4"

"ra2fnt/src/internal/fnt"
"ra2fnt/src/internal/fontout"
)

func TestEnsureExportOutDirNotExists(t *testing.T) {
Expand Down Expand Up @@ -220,6 +225,62 @@ func TestRunValidateAcceptsNoDedupFlag(t *testing.T) {
}
}

func TestRunCreateSpriteFontXNB(t *testing.T) {
root := t.TempDir()
inPath := filepath.Join(root, "in.fnt")
outDir := filepath.Join(root, "out")
outPath := filepath.Join(root, "font.xnb")
if err := writeSampleFont(inPath); err != nil {
t.Fatalf("write sample font: %v", err)
}

if err := runExport([]string{"-in", inPath, "-out", outDir}); err != nil {
t.Fatalf("runExport: %v", err)
}
if err := runCreate([]string{"-in", outDir, "-out", outPath, "-format", fontout.FormatSpriteFontXNB}); err != nil {
t.Fatalf("runCreate spritefont-xnb: %v", err)
}

raw, err := os.ReadFile(outPath)
if err != nil {
t.Fatalf("read created xnb: %v", err)
}
if got, want := string(raw[:3]), "XNB"; got != want {
t.Fatalf("xnb magic mismatch: got=%q want=%q", got, want)
}
if got, want := raw[3], byte('w'); got != want {
t.Fatalf("xnb platform mismatch: got=%q want=%q", got, want)
}
if got, want := raw[4], byte(5); got != want {
t.Fatalf("xnb version mismatch: got=%d want=%d", got, want)
}
if got, want := raw[5], byte(0x40); got != want {
t.Fatalf("xnb flags mismatch: got=%d want=%d", got, want)
}
if got, want := int(binary.LittleEndian.Uint32(raw[10:14])), len(decompressLZ4Block(t, raw[14:], int(binary.LittleEndian.Uint32(raw[10:14])))); got != want {
t.Fatalf("xnb decompressed size mismatch: got=%d want=%d", got, want)
}
}

func TestRunCreateRejectsUnsupportedFormat(t *testing.T) {
root := t.TempDir()
inPath := filepath.Join(root, "in.fnt")
outDir := filepath.Join(root, "out")
outPath := filepath.Join(root, "font.bin")
if err := writeSampleFont(inPath); err != nil {
t.Fatalf("write sample font: %v", err)
}

if err := runExport([]string{"-in", inPath, "-out", outDir}); err != nil {
t.Fatalf("runExport: %v", err)
}

err := runCreate([]string{"-in", outDir, "-out", outPath, "-format", "unknown"})
if err == nil || !strings.Contains(err.Error(), "unsupported create format") {
t.Fatalf("expected unsupported format error, got: %v", err)
}
}

func writeSampleFont(path string) error {
font := &fnt.Font{
IdeographWidth: 8,
Expand Down Expand Up @@ -247,3 +308,47 @@ func TestVersionString(t *testing.T) {
t.Fatalf("version string mismatch: got=%q want=%q", got, want)
}
}

func TestProgressBarFinishIsIdempotent(t *testing.T) {
readPipe, writePipe, err := os.Pipe()
if err != nil {
t.Fatalf("os.Pipe: %v", err)
}
defer readPipe.Close()

oldStderr := os.Stderr
os.Stderr = writePipe
defer func() {
os.Stderr = oldStderr
}()

bar := newProgressBar("create")
bar.printed = true
bar.Finish()
bar.Finish()

if err := writePipe.Close(); err != nil {
t.Fatalf("close write pipe: %v", err)
}

output, err := io.ReadAll(readPipe)
if err != nil {
t.Fatalf("read stderr: %v", err)
}
if got, want := string(output), "\n"; got != want {
t.Fatalf("unexpected finish output: got=%q want=%q", got, want)
}
}

func decompressLZ4Block(t *testing.T, src []byte, size int) []byte {
t.Helper()
dst := make([]byte, size)
n, err := lz4.UncompressBlock(src, dst)
if err != nil {
t.Fatalf("lz4.UncompressBlock: %v", err)
}
if got, want := n, size; got != want {
t.Fatalf("decompressed size mismatch: got=%d want=%d", got, want)
}
return dst
}
Loading