diff --git a/docs/guide/archive.md b/docs/guide/archive.md new file mode 100644 index 0000000..5524350 --- /dev/null +++ b/docs/guide/archive.md @@ -0,0 +1,212 @@ +# Archive + +Every archive format loads as one `Archive` value: a list of named entries whose bytes you `read` on demand. Zip, +tar and 7z hold many entries; gzip, xz, zstd, bzip2 and Brotli files are *single-stream* archives with one entry +(the decompressed data). A `.tar.gz` (`.tgz`, `.tar.xz`, `.tar.zst`, `.tar.bz2`, `.tar.br`) loads straight as the tar +inside. Zip, tar and gzip are writable; any Archive can be written as any of them. + +```luau +local zip = assert(F.archive.load(zipBytes)) +for _, e in zip:list() do + print(e.name, e.size, e.method, e.dir) -- "readme.txt" 116 "deflate" false +end +local readme = assert(zip:read("readme.txt")) -- a buffer +assert(string.find(buffer.tostring(readme), "archive example", 1, true)) + +zip:add("notes/todo.txt", "write the docs") -- a string or a buffer +local out = assert(F.save(zip)) -- a buffer, in the source format (zip) +assert(F.archive.load(out):read("notes/todo.txt")) +``` + +## The type + +`Archive`: + +| Field / method | Type | Meaning | +|---|---|---| +| `kind` | `"archive"` | | +| `format` | string | `"zip"`, `"tar"`, `"7z"`, `"gzip"`, `"xz"`, `"zst"`, `"bz2"`, `"br"` | +| `list(self)` | `{ ArchiveEntry }` | the entries in archive order (directories included) | +| `read(self, name)` | `buffer?, Err?` | a fresh copy of the entry's bytes, decompressed (lazily, on each call) | +| `add(self, name, data, opts?)` | | add or replace an entry; `data` is a buffer or a string | +| `write(self, opts?)` | `buffer?, Err?` | the archive in its own format (`F.save` does the same and can pick another format) | +| `meta` | table | `source.format`; `stream = true` for single-stream archives; `compression` (the outer format of an unwrapped `.tar.gz`); `comment` (zip, gzip) | + +`ArchiveEntry` (each `list()` call returns new tables; editing them changes nothing): + +| Field | Type | Meaning | +|---|---|---| +| `name` | string | the path inside the archive, `/` separated, no leading `/`; directories end in `/` in zip | +| `size` | number | uncompressed bytes (0 for directories) | +| `compressedSize` | number? | stored bytes (zip, gzip) | +| `method` | string? | `"store"`, `"deflate"`, `"lzma2"`, ... | +| `mtime` | number? | modification time, Unix seconds (UTC) | +| `dir` | boolean | a directory entry | +| `crc32`, `comment` | number?, string? | zip only | +| `mode`, `uid`, `gid`, `uname`, `gname`, `type`, `link` | | tar only (`mode` is the Unix permission bits, e.g. `420` = `0644`) | + +## Load + +```luau +local tar = assert(F.archive.load(tgzBytes)) -- a .tar.gz: the tar inside +assert(tar.format == "tar" and tar.meta.compression == "gzip") +for _, e in tar:list() do + assert(e.mtime == 1767225600) -- 2026-01-01T00:00:00Z, Unix seconds +end + +local seven = assert(F.archive.load(sevenzBytes)) -- 7z: LZMA / LZMA2 / Deflate / BZip2 / BCJ / delta +local csv = assert(seven:read("data/scores.csv")) +assert(buffer.tostring(csv):sub(1, 4) == "name") +``` + +Single-stream files hold one entry, named after the file without its compression extension when the loader knows +the name (a path, or `opts.name`), else after the name stored in the file (gzip `FNAME`), else `"data"`: + +```luau +local xz = assert(F.archive.load(xzBytes, { name = "notes.txt.xz" })) +assert(xz.meta.stream and #xz:list() == 1) +assert(xz:list()[1].name == "notes.txt") +local text = buffer.tostring(assert(xz:read("notes.txt"))) + +local zst = assert(F.archive.load(zstBytes)) -- no name given: the entry is "data" +assert(buffer.tostring(assert(zst:read("data"))) == text) +``` + +Pass `unwrap = false` to keep the outer single-stream archive of a `.tar.gz` (its one entry is the raw tar): + +```luau +local gz = assert(F.archive.load(tgzBytes, { unwrap = false })) +assert(gz.format == "gzip" and gz.meta.stream) +local inner = assert(gz:read(gz:list()[1].name)) +assert(F.detect(inner) == "tar") +``` + +Options for loading: + +| Option | Formats | Meaning | +|---|---|---| +| `unwrap` | gzip, xz, zst, bz2, br | `false`: do not open an archive inside a single-stream file (also off when `format` is given) | +| `name` | single-stream | the file name, used to name the entry (set for you when loading a path) | +| `verify` | zip | check each entry's CRC-32 on read (default `true`) | +| `maxEntries` | tar | refuse more entries (default 1e6) | +| `maxBytes` | bz2, br | refuse a bigger decompressed size | + +A path works on hosts with a file system: + + +```luau +local a = assert(F.load("assets/files.zip")) +assert(F.save(a, "out/files.tar")) -- the format from the extension +assert(F.archive.load("out/files.tar"):read("readme.txt")) +``` + +## Inspect + +`read` matches the exact name first; zip also finds entries case-insensitively and by base name. A missing entry is +`nil, Err` (code `ARG`), never an error: + +```luau +local zip = assert(F.archive.load(zipBytes)) +local data, err = zip:read("missing.txt") +assert(data == nil and err.code == F.Err.ARG) +assert(zip:read("README.TXT")) -- zip: case-insensitive lookup + +local files, bytes = 0, 0 +for _, e in zip:list() do + if not e.dir then + files += 1 + bytes += e.size + end +end +assert(files == 3) +``` + +## Edit + +`add` appends an entry or replaces the one with the same name. Its options depend on the format the archive came +from: + +| Option | zip | tar | +|---|---|---| +| `method` | `"deflate"` (default; stored when deflate does not shrink it) or `"store"` | | +| `level` | deflate level 0..9 (default 6) | | +| `mtime` | Unix seconds (default 1980-01-01, for reproducible output) | Unix seconds (default 0) | +| `mode` | | permission bits (default `0644`) | +| `dir` | name the entry `"dir/"` with `data = nil` | `{ dir = true }` | +| `comment`, `utf8`, `attributes` | per-entry comment, UTF-8 name flag, external attributes | | + +Zip archives also have `remove(name)` (true when the entry existed). Unchanged zip entries are copied as they are, +without recompressing. + +New archives come from the format modules: `F.format("zip").create()` and `F.format("tar").new()`. + +```luau +local zip = F.format("zip").create() +zip:add("assets/", nil) -- a directory +zip:add("assets/hello.txt", "hello", { level = 9, mtime = 1767225600 }) +zip:add("assets/raw.bin", buffer.create(1024), { method = "store" }) +local bytes = assert(F.save(zip, nil, { format = "zip", comment = "made by formats-luau" })) + +local back = assert(F.archive.load(bytes)) +assert(#back:list() == 3 and back.meta.comment == "made by formats-luau") +assert(back:list()[3].method == "store") +assert(back:remove("assets/raw.bin") and #back:list() == 2) + +local tar = F.format("tar").new() +tar:add("bin/", "", { dir = true }) +tar:add("bin/run.sh", "#!/bin/sh\necho hi\n", { mode = 493, mtime = 1767225600 }) -- 493 = 0755 +local tarData = assert(F.save(tar)) -- the tar's own format +assert(F.archive.load(tarData):list()[2].mode == 493) +``` + +## Save and convert + +`F.save(archive, dest?, opts?)` writes the archive's own format unless `opts.format` (or the destination's +extension) names another one; any Archive (a 7z, a tar, a zip) can be written as zip, tar or gzip. + +| Writing as | Options | What it holds | +|---|---|---| +| zip | `comment` (archive comment), `zip64` (force ZIP64 records) | every entry | +| tar | `format`: `"pax"` (default: ustar plus pax records when needed), `"gnu"`, `"ustar"` | every entry, with `mode` / `mtime` | +| gzip (`gz`, `tgz`) | `level` 0..9, `name` (FNAME), `mtime` | one entry: that file; several entries: a tar inside (a `.tar.gz`) | + +```luau +local seven = assert(F.archive.load(sevenzBytes)) +local zipData = assert(F.save(seven, nil, { format = "zip" })) -- 7z -> zip +local tgz = assert(F.save(seven, nil, { format = "tgz" })) -- 7z -> .tar.gz +local back = assert(F.archive.load(tgz)) +assert(back.format == "tar" and back.meta.compression == "gzip") +assert(F.detect(zipData) == "zip") + +local converted = assert(F.convert(tgzBytes, "zip")) -- load + save in one call +assert(F.archive.load(converted):read("src/main.luau")) + +local gzipped = assert(F.save("some text", nil, { format = "gzip", name = "note.txt" })) -- a buffer or a string +assert(F.archive.load(gzipped, { unwrap = false }):list()[1].name == "note.txt") +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| zip (`.zip`) | yes | yes | store / deflate entries, ZIP64, data descriptors, comments; no encryption | +| tar (`.tar`) | yes | yes | ustar, pax, GNU long names | +| 7z (`.7z`) | yes | - | copy / LZMA / LZMA2 / Deflate / BZip2 / BCJ / delta; no AES, PPMd, BCJ2 | +| gzip (`.gz`, `.tgz`) | yes | yes | single stream; concatenated members read as one | +| xz / lzma (`.xz`, `.txz`, `.lzma`) | yes | - | single stream | +| zstd (`.zst`, `.tzst`) | yes | - | single stream; no dictionaries | +| bzip2 (`.bz2`, `.tbz2`) | yes | - | single stream | +| Brotli (`.br`) | yes | - | single stream; no magic number, so pass a `.br` name or `format = "br"` | + +Full capability list: [FORMATS.md](../FORMATS.md). + +## Gotchas + +- `read` returns a new buffer every call and decompresses again; keep the buffer if you need it twice. +- `F.save(tar)` of an unwrapped `.tar.gz` writes a plain tar: the value *is* the tar. Pass `format = "tgz"` (or a + `.tar.gz` / `.tgz` destination) to compress it again. +- Writing gzip from an archive with exactly one entry writes that file, not a tar (`format = "tgz"` included); a + `.tar.gz` needs two or more entries. +- Brotli has no magic bytes: detection needs a `.br` name or `format = "br"`. +- Entry names are stored as given. Before extracting to disk, reject names containing `..` or starting with `/`. +- Directory entries: zip lists `"src/"` (trailing slash), 7z and tar list `"src"` with `dir = true`. diff --git a/docs/guide/audio.md b/docs/guide/audio.md new file mode 100644 index 0000000..454473c --- /dev/null +++ b/docs/guide/audio.md @@ -0,0 +1,254 @@ +# Audio + +Every audio format opens as the same streaming **Decoder** and loads as the same **Audio** value. A Decoder hands +out interleaved 32-bit float samples a block at a time, for playback and long files. An Audio holds the whole sound +in one buffer, for editing with `F.ops.audio`. Encoders take either one. A FLAC, an MP3 and an Ogg Vorbis file are +used the same way. + +```luau +local song = assert(F.audio.load(flacBytes)) -- Audio: the whole file decoded +print(song.sampleRate, song.channels, song.frames) -- 44100 2 44100 +print(song.tags.title, song.tags.artist) -- Docs Tone formats-luau +local quieter = F.ops.audio.gainDb(song, -6) +local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192 })) -- a buffer +assert(F.detect(mp3) == "mp3") +``` + +## The types + +### Audio + +`F.audio.load(src)` and `F.load(src)` return an Audio. `F.Types.Audio.new(sampleRate, channels, frames)` makes a +silent one. + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"audio"` | | +| `sampleRate` | number | frames per second (Hz) | +| `channels` | number | samples per frame | +| `frames` | number | the length in sample frames (`frames / sampleRate` = seconds) | +| `samples` | buffer | interleaved f32, `frames * channels * 4` bytes | +| `tags` | `{ [string]: string }` | `title`, `artist`, `album`, `date`, `genre`, `track`, `comment`, ...; keys are lower case | +| `meta` | table | `meta.source = { format = "flac", ... }` after a load | + +**Sample layout.** Samples are little-endian 32-bit floats, nominally in -1..1. The values are not clipped: the +encoders clip. Frame `i` (0-based), channel `c` (0-based) is at byte offset `(i * channels + c) * 4`: + +```luau +local a = F.Types.Audio.new(8000, 2, 8000) -- 1 s of stereo silence at 8 kHz +for i = 0, a.frames - 1 do + local v = math.sin(2 * math.pi * 440 * i / a.sampleRate) * 0.5 + buffer.writef32(a.samples, (i * 2 + 0) * 4, v) -- left + buffer.writef32(a.samples, (i * 2 + 1) * 4, -v) -- right +end +assert(buffer.len(a.samples) == a.frames * a.channels * 4) +local wav = assert(F.save(a, nil, { format = "wav" })) +``` + +**Channel order.** Channels come in WAVE order, whatever the source format uses: FL, FR, C, LFE, BL, BR, SL, SR. +Mono is one channel and stereo is FL, FR. Vorbis and Opus streams are reordered on decode. + +### Decoder + +`F.audio.open(src)` and `F.open(src)` return a Decoder. + +| Member | Meaning | +|---|---| +| `sampleRate`, `channels` | as in Audio | +| `frames` | total frames (an estimate for VBR streams without an index; 0 = unknown) | +| `duration` | seconds | +| `bitrate` | average bits per second | +| `tags` | as in Audio | +| `dec:read(n, out?)` | `buffer, count`: up to `n` frames as interleaved f32, and how many were read (0 at the end). The returned buffer is `out` when `out` holds at least `n * channels * 4` bytes; otherwise it is a new buffer. Only the first `count * channels * 4` bytes are valid. | +| `dec:seek(seconds)` | moves the read position | +| `dec:position()` | the read position in seconds | + +Some formats add their own fields. For example, `bitsPerSample` on WAV, FLAC and AIFF, and `pictures` (cover art) +on FLAC and M4A. + +```luau +local dec = assert(F.audio.open(flacBytes)) +assert(dec.sampleRate == 44100 and dec.channels == 2 and dec.duration == 1) +local block = buffer.create(1024 * dec.channels * 4) -- reused for every read +local total, peak = 0, 0 +while true do + local out, n = dec:read(1024, block) + if n == 0 then break end + for k = 0, n * dec.channels - 1 do + peak = math.max(peak, math.abs(buffer.readf32(out, k * 4))) + end + total += n +end +assert(total == dec.frames) +dec:seek(0.5) +assert(math.abs(dec:position() - 0.5) < 0.001) +``` + +## Loading + +| Call | Gives | +|---|---| +| `F.audio.load(src, opts?)` | an Audio: the whole file decoded | +| `F.audio.open(src, opts?)` | a Decoder | +| `F.load` / `F.open` | the same, when you don't know the category in advance | +| `F.ops.audio.toAudio(decoder)` | the rest of a Decoder as an Audio (`opts.maxFrames` limits it) | + +`src` is a buffer, a string of bytes, or a path on hosts with files. The format is detected from the content (see +the guide's [README](README.md#inputs)). Options: + +| Option | Formats | Meaning | +|---|---|---| +| `format` | all | decode as this format (`"mp3"`, `"wav"`, ...) and skip detection | +| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac | `Err.LIMIT` past this many frames | +| `stereo` | opus | downmix surround streams to stereo | + +```luau +local tags = assert(F.audio.open(mp3Bytes)).tags -- opening reads the tags; nothing is decoded yet +assert(tags.title == "Docs Tone" and tags.album == "Guide" and tags.date == "2026") +local ogg = assert(F.audio.open(oggBytes)) +print(ogg.bitrate, ogg.duration) +local bad, err = F.audio.load("not audio at all") +assert(bad == nil and err.code == F.Err.UNKNOWN_FORMAT) +``` + +## Editing: `F.ops.audio` + +Every function returns a new Audio, or `nil, err` for bad arguments. Times are in seconds. Rates and channel counts +of other inputs are converted to the first input's. + +| Function | Does | +|---|---| +| `toAudio(audioOrDecoder, opts?)` | an Audio as it is, or a Decoder read to its end | +| `gain(a, factor)`, `gainDb(a, dB)` | scale every sample | +| `normalize(a, target?)` | scale so the peak is `target` (default 1) | +| `peak(a)`, `rms(a)` | `level, { per channel }` | +| `fade(a, inSeconds?, outSeconds?)` | linear fade-in / fade-out | +| `trim(a, start, stop?)` | the seconds `[start, stop)` | +| `concat({ a, b, ... })` | one after the other | +| `mix({ a, b, ... }, weights?)` | the sum, as long as the longest | +| `remix(a, channels, m?)` | any channel count. `m[out][in]` is an explicit matrix; the default comes from `matrix(from, to)` | +| `downmix(a, channels?)` | fewer channels (default 2), with ITU-R BS.775 coefficients | +| `upmix(a, channels)` | more channels: mono to FL / FR, stereo to FL / FR, the others silent | +| `matrix(from, to)` | the default remix matrix | +| `resample(a, rate, opts?)` | a new rate, band-limited; `opts.quality = "low" \| "medium" \| "high"` | + +```luau +local A = F.ops.audio +local a = assert(F.audio.load(wavBytes)) +local mono = assert(A.downmix(a, 1)) +local clip = assert(A.trim(A.resample(mono, 22050), 0.25, 0.75)) +assert(clip.channels == 1 and clip.sampleRate == 22050 and clip.frames == 11025) +local loop = assert(A.concat({ clip, A.fade(clip, 0.05, 0.05) })) +local level, perChannel = A.peak(loop) +local loud = assert(A.normalize(loop, 0.9)) +assert(math.abs(A.peak(loud) - 0.9) < 1e-4) +local both = assert(A.mix({ a, loud }, { 0.5, 0.5 })) -- loud is converted to a's 44.1 kHz stereo +assert(both.channels == 2 and both.sampleRate == 44100) +``` + +## Saving and converting + +`F.save(value, dest?, opts?)` takes an Audio or a Decoder. It picks the format from `opts.format`, else from the +destination's extension, else from the source format (`meta.source.format`). A Decoder has no source format, so pass +one. A Decoder is encoded as it is read, without decoding the whole file first. + +```luau +local a = assert(F.audio.load(wavBytes)) +local flac = assert(F.save(a, nil, { format = "flac", level = 8 })) -- buffer +local again = assert(F.save(F.audio.load(flac))) -- the source format: flac +local opus = assert(F.save(F.audio.open(mp3Bytes), nil, { format = "opus", bitrate = 64000 })) -- streamed +assert(F.audio.open(opus).sampleRate == 48000) +local wav24 = assert(F.convert(flacBytes, "wav", { sampleFormat = "s24" })) -- load + save +assert(F.audio.open(wav24).bitsPerSample == 24) +``` + + +```luau +assert(F.save(F.audio.open("assets/tone.flac"), "out/tone.ogg", { quality = 5 })) -- file in, file out +assert(F.detect("out/tone.ogg") == "vorbis") +``` + +Encoder options: + +| Format | Options | +|---|---| +| wav | `sampleFormat = "u8" \| "s16" \| "s24" \| "s32" \| "f32"` (default `"s16"`), `rf64`, `extensible`, `channelMask`, `tags` | +| flac | `level` 0..8 (default 5), `bits` 4..24 (default: the source depth, else 16), `blockSize`, `seekInterval`, `padding` | +| mp3 | `bitrate` **in kbps** (default 128), `layer` 3 or 2 (MP2), `mode = "stereo" \| "joint" \| "mono"`, `sampleRate`, `id3`, `resampleQuality` | +| vorbis | `quality` -1..10 (default 3) | +| opus | `bitrate` **in bits per second** (default 64000 per channel); CELT only; resampled to 48 kHz | +| aiff, au, voc | `sampleFormat` (see each format's `init.luau`) | +| m4a, caf | ALAC (lossless); m4a and caf also keep tags | + +Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the format has tags. + +## Formats + +| Read and write | Read only | +|---|---| +| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC | + +Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as +Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see +[music.md](music.md). + +## Streaming in a game loop + +Decode a little per frame with a time budget. The game never stalls, and memory holds one block, not the whole song. + +```luau +local dec = assert(F.audio.open(oggBytes)) +local block = buffer.create(1024 * dec.channels * 4) +local queued = 0 +-- call once per game frame; returns true at the end of the stream +local function pump(budgetSeconds: number): boolean + local t0 = os.clock() + repeat + local out, n = dec:read(1024, block) + if n == 0 then return true end + queued += n -- hand out[0 .. n * channels * 4) to the audio device here + until os.clock() - t0 >= budgetSeconds + return false +end +while not pump(0.002) do end -- in a game: one pump(0.002) per frame +assert(queued == dec.frames) +``` + +On LÖVE, `F.host.toSoundData(audioOrDecoder)` makes a `SoundData` (16-bit) for `love.audio.newSource`. A queued +source can be fed block by block: + + +```lua +local F = require("formats") +local sd = F.host.toSoundData(F.audio.load("music.flac")) -- whole file +love.audio.newSource(sd):play() + +local dec = F.audio.open("music.ogg") -- streamed +local q = love.audio.newQueueableSource(dec.sampleRate, 16, dec.channels) +function love.update() + while q:getFreeBufferCount() > 0 do + local out, n = dec:read(4096) + if n == 0 then break end + local part = F.Types.Audio.new(dec.sampleRate, dec.channels, n) + buffer.copy(part.samples, 0, out, 0, n * dec.channels * 4) + q:queue(F.host.toSoundData(part)) + end + q:play() +end +``` + +Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or +visualisers. + +## Gotchas + +- **Bitrate units differ.** MP3 takes kbps (`bitrate = 192`); Opus takes bits per second (`bitrate = 96000`). +- `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono. +- `read(n, out)` returns a new buffer when `out` is too small. Always use the buffer it returns. +- Opus always decodes at 48 kHz. Resample with `F.ops.audio.resample` if you need another rate. +- `frames` of a VBR stream without an index is an estimate. Count the frames `read` returns if you need the exact + number. +- `F.save(decoder)` without `opts.format` or a destination fails with `Err.ARG`, because a Decoder has no source + format. +- `F.audio.load` does not take music files (MOD, MIDI). Use `F.music.open(src)` for their audio + ([music.md](music.md)). diff --git a/docs/guide/data.md b/docs/guide/data.md new file mode 100644 index 0000000..3b40019 --- /dev/null +++ b/docs/guide/data.md @@ -0,0 +1,356 @@ +# Data + +The data formats (JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist) decode to plain Luau values: tables, +strings, numbers, booleans. Three helpers fill the gaps Luau tables leave: `F.data.null` (a null that can sit in a +table), ordered objects (`F.Types.object`: key order, and `{}` that stays an object), and `F.Types.Date` (TOML, +YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. + +```luau +local v = assert(F.data.load('{"name": "ada", "tags": ["x", "y"], "boss": null}')) +assert(v.name == "ada" and v.tags[2] == "y") +assert(v.boss == F.data.null) -- JSON null is a sentinel, not nil + +v.level = 3 +local json = assert(F.saveString(v, { format = "json" })) +assert(json == '{"boss":null,"level":3,"name":"ada","tags":["x","y"]}') -- plain tables: keys sorted + +local yaml = assert(F.convert('{"a": [1, 2]}', "yaml", { format = "json" })) -- opts.format: the input's format +assert(buffer.tostring(yaml) == "a:\n - 1\n - 2\n") +``` + +## Values + +| Data | Luau value | +|---|---| +| object / map / table / dict | a table with string keys; maps of MessagePack / CBOR can have any key type | +| array / sequence / list | an array `{ ... }` (1-based) | +| string | string (UTF-8) | +| number | number (one type: integers and floats are both doubles; integers past 2^53 lose precision unless `bigInts = "string"`) | +| true / false | boolean | +| null (`null`, `~`, CBOR `null`, msgpack `nil`) | `F.data.null` (same as `F.null`; `tostring` gives `"null"`) | +| bytes (msgpack bin, CBOR byte string, plist ``, YAML `!!binary`) | `buffer` | +| date / time (TOML, YAML `!!timestamp`, plist ``, CBOR tags 0 / 1, msgpack timestamp) | `F.Types.Date` | + +Decoders give objects as `F.Types.object` tables when the key order is known: always for YAML, TOML, INI, CSV +(`header = true`), MessagePack, CBOR and plist; for JSON only empty objects, unless `ordered = true`. Encoders write +an object's keys in that order; plain tables are written with their keys sorted. + +## Ordered objects and empty tables + +```luau +local Types = F.Types +local o = Types.object() -- an empty object: writes as {} (a plain {} writes as []) +Types.set(o, "zeta", 1) -- assigns and records the key order +Types.set(o, "alpha", 2) +o.later = 3 -- plain assignment works too; keys not in the order come last, sorted +assert(table.concat(Types.keys(o), ",") == "zeta,alpha,later") +assert(Types.isObject(o) and not Types.isObject({})) +assert(F.saveString(o, { format = "json" }) == '{"zeta":1,"alpha":2,"later":3}') + +local keep = assert(F.data.load('{"b": 1, "a": 2}', { ordered = true })) +assert(F.saveString(keep, { format = "json" }) == '{"b":1,"a":2}') + +assert(F.saveString({}, { format = "json" }) == "[]") +assert(F.saveString(Types.object(), { format = "json" }) == "{}") +assert(F.saveString({}, { format = "json", emptyTable = "object" }) == "{}") +``` + +`Types.object(t, keys)` marks an existing table and gives its order; `Types.keys(t)` works on any table (plain +tables: sorted, numbers before strings). + +## Dates + +`F.Types.Date` values are tables with a metatable (`tostring` gives RFC 3339; `==` compares them). + +| Field | Meaning | +|---|---| +| `kind` | `"datetime"` (has an offset: an instant), `"datetime-local"`, `"date-local"`, `"time-local"` | +| `year`, `month`, `day` | the date (month 1..12, day 1..31) | +| `hour`, `minute`, `second` | the time of day | +| `nanosecond` | 0 .. 999999999 | +| `offset` | minutes east of UTC (`-480` = `-08:00`); nil for local kinds | + +```luau +local Date = F.Types.Date +local d = assert(Date.parse("1979-05-27T07:32:00-08:00")) +assert(d.kind == "datetime" and d.offset == -480 and d.hour == 7) +assert(Date.toUnix(d) == 296667120) -- seconds since 1970-01-01T00:00:00Z +assert(tostring(Date.fromUnix(0)) == "1970-01-01T00:00:00Z") +assert(Date.new({ year = 2026, month = 3, day = 4 }).kind == "date-local") +assert(Date.is(d) and Date.valid(d)) +assert(Date.parse("2026-02-30") == nil) -- out-of-range fields +``` + +## Load + +`F.data.load(src, opts?)` or `F.load(src, opts)`; `src` is a string, a buffer or (on hosts with files) a path. Text +formats sniff weakly (YAML, TOML and INI look alike; MessagePack and CBOR without its self-describe tag have no magic), +so pass `format` (a name or extension) unless the data comes from a named file: + +```luau +local cfg = assert(F.data.load('title = "x"\n[server]\nport = 8080\n', { format = "toml" })) +assert(cfg.server.port == 8080) + +local msg = assert(F.data.load(msgpackBytes, { format = "msgpack" })) +assert(msg.name == "ada" and msg.none == F.data.null) +assert(typeof(msg.raw) == "buffer" and buffer.len(msg.raw) == 3) -- bin -> buffer + +local bad, err = F.data.load("{bad", { format = "json" }) +assert(bad == nil and err.code == F.Err.CORRUPT) +print(tostring(err)) -- json: CORRUPT at 0x1: expected a key +``` + + +```luau +local scores = assert(F.load("assets/scores.csv", { header = true, numbers = true })) -- the extension decides +assert(scores[1].name == "ada" and scores[1].score == 1200) +``` + +## JSON + +| Option | Direction | Meaning | +|---|---|---| +| `ordered` | decode | every object as a `Types.object` with its key order | +| `bigInts` | decode | `"string"`: integers past 2^53 stay their exact text | +| `null` | decode | the value used for null (default `F.data.null`) | +| `lines` | both | JSON Lines: an array of values, one per line | +| `indent` | encode | pretty print: spaces per level, or the indent string | +| `sortKeys` | encode | plain tables' keys sorted (default `true`) | +| `emptyTable` | encode | `"array"` (default) or `"object"` for a plain `{}` | +| `ascii` | encode | escape non-ASCII as `\uXXXX` | +| `nan` | encode | `"error"` (default) or `"null"` for NaN / inf | + +```luau +local v = assert(F.data.load('{"a": [1, 2.5, null, true], "e": {}}')) +local pretty = assert(F.saveString(v, { format = "json", indent = 2 })) +assert(string.find(pretty, '\n "a": [\n 1,', 1, true)) + +local rows = assert(F.data.load('{"id": 1}\n{"id": 2}\n', { format = "json", lines = true })) +assert(#rows == 2 and rows[2].id == 2) +assert(F.saveString(rows, { format = "json", lines = true }) == '{"id":1}\n{"id":2}\n') +``` + +## XML + +XML decodes to a `"#document"` node; `doc.root` is the root element. + +| `XmlNode` field | Type | Meaning | +|---|---|---| +| `name` | string | the qualified element name (`"svg:rect"`), or `"#document"`, `"#comment"`, `"#cdata"`, `"#pi"`, `"#doctype"` | +| `attrs` | `Types.object` of strings | attributes, in document order | +| `children` | `{ XmlNode \| string }` | child nodes; text is plain strings | +| `parent` | XmlNode? | the parent (unless `parents = false`) | +| `text` | string? | the content of comment / CDATA / PI / doctype nodes | +| `target` | string? | a PI's target | +| `ns` | string? | the element's namespace URI (with `namespaces = true`) | +| `root`, `declaration`, `doctype` | | on the document: the root element, `{ version, encoding, standalone }`, `{ name, publicId, systemId, ... }` | + +Decode options: `comments`, `cdata`, `pi` (keep those nodes; by default comments and PIs are dropped and CDATA +merges into the text), `whitespace` (keep whitespace-only text), `namespaces`, `entities` (extra named entities), +`maxDepth`. Encode options: `indent`, `declaration` (default true for a document), `selfClose` (default true). + +```luau +local doc = assert(F.data.load([[ +Dune classic]], + { format = "xml", comments = true })) +local lib = doc.root +assert(lib.name == "library" and #lib.children == 3) + +local function text(node) -- all character data below a node + local out = {} + for _, c in node.children do + table.insert(out, if type(c) == "string" then c else text(c)) + end + return table.concat(out) +end +local book = lib.children[1] +assert(book.attrs.id == "b1" and text(book) == "Dune classic") +assert(table.concat(F.Types.keys(book.attrs), ",") == "id,lang") -- attribute order kept +assert(lib.children[2].name == "#comment" and lib.children[2].text == " shelf 2 ") + +-- edit: add an element, then write the document back +local new = { name = "book", attrs = F.Types.object({ id = "b3" }, { "id" }), children = { "Emma" } } +table.insert(lib.children, new) +local xml = assert(F.saveString(doc, { format = "xml" })) +assert(string.find(xml, 'Emma', 1, true)) +``` + +## YAML + +Maps decode to `Types.object`, `~` / `null` to `F.data.null`; anchors and aliases become shared tables (the same +Luau table twice). Decode options: `all` (every document of a multi-document stream, as an array), `tags` +(`"ignore"` resolves unknown tags as untagged), `null`, `maxAliasNodes` (the alias-bomb guard), `maxDepth`. Encode +options: `indent` (default 2), `all`, `explicitStart`, `sortKeys`. Shared tables are written as anchors. + +```luau +local y = assert(F.data.load("base: &b {color: red}\nitem: *b\nlist: [1, two, ~]\n", { format = "yaml" })) +assert(y.item == y.base and y.item.color == "red") +assert(y.list[3] == F.data.null) + +local docs = assert(F.data.load("---\nname: a\n---\nname: b\n", { format = "yaml", all = true })) +assert(#docs == 2 and docs[2].name == "b") +local out = assert(F.saveString(y, { format = "yaml" })) +assert(string.find(out, "base: &", 1, true) and string.find(out, "item: *", 1, true)) +``` + +YAML 1.2 core schema: `yes` / `no` / `on` / `off` are strings, not booleans. + +## TOML + +Tables decode to `Types.object` (file order kept), datetimes to `Types.Date` (all four kinds). Decode option: +`bigInts`. Encode options: `inline` (every sub-table inline), `indent` (indent keys of nested sections). + +```luau +local cfg = assert(F.data.load([=[ +title = "demo" +[server] +port = 8080 +started = 1979-05-27T07:32:00-08:00 +[[users]] +name = "ada" +[[users]] +name = "bob" +]=], { format = "toml" })) +assert(cfg.server.port == 8080 and #cfg.users == 2) +assert(F.Types.Date.is(cfg.server.started) and tostring(cfg.server.started) == "1979-05-27T07:32:00-08:00") + +cfg.server.port = 9090 +local text = assert(F.saveString(cfg, { format = "toml" })) +assert(string.find(text, "[server]\nport = 9090", 1, true)) +``` + +## CSV + +Rows decode to arrays of strings; with `header = true` the first row names the columns and every other row is a +`Types.object` keyed by them (column order kept). Fields are strings unless `numbers = true`. + +| Option | Direction | Meaning | +|---|---|---| +| `header` | both | decode: rows as records; encode (records): write the header row (default true) | +| `numbers` | decode | numeric fields become numbers | +| `delimiter` | both | one byte (default `","`; decode also `"auto"`: picks among `,` `;` tab `\|`) | +| `quote` | both | the quote byte (default `"`) | +| `maxRows` | decode | refuse more rows | +| `newline` | encode | row terminator (default `"\r\n"`) | +| `quoteAll` | encode | quote every field | +| `columns` | encode | record column order (default: first-seen) | + +```luau +local rows = assert(F.data.load(csvText, { format = "csv" })) +assert(rows[1][1] == "name" and rows[4][1] == "lee, jr") -- quoted field with a comma + +local recs = assert(F.data.load(csvText, { format = "csv", header = true, numbers = true })) +assert(#recs == 3 and recs[2].name == "bob" and recs[2].score == 950) + +table.insert(recs, F.Types.object({ name = "cy", score = 10, level = 1 }, { "name", "score", "level" })) +local out = assert(F.saveString(recs, { format = "csv", newline = "\n" })) +assert(string.sub(out, 1, 17) == "name,score,level\n") +assert(string.find(out, '"lee, jr",400,1\ncy,10,1\n', 1, true)) + +local tsv = assert(F.saveString({ { "a", "b" }, { "1", "2" } }, { format = "csv", delimiter = "\t" })) +assert(tsv == "a\tb\r\n1\t2\r\n") +``` + +## INI + +A `Types.object` of sections, each a `Types.object` of string values; keys before the first section sit at the top +level. Decode options: `types` (numbers and `true` / `false` / `yes` / `no` / `on` / `off` become numbers / booleans), +`inlineComments` (strip ` ;...` / ` #...`), `allowNoValue`, `strict` (duplicates are errors). Encode option: +`delimiter` (default `" = "`). + +```luau +local ini = assert(F.data.load("top = 1\n[server]\nhost = example.com\nport = 80\n", { format = "ini" })) +assert(ini.top == "1" and ini.server.port == "80") -- strings by default +local typed = assert(F.data.load("[s]\nport = 80\ndebug = yes\n", { format = "ini", types = true })) +assert(typed.s.port == 80 and typed.s.debug == true) +local text = assert(F.saveString(ini, { format = "ini" })) +assert(string.find(text, "[server]\nhost = example.com\n", 1, true)) +``` + +## MessagePack, CBOR + +Both decode maps to `Types.object` (any key type), bin / byte strings to buffers, timestamps (msgpack ext -1, CBOR +tags 0 / 1) to `Types.Date`. Decode options: `all` (a stream of concatenated values, as an array), `bigInts`, +`null`, `maxDepth`; msgpack `timestamps` / `ordered` (default true), CBOR `dates` (default true). Encode options: +`all`, `sortKeys`, `emptyTable` (`"array"` or `"map"`); msgpack `float32`, `stringsAsBin`; CBOR `compactFloats`, +`dates` (`"string"` or `"epoch"`), `selfDescribe` (prefix tag 55799, which also makes the bytes detectable). + +```luau +local c = assert(F.data.load(cborBytes, { format = "cbor" })) +assert(c.name == "ada" and c.ratio == 0.5 and c.tags[1] == "x") + +local packed = assert(F.save({ id = 7, blob = buffer.fromstring("\0\1") }, nil, { format = "msgpack" })) +local back = assert(F.data.load(packed, { format = "msgpack" })) +assert(back.id == 7 and buffer.len(back.blob) == 2) + +local tagged = assert(F.save({ when = F.Types.Date.fromUnix(0) }, nil, { format = "cbor", selfDescribe = true })) +assert(F.detect(tagged) == "cbor") +assert(F.data.load(tagged).when.year == 1970) +``` + +Extension and tag values without a mapping keep their type: `F.format("msgpack").ext(type, data)` / +`isExt(v)`; `F.format("cbor").tagged(tag, value)`, `isTagged`, `simple(n)`, `undefined`. + +## Plist + +XML and binary (`bplist00`) plists load; writing is XML. `dict` is a `Types.object`, `` a `Types.Date`, +`` a buffer, binary UIDs `F.format("plist").uid(n)` values. Decode option: `bigInts`; encode option: +`sortKeys` (plain tables). + +```luau +local p = assert(F.data.load(bplistBytes)) -- binary plists are detected +assert(p.CFBundleName == "Demo" and p.Version == 3 and p.Beta == false) +assert(p.Built.year == 2026 and typeof(p.Icon) == "buffer") +local xml = assert(F.saveString(p, { format = "plist" })) +assert(string.find(xml, "CFBundleName\n\tDemo", 1, true)) +``` + +## Save and convert + +Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too): +`F.save(value, nil, { format = "json" })` returns a buffer, `F.saveString` a string. `F.convert(src, format, opts)` +loads with `opts` (where `opts.format` names the input's format) and saves as `format` with the same options; a file +name hint (`name = "in.json"`) also names the input: + +```luau +local yaml = assert(F.convert('{"name": "ada", "tags": ["x"]}', "yaml", { name = "in.json" })) +local v = assert(F.data.load(yaml, { format = "yaml" })) +assert(v.name == "ada" and v.tags[1] == "x") + +local toml = assert(F.saveString(v, { format = "toml" })) +local mp = assert(F.save(v, nil, { format = "msgpack" })) +assert(F.data.load(mp, { format = "msgpack" }).tags[1] == "x") +``` + +What survives a conversion: everything maps across except types a target lacks. TOML has no null (`F.data.null` +is an error there), CSV needs rows, INI needs sections of scalars, JSON has no bytes or dates (encode them yourself: +`tostring(date)`), plist cannot hold null. + +## Formats + +| Format | Read | Write | Decodes to | +|---|---|---|---| +| json (`.json`, `.jsonl`, `.ndjson`, `.geojson`) | yes | yes | values; objects plain (or ordered) | +| xml (`.xml`, `.xsd`, `.rss`, `.atom`, `.xhtml`, ...) | yes | yes | `#document` XmlNode tree | +| yaml (`.yaml`, `.yml`) | yes | yes | values, ordered maps, shared aliases | +| toml (`.toml`) | yes | yes | ordered tables, Dates | +| csv (`.csv`, `.tsv`) | yes | yes | rows (arrays or records) | +| ini (`.ini`, `.cfg`, `.conf`, `.desktop`) | yes | yes | sections of strings | +| msgpack (`.msgpack`, `.mpk`) | yes | yes | values, buffers, Dates | +| cbor (`.cbor`) | yes | yes | values, buffers, Dates, tagged values | +| plist (`.plist`) | XML + binary | XML | values, buffers, Dates | + +Full capability list: [FORMATS.md](../FORMATS.md). + +## Gotchas + +- `nil` cannot sit in a table: check `v == F.data.null`, not `v == nil`, for JSON / YAML / CBOR nulls. Assigning + `nil` removes the key (it is not written). +- Luau has one number type: `1.0` reads back as `1`, and TOML / plist write integral floats as integers. Integers + past 2^53 need `bigInts = "string"` to survive. +- An empty plain table `{}` is written as an array; use `F.Types.object()` (or `emptyTable = "object"`) for `{}`. +- Text formats sniff weakly: give `format` (or a file name) for YAML, TOML, INI, CSV, MessagePack and CBOR without + its self-describe tag. +- XML whitespace-only text between elements is dropped by default (`whitespace = true` keeps it); text is never + trimmed otherwise. +- YAML aliases are shared tables: editing `y.item` also edits `y.base`. diff --git a/docs/guide/image.md b/docs/guide/image.md new file mode 100644 index 0000000..4d85bc0 --- /dev/null +++ b/docs/guide/image.md @@ -0,0 +1,245 @@ +# Images + +Every image format (PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO / CUR, PNM / PAM / PFM, Radiance HDR) loads +as one `Image`: a width, a height, a pixel format and one tightly packed `buffer`. Animations (GIF, APNG, animated +WebP) and multi-image files (TIFF pages, ICO entries) add a list of `Frame`s. Editing goes through `F.ops.image`. + +```luau +local img = assert(F.image.load(pngBytes)) -- buffer, string, or a path on hosts with files +print(img.width, img.height, img.format) -- 64 48 rgba8 +local thumb = assert(F.ops.image.resize(img, 32, 24, "lanczos")) +local jpg = assert(F.save(thumb, nil, { format = "jpeg", quality = 85 })) +assert(F.detect(jpg) == "jpeg") +``` + +## The type + +`Image` + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"image"` | | +| `width`, `height` | number | pixels, both >= 1 for decoded images | +| `format` | string | the pixel format (below); decoders give `"rgba8"` unless `opts.native` asks otherwise | +| `pixels` | buffer | rows top to bottom, pixels left to right, no padding between rows | +| `frames` | `{ Frame }?` | animations / pages / icon entries; `nil` for a still image | +| `loops` | number | play count of an animation: `0` = forever, `1` = once, `n` = n plays | +| `meta` | table | `source` (`{ format, bitDepth?, colorType?, ... }`), and when the file has them: `icc` (buffer), `exif` (buffer, from the TIFF header on), `dpi` (`{ x, y }`), `palette` (`{ { r, g, b, a } }`), `text` (`{ [key]: string }`), `orientation` (JPEG EXIF, 1..8) | + +Pixel formats (`F.Types.BPP[format]` is the bytes per pixel): + +| `format` | Bytes / pixel | Layout of one pixel | Range | +|---|---|---|---| +| `rgba8` | 4 | R, G, B, A bytes | 0..255, straight (not premultiplied) alpha | +| `rgb8` | 3 | R, G, B | 0..255 | +| `gray8` | 1 | luma | 0..255 | +| `graya8` | 2 | luma, alpha | 0..255 | +| `alpha8` | 1 | alpha (glyph coverage) | 0..255 | +| `gray16` | 2 | luma, u16 little endian | 0..65535 | +| `rgba16` | 8 | R, G, B, A as u16 little endian | 0..65535 | +| `rgbaf32` | 16 | R, G, B, A as f32 little endian | linear, 0..1 nominal (HDR may exceed 1) | +| `yuv420p` | planar | Y plane `w * h`, then U and V planes `ceil(w/2) * ceil(h/2)` each | BT.601 full range unless `meta.yuv` says otherwise | + +For a packed format the pixel `(x, y)` (0-based, origin top left) starts at byte `(y * width + x) * bpp`: + +```luau +local img = assert(F.load(pngBytes)) +local x, y = 10, 5 +local o = (y * img.width + x) * 4 -- rgba8 +local r, g, b, a = buffer.readu8(img.pixels, o), buffer.readu8(img.pixels, o + 1), + buffer.readu8(img.pixels, o + 2), buffer.readu8(img.pixels, o + 3) +assert(buffer.len(img.pixels) == img.width * img.height * 4) +assert(select(1, F.ops.image.getPixel(img, x, y)) == r) -- the same pixel, through ops +local _ = g + b + a +``` + +`Frame` (one entry of `img.frames`) + +| Field | Type | Meaning | +|---|---|---| +| `image` | Image | the frame's own rectangle (not the full canvas) | +| `x`, `y` | number | where that rectangle sits on the `width x height` canvas | +| `delay` | number | seconds the frame stays on screen | +| `dispose` | `"none"` / `"background"` / `"previous"` | what happens to the frame's rectangle before the next frame: keep it, clear it to transparent, or restore what was there before | +| `blend` | `"source"` / `"over"` | replace the canvas pixels, or alpha-composite over them | + +For an animation, `img.pixels` is the first frame already composited onto the canvas, so code that ignores `frames` +still gets a sensible still image. `F.ops.image.coalesce(img)` composites every frame for you: + +```luau +local gif = assert(F.load(gifBytes)) +print(#gif.frames, gif.loops) -- 3 0 (forever) +local canvases = assert(F.ops.image.coalesce(gif)) -- { Image }: full width x height rgba8, one per frame +assert(#canvases == 3 and canvases[2].width == gif.width) +local delays = F.ops.image.durations(gif) -- { 0.1, 0.1, 0.1 } +assert(F.ops.image.frameCount(gif) == 3 and delays[1] == 0.1) +``` + +Make an image from scratch with `F.Types.Image.new(w, h, format?)` (zero-filled, so transparent black) or +`F.ops.image.new`: + +```luau +local img = F.Types.Image.new(16, 16) -- rgba8 +F.ops.image.fill(img, 255, 128, 0) -- opaque orange (alpha defaults to opaque) +F.ops.image.setPixel(img, 0, 0, 0, 0, 0, 0) -- one transparent pixel +local png = assert(F.save(img, nil, { format = "png" })) +assert(F.load(png).width == 16) +``` + +## Load + +```luau +local img, err = F.load(pngBytes) -- any category: detected from the content +local same = F.image.load(pngBytes) -- restricted to image formats +local jpg = F.image.load(jpegBytes, { scale = 2 }) -- JPEG: decode at half size (2, 4 or 8) +assert(jpg.width == 32) +local tooBig, lerr = F.load(pngBytes, { maxPixels = 100 }) +assert(tooBig == nil and lerr.code == F.Err.LIMIT) +local _ = img and same and err +``` + +| Option | Formats | Meaning | +|---|---|---| +| `format` | all | decode as this format (name or extension) instead of sniffing | +| `maxPixels` | all | refuse larger images with `Err.LIMIT` (default `2^26`) | +| `native` | JPEG, WebP, TIFF, PNM, QOI, TGA, HDR | keep the source layout: `gray8` / `gray16` / `rgb8` / `rgba16` / `rgbaf32` / `yuv420p` (lossy WebP) instead of `rgba8` | +| `scale`, `orient` | JPEG | reduced-size decode; apply the EXIF orientation (`meta.orientation` reports it either way) | +| `coalesce`, `frames` | WebP | every frame as a full canvas; `frames = false` decodes only the first | +| `page`, `maxPages` | TIFF | decode one page (1-based); cap on pages in `frames` | +| `maxFrames` | GIF | cap on frames | + +To read only the header, use the format module's `info` on a reader (no pixels are decoded): + +```luau +local info = assert(F.format("png").info(F.Bytes.reader(pngBytes))) +assert(info.width == 64 and info.height == 48 and info.bitDepth == 8) +``` + +## Edit with `F.ops.image` + +Every function returns a new Image (or `nil, err`) unless it says "in place". Inputs may be any pixel format; +geometric operations on `yuv420p` go through rgba8. + +```luau +local img = assert(F.load(pngBytes)) +local ops = F.ops.image +local small = assert(ops.resize(img, 32, 24)) -- filter: "bilinear" (default), "nearest", "lanczos" +local part = assert(ops.crop(img, 8, 8, 16, 16)) -- x, y, w, h (clipped to the image) +local mirrored = assert(ops.flip(img, "h")) -- "h" left-right, "v" top-bottom +local turned = assert(ops.rotate90(img, 1)) -- quarter turns counter-clockwise (-1 = clockwise) +local tilted = assert(ops.rotate(img, 30)) -- degrees counter-clockwise, canvas grows (opts.expand) +local grey = assert(ops.convert(img, "gray8")) -- any pixel format to any other +assert(turned.width == 48 and grey.format == "gray8" and tilted.width > 64) +local canvas = assert(ops.new(64, 64)) +ops.blit(canvas, part, 4, 4) -- in place, alpha "over" (opts.blend = "source" copies) +ops.blit(canvas, small, 30, 30, { opacity = 0.5 }) +local merged = assert(ops.composite(canvas, mirrored, -32, 40)) -- a copy of canvas with the image drawn on it +local pm = assert(ops.premultiply(img)) -- and ops.unpremultiply +local r, g, b, a = ops.getPixel(img, 63, 0) -- in the format's scale (0..255 / 0..65535 / float) +assert(a == 128 and select(4, ops.getPixel(pm, 63, 0)) == 128) +local copy = assert(ops.copy(img)) +ops.setPixel(copy, 0, 0, 255, 0, 0) -- in place; alpha defaults to opaque +local _ = merged and r and g and b +``` + +Conversions: 8 <-> 16 bit multiplies / divides by 257, float <-> integer clamps to 0..1 (no gamma), grey uses +`(19595 R + 38470 G + 7471 B + 32768) >> 16`. + +Animations: + +```luau +local ops = F.ops.image +local a = assert(ops.new(8, 8)) +local b = assert(ops.fill(assert(ops.new(8, 8)), 255, 0, 0)) +local anim = assert(ops.fromFrames({ a, b }, 0.5)) -- delays: one number or { seconds } +assert(#anim.frames == 2 and anim.frames[2].delay == 0.5) +anim.loops = 3 +local gif = assert(F.save(anim, nil, { format = "gif" })) +assert(F.load(gif).loops == 3) +``` + +## Save and convert + +`F.save(img, dest?, opts?)` picks the writer from `opts.format`, else from the extension of `dest`, else from +`img.meta.source.format` (the format it was loaded from). Without `dest` it returns the encoded `buffer`. + +```luau +local img = assert(F.load(pngBytes)) +local again = assert(F.save(img)) -- PNG again: the source format +local q = assert(F.save(img, nil, { format = "qoi" })) +local s = assert(F.saveString(img, { format = "bmp" })) -- a string instead of a buffer +local webp = assert(F.convert(pngBytes, "webp", { effort = 9 })) -- load + save in one call +assert(F.detect(again) == "png" and F.detect(q) == "qoi" and string.sub(s, 1, 2) == "BM" and F.detect(webp) == "webp") +``` + + +```luau +local img = assert(F.load("assets/photo.png")) -- a path (LuaJIT / LÖVE) +assert(F.save(img, "out/photo.jpg", { quality = 80 })) -- format from the extension; returns true +assert(F.convert("assets/anim.gif", "png", { out = "out/anim.png" })) -- an APNG +assert(F.load("out/anim.png").frames ~= nil) +``` + +Encoder options: + +| Format | Options | +|---|---| +| PNG | `level` (deflate 0..9, default 6), `colorType` (`"auto"`: smallest of RGBA / RGB / grey / grey + alpha), `apng` (write an APNG; automatic when `frames` is set) | +| JPEG | `quality` (1..100, default 90), `subsampling` (`"420"` / `"422"` / `"444"`), `progressive`, `optimize`, `restart`, `jfif`, `meta` (write EXIF / ICC / comment) | +| WebP | lossless only: `effort` (0..9, default 5), `exact` (keep RGB under transparent pixels), `loops`, `background` (`{ r, g, b, a }`) | +| GIF | `maxColors` (default 256), `method` (`"mediancut"` / `"octree"`), `dither`, `loops`, `globalPalette` | +| TIFF | `compression` (`"deflate"` default, `"lzw"`, `"packbits"`, `"none"`), `predictor`, `level`, `rowsPerStrip`; `frames` become pages | +| BMP | `header` (`"v4"` default, `"info"`) | +| TGA | `rle`, `origin` (`"bottom-left"` / `"top-left"`) | +| ICO | `cursor`, `png` (PNG entries); `frames` become entries (each up to 256 x 256) | +| PNM | the subtype from the extension or `format`: `pbm`, `pgm`, `ppm`, `pam`, `pfm` | + +## Formats + +Read and write unless noted; see [FORMATS.md](../FORMATS.md) for depths and details. + +| Format | Animation / pages | Alpha | Notes | +|---|---|---|---| +| PNG / APNG | APNG frames | yes | writes rgba8 only | +| JPEG | | no | lossy; reads baseline / progressive / arithmetic, 8 and 12 bit | +| WebP | frames | yes | reads lossy + lossless; writes lossless only | +| GIF | frames | 1-bit | writes through a palette quantizer (exact when <= 256 colours) | +| TIFF | pages | yes | 1..32-bit, float | +| BMP, TGA, QOI, ICO / CUR, PNM / PAM / PFM | ICO entries | yes | | +| HDR | | no | float (`native` gives rgbaf32) | + +An animated image also opens as a video (`F.video.open(gifBytes)`), and saves to a video format +(`F.convert(gifBytes, "avi")`): see [video.md](video.md). + +## Showing an image + + +```luau +local F = require(game.ReplicatedStorage.Formats) +local img = assert(F.image.load(pngBuffer)) -- e.g. from HttpService:GetAsync(...) +local editable = assert(F.host.toEditableImage(img)) -- needs rgba8: F.ops.image.convert first otherwise +local label = Instance.new("ImageLabel") +label.ImageContent = Content.fromObject(editable) +``` + + +```lua +local F = require("formats") +local img = assert(F.load("photo.png")) -- love.filesystem path +local image = love.graphics.newImage(F.host.toImageData(img)) +local back = F.host.fromImageData(love.image.newImageData("other.png")) -- ImageData -> rgba8 Image +``` + +## Gotchas + +- Encoders take `rgba8` (JPEG also `gray8` / `yuv420p`; TIFF, PNM and HDR more): convert first, e.g. + `F.save(F.ops.image.convert(img16, "rgba8"), nil, { format = "png" })`. PNG writing of 16-bit or palette images is + not supported; 16-bit PNGs decode to 8 bits. +- `frames[i].image` is only the frame's rectangle. Use `F.ops.image.coalesce` to get full canvases. +- GIF stores "repeat count" (plays - 1); `loops` is always the play count, so a loaded GIF that loops forever has + `loops = 0` and a GIF without a loop extension has `loops = 1`. +- A loaded GIF's `meta.background` is a palette index, while the WebP writer wants an `{ r, g, b, a }` colour: pass + `background` explicitly when converting GIF to WebP: `F.save(gif, nil, { format = "webp", background = { 0, 0, 0, 0 } })`. +- WebP writes lossless only (`lossless = false` returns `Err.UNSUPPORTED`). +- `alpha8` images (font glyphs) convert to white with that alpha. +- Pixel values are not colour managed: ICC profiles are kept in `meta.icc` but not applied. diff --git a/docs/guide/recipes.md b/docs/guide/recipes.md new file mode 100644 index 0000000..6f7c875 --- /dev/null +++ b/docs/guide/recipes.md @@ -0,0 +1,166 @@ +# Recipes + +Short task-oriented snippets. Each one runs as a test (see the [guide](README.md) for how the inputs such as +`pngBytes` are provided); the ones that read or write files run on hosts with a file system. + +- [Images](#images): thumbnail, format conversion, GIF to video and back, show an image in Roblox or LÖVE +- [Audio](#audio): transcode, tags, game-loop streaming, render a MIDI +- [3D](#3d): glTF to OBJ with textures, voxels to a mesh +- [Other files](#other-files): zip, CSV, SVG, fonts + +## Images + +### Make a thumbnail + +Fit the image into a 32 x 32 box, keeping its aspect ratio, and save it as a JPEG: + +```luau +local img = assert(F.image.load(pngBytes)) +local scale = math.min(32 / img.width, 32 / img.height, 1) +local w, h = math.max(1, math.floor(img.width * scale + 0.5)), math.max(1, math.floor(img.height * scale + 0.5)) +local thumb = assert(F.ops.image.resize(img, w, h, "lanczos")) +local jpg = assert(F.save(thumb, nil, { format = "jpeg", quality = 85 })) +assert(thumb.width == 32 and thumb.height == 24 and F.detect(jpg) == "jpeg") +``` + +JPEG has no alpha channel. To keep transparency, save as PNG or WebP instead. + +### Convert between image formats + +```luau +local webp = assert(F.convert(pngBytes, "webp", { lossless = true })) +local back = assert(F.load(webp)) +local orig = assert(F.load(pngBytes)) +assert(buffer.tostring(back.pixels) == buffer.tostring(orig.pixels)) -- lossless: the same pixels +``` + +### Animated GIF to video and back to frames + +An animated image converts to a video directly. AVI and MP4 store Motion-JPEG frames. + +```luau +local avi = assert(F.convert(gifBytes, "avi")) +local mp4 = assert(F.convert(gifBytes, "mp4", { quality = 90 })) +assert(F.detect(avi) == "avi" and F.detect(mp4) == "mp4") + +local v = assert(F.video.open(avi)) +local frames = {} +while true do + local f = v:nextFrame() + if not f then + break + end + table.insert(frames, v:toRGBA(f)) -- each frame as an rgba8 Image +end +assert(#frames >= 3 and frames[1].width == 32) +local gif = assert(F.save(assert(F.ops.image.fromFrames(frames, 1 / v.frameRate)), nil, { format = "gif" })) +assert(F.detect(gif) == "gif") +``` + +The GIF frames of `gifBytes` are full-canvas, so the frames you get back match the GIF's. GIF delays that are not a +whole number of video frames become repeated frames. + +### Every frame of an animation as a full image + +```luau +local gif = assert(F.image.load(gifBytes)) +local canvases = assert(F.ops.image.coalesce(gif)) -- frames composited onto full canvases +local delays = F.ops.image.durations(gif) -- seconds per frame +assert(#canvases == F.ops.image.frameCount(gif) and #delays == #canvases) +for i, frame in canvases do + local png = assert(F.save(frame, nil, { format = "png" })) + local _ = png, i -- e.g. F.save(frame, "frame" .. i .. ".png") +end +``` + +### Show an image in Roblox + + +```luau +local F = require(game:GetService("ReplicatedStorage").Formats) +local bytes = game:GetService("HttpService"):GetAsync("https://example.com/cat.webp") +local img = assert(F.image.load(bytes)) +if img.format ~= "rgba8" then + img = assert(F.ops.image.convert(img, "rgba8")) +end +local editable = assert(F.host.toEditableImage(img)) +local label = Instance.new("ImageLabel") +label.Size = UDim2.fromOffset(img.width, img.height) +label.ImageContent = Content.fromObject(editable) +label.Parent = game:GetService("Players").LocalPlayer.PlayerGui:WaitForChild("ScreenGui") +``` + +### Show an image in LÖVE + + +```lua +local F = require("formats") +local image +function love.load() + local img = assert(F.load("cat.webp")) -- a love.filesystem path + image = love.graphics.newImage(F.host.toImageData(img)) +end +function love.draw() + love.graphics.draw(image, 0, 0) +end +``` + +## Audio + +### Transcode FLAC to MP3 + +`F.convert` streams audio: the encoder reads the decoder as it goes. + +```luau +local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192 })) -- MP3 bit rates are in kbit/s +local dec = assert(F.audio.open(mp3)) +assert(dec.sampleRate == 44100 and dec.channels == 2) +assert(math.abs(dec.duration - 1) < 0.1) +``` + +### Read the tags of any audio file + +Tag keys are lower case (`title`, `artist`, `album`, `date`, `genre`, `track`, `comment`, ...), whatever the +container calls them. + +```luau +for _, bytes in { flacBytes, mp3Bytes, oggBytes } do + local dec = assert(F.audio.open(bytes)) -- open reads the headers only + assert(dec.tags.title == "Docs Tone" and dec.tags.artist == "formats-luau") + print(string.format("%s - %s (%.1f s, %d Hz)", dec.tags.artist, dec.tags.title, dec.duration, dec.sampleRate)) +end +``` + +### Stream decode with a CPU budget per frame + +In a game loop, decode a little each frame instead of everything at once. Read in small blocks, stop when the time +budget for this frame is used up, and continue next frame. `os.clock()` works on every host, Roblox included. + +```luau +local dec = assert(F.audio.open(oggBytes)) +local block = buffer.create(1024 * dec.channels * 4) -- reused for every read +local decoded = 0 + +local function step(budget: number): boolean -- call once per frame; false when finished + local t0 = os.clock() + while os.clock() - t0 < budget do + local out, n = dec:read(1024, block) + if n == 0 then + return false + end + decoded += n -- hand out[0 .. n * channels * 4) to the mixer here + local _ = out + end + return true +end + +while step(0.002) do end -- in a game: RunService.Heartbeat / love.update +assert(decoded == dec.frames) +``` + +The same pattern works for video: call `v:nextFrame()` until the budget is used up or the next frame's `pts` is in +the future. + +## 3D + +## Other files diff --git a/docs/guide/scene.md b/docs/guide/scene.md new file mode 100644 index 0000000..525643e --- /dev/null +++ b/docs/guide/scene.md @@ -0,0 +1,412 @@ +# Scene (3D models) and Voxels + +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure +shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, +textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel +files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. + +```luau +local scene = assert(F.model.load(texturedGltfText)) +print(#scene.nodes, #scene.meshes, scene.meta.up) -- 2 1 y +local prim = scene.meshes[1].primitives[1] +local pos = prim.attributes.POSITION -- f32, 3 components, 24 vertices +assert(pos.type == "f32" and pos.components == 3 and pos.count == 24) +assert(prim.indices.count == 36 and prim.mode == "triangles") + +local merged = F.ops.mesh.merge(scene) -- one world-space triangle primitive +local lo, hi = F.ops.mesh.bounds(merged) +print(lo[1], hi[1]) -- -0.5 0.5 +local glb = assert(F.save(scene, nil, { format = "glb" })) +local obj = assert(F.convert(texturedGltfText, "obj")) +``` + +## The type + +**Indices are 1-based everywhere** (`node.mesh`, `node.children`, `prim.material`, `material.baseColorTexture.texture`, +`skin.joints`, `channel.node`, `scene.roots`). Only the *contents* of index accessors are 0-based vertex numbers, as +in glTF. + +### Scene + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"scene"` | | +| `nodes` | `{ Node }` | every node, in file order | +| `roots` | `{ number }` | the top-level node indices (the scene shown) | +| `meshes` | `{ Mesh }` | `{ name?, primitives = { Primitive }, weights? }` | +| `materials` | `{ Material }` | | +| `textures` | `{ Texture }` | | +| `cameras`, `lights`, `skins`, `animations` | arrays | see below | +| `voxels` | `{ Voxels }?` | voxel grids (VOX), shown by `node.voxels` | +| `meta.up` | `"y"` \| `"z"` | the source's up axis: `"y"` for glTF / OBJ, `"z"` for STL / VOX / CAD. Never rotated on load | +| `meta.unit` | `number?` | metres per scene unit when the file says (glTF: 1) | +| `meta.source` | table | `{ format = "gltf", binary = false, generator = ..., ... }` | + +### Node + +| Field | Type | Meaning | +|---|---|---| +| `name` | `string?` | | +| `children` | `{ number }` | child node indices | +| `mesh`, `camera`, `light`, `skin`, `voxels` | `number?` | indices into the scene arrays | +| `translation` | `{ x, y, z }?` | TRS form ... | +| `rotation` | `{ x, y, z, w }?` | ... unit quaternion | +| `scale` | `{ x, y, z }?` | | +| `matrix` | `{ number }?` (16) | ... or a **column-major** 4x4 matrix (`m[13], m[14], m[15]` = translation). Never both | +| `weights` | `{ number }?` | morph target weights | + +`F.Types.Scene.nodeMatrix(node)` gives the local matrix of either form (T * R * S), `F.Types.Scene.mul(a, b)` multiplies +two column-major matrices, and `F.Types.Scene.flatten(scene)` walks the tree from the roots and returns +`{ { primitive, matrix (world), node, mesh } }` for every primitive. + +```luau +local scene = assert(F.load(texturedGltfText)) +local root = scene.nodes[scene.roots[1]] +assert(#root.matrix == 16) -- this file uses a matrix (a -90 degree turn about x) +for _, placed in F.Types.Scene.flatten(scene) do + local m = placed.matrix -- world matrix, column-major + print(placed.node, placed.mesh, m[13], m[14], m[15]) +end +``` + +### Primitive and Accessor + +| Primitive field | Type | Meaning | +|---|---|---| +| `attributes` | `{ [name]: Accessor }` | `POSITION`, `NORMAL`, `TANGENT` (vec4, w = handedness), `TEXCOORD_n`, `COLOR_n`, `JOINTS_n`, `WEIGHTS_n`; custom ones start with `_` (PLY extra properties: `_quality`) | +| `indices` | `Accessor?` | 0-based vertex numbers (`u8` / `u16` / `u32`); nil = vertices in order | +| `mode` | string | `"triangles"`, `"lines"`, `"points"`, `"triangle_strip"`, `"triangle_fan"`, `"line_strip"`, `"line_loop"`, `"polygons"` | +| `faces` | `Accessor?` | `"polygons"` only: one `u32` vertex count per face; `indices` holds the faces one after another | +| `material` | `number?` | index into `scene.materials` | +| `targets` | `{ { [name]: Accessor } }?` | morph targets: `POSITION` / `NORMAL` / `TANGENT` deltas | + +| Accessor field | Type | Meaning | +|---|---|---| +| `data` | `buffer` | **tightly packed** little-endian elements: element `i`, component `c` sits at `(i * components + c) * size`. No stride, no padding; sparse accessors are already applied | +| `type` | string | `f32`, `f64`, `u8`, `u16`, `u32`, `i8`, `i16`, `i32`, or the normalized integers `unorm8`, `unorm16`, `snorm8`, `snorm16` (glTF `normalized: true`: `unorm8` 255 = 1.0, `snorm16` -32767 = -1.0) | +| `components` | number | 1 (scalar), 2, 3, 4 (vec4), or 4 / 9 / 16 with `matrix = true` (MAT2 / MAT3 / MAT4, column-major) | +| `count` | number | elements | + +Read any accessor without caring about its type with `F.Types.Scene.reader`, which converts normalized types to floats: + +```luau +local scene = assert(F.load(texturedGltfText)) +local prim = scene.meshes[1].primitives[1] +local get = assert(F.Types.Scene.reader(prim.attributes.POSITION)) +print(get(0, 0), get(0, 1), get(0, 2)) -- x, y, z of vertex 0 (0-based) +-- the same by hand: f32, 3 components, 4 bytes each +local x = buffer.readf32(prim.attributes.POSITION.data, (0 * 3 + 0) * 4) +assert(x == get(0, 0)) +local idx = prim.indices -- u16 here +local first = buffer.readu16(idx.data, 0) -- the first triangle's first vertex (0-based) +assert(first >= 0 and first < prim.attributes.POSITION.count) +``` + +Build accessors with `F.Types.Scene.accessor(data?, type, components, count)` (`data = nil` allocates zeros); the +byte size of one component is `F.Types.COMPONENT_SIZE[type]`. + +### Material, Texture, Sampler + +| Material field | Type | Meaning | +|---|---|---| +| `baseColor` | `{ r, g, b, a }` | **linear** 0..1 | +| `baseColorTexture`, `metallicRoughnessTexture`, `normalTexture`, `occlusionTexture`, `emissiveTexture` | `TextureRef?` | `{ texture (index), texCoord? (TEXCOORD_n, default 0), scale?, strength?, transform? (KHR_texture_transform: offset, scale, rotation) }` | +| `metallic`, `roughness` | number | 0..1 | +| `emissive` | `{ r, g, b }` | linear | +| `alphaMode`, `alphaCutoff` | `"opaque"` \| `"mask"` \| `"blend"`, number | | +| `doubleSided` | boolean | | +| `extensions` | table? | glTF `KHR_materials_*` by name, their fields as in glTF (texture infos as TextureRefs) | +| `extras` | table? | format extras. OBJ: `extras.obj.values` holds the MTL statements (`Kd`, `Ks`, `Ns`, ...), `extras.obj.maps` the texture maps; the PBR fields are derived from them | + +| Texture field | Type | Meaning | +|---|---|---| +| `data` | `buffer?` | the **encoded** image bytes (PNG, JPEG, WebP, KTX2, ...) | +| `mime` | `string?` | `"image/png"`, ... | +| `uri` | `string?` | the file name relative to the model, when the bytes were not embedded or not found | +| `image` | `Image?` | the decoded image, set by `F.model.loadTextures` (or you) | +| `sampler` | `Sampler?` | `{ wrapS, wrapT = "repeat" \| "clamp" \| "mirror", filter = "linear" \| "nearest", minFilter }` | + +**Model formats never decode images.** Textures stay encoded until you ask: + +```luau +local scene = assert(F.load(texturedGltfText)) +local tex = scene.textures[1] +assert(tex.mime == "image/png" and tex.image == nil) +local _, errs = F.model.loadTextures(scene) -- decodes every texture.data (or texture.uri via opts.resolve) +assert(next(errs) == nil) +local img = tex.image -- an rgba8 Image, 256 x 256 +assert(img.width == 256 and img.format == "rgba8") +local mat = scene.materials[1] +assert(scene.textures[mat.baseColorTexture.texture] == tex) +``` + +`loadTextures(scene, opts?)` returns `scene, errors` (`errors[i]` = the Err of texture `i`); textures whose image format +is missing keep `image = nil`. Saving a scene whose texture has only an `image` encodes it as PNG first. + +### Cameras, lights, skins, animations + +| Type | Fields | +|---|---| +| Camera | `type = "perspective"` (`yfov` radians, `aspect?`, `znear`, `zfar?`) or `"orthographic"` (`xmag`, `ymag`, `znear`, `zfar`) | +| Light | `type = "directional" \| "point" \| "spot"`, `color { r, g, b }`, `intensity`, `range?`, `innerCone?` / `outerCone?` (radians) | +| Skin | `joints { node index }`, `inverseBindMatrices` (Accessor, `f32`, 16 components, `matrix = true`), `skeleton?` | +| Animation | `name?`, `channels { { node, path = "translation" \| "rotation" \| "scale" \| "weights", input, output, interpolation = "LINEAR" \| "STEP" \| "CUBICSPLINE" } }` | + +A channel's `input` accessor holds the key times in **seconds** (`f32` scalars), `output` the values (vec3 for +translation / scale, vec4 quaternions for rotation; CUBICSPLINE stores in-tangent, value, out-tangent per key). +Skinned vertices carry `JOINTS_0` (indices into `skin.joints`, 0-based) and `WEIGHTS_0`. + +```luau +local scene = assert(F.load(riggedGlbBytes)) +local skin = scene.skins[1] +assert(skin.inverseBindMatrices.components == 16 and skin.inverseBindMatrices.count == #skin.joints) +local ch = scene.animations[1].channels[1] +local times = assert(F.Types.Scene.reader(ch.input)) +local lastKey = times(ch.input.count - 1, 0) -- seconds +print(scene.nodes[ch.node].name, ch.path, ch.interpolation, lastKey) +local prim = scene.meshes[1].primitives[1] +assert(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0) +``` + +## Loading + +```luau +local a = assert(F.load(boxGlbBytes)) -- detected by content: GLB +local b = assert(F.model.load(objText, { format = "obj" })) -- text formats: pass format (or a name) when sniffing is unsure +local c = F.load(objText, { name = "cube.obj" }) -- the name's extension is the fallback +assert(a.kind == "scene" and b.kind == "scene" and c.kind == "scene") +``` + +Model options (each format's own; unknown ones are ignored): + +| Option | Formats | Meaning | +|---|---|---| +| `resolve(uri) -> buffer \| string \| nil` | glTF, OBJ, DAE, ... | reads the other files a model names (`.bin`, `.mtl`, textures) | +| `files = { [name] = buffer \| string }` | glTF, OBJ, ... | the other files, by name, instead of `resolve` | +| `mtl` | OBJ | the material library text, when not found otherwise | +| `triangulate` | OBJ, PLY, OFF | `false` keeps n-gons as `mode = "polygons"` (default: fan-triangulated) | +| `flipV` | OBJ | `false` keeps OBJ's bottom-left UV origin (default flips to glTF's top-left) | +| `maxBytes`, `maxVertices`, `maxFaces` | various | size limits (`Err.LIMIT`) | + +### Files next to the model + +A `.gltf` may reference a `.bin` and image files; an `.obj` names its `.mtl`. Loading **from a path** on a host with a +file system (LuaJIT, LÖVE) reads them from the model's folder automatically (relative names only: no absolute paths, no +`..`, no URLs): + + +```luau +local scene = assert(F.load("assets/BoxTextured.gltf")) -- reads BoxTextured0.bin and CesiumLogoFlat.png too +assert(scene.textures[1].data ~= nil and scene.textures[1].uri == "CesiumLogoFlat.png") +local cube = assert(F.load("assets/cube.obj")) -- and cube.mtl +assert(cube.materials[1].name == "red") +``` + +From bytes (Roblox, the luau CLI, downloaded data) hand the files over yourself, as a table or a function: + +```luau +local files = { ["BoxTextured0.bin"] = boxBinBytes, ["CesiumLogoFlat.png"] = logoPngBytes } +local a = assert(F.load(boxGltfText, { files = files })) +local b = assert(F.load(boxGltfText, { resolve = function(uri) return files[uri] end })) +assert(a.textures[1].data and b.textures[1].data) + +local missing, err = F.load(boxGltfText) -- the .bin is required +assert(missing == nil and err.code == F.Err.IO) +local cube = assert(F.load(objText, { format = "obj", files = { ["cube.mtl"] = mtlText } })) +assert(cube.materials[1].baseColor[1] == 0.8) -- from Kd 0.8 0.1 0.1 +``` + +A missing **image** is not an error: the texture keeps its `uri` and no `data`. + +## Editing: `F.ops.mesh` + +Every function accepts any accessor type and writes `f32` attributes and `u32` indices. Bad arguments return +`nil, err`. + +| Function | Does | +|---|---| +| `merge(scene, opts?)` | bakes every primitive (node transforms applied) into one triangle primitive; `byMaterial = true` returns one per material. Lines and points are skipped; skins / morphs stay in rest pose | +| `bounds(primitive \| scene)` | `min { x, y, z }, max { x, y, z }` (a scene: world space) | +| `transform(prim, matrix)` | in place: positions, normals, tangents (and morph deltas); a mirroring matrix flips the winding | +| `triangulate(prim, opts?)` | a new triangle primitive from strips, fans and polygons (`method = "earclip"` default, or `"fan"`) | +| `computeNormals(prim, opts?)` | area-weighted `NORMAL`; `flat = true` splits corners for faceted shading | +| `computeTangents(prim, opts?)` | `TANGENT` (vec4, w = +-1) from `TEXCOORD_` | +| `weld(prim, opts?)` | merges identical vertices; `epsilon` merges near positions; `positionsOnly = true` merges by position alone | +| `unweld(prim)` | one vertex per index (no indices) | +| `f32(accessor)` | the accessor converted to `f32` | +| `scale(scene, factor)` | in place: geometry, translations, animations, cameras, lights; `meta.unit` is divided by factor | +| `setUnit(scene, metresPerUnit)` | rescales so one unit is that many metres (from `meta.unit`, default 1) | +| `setUp(scene, "y" \| "z")` | adds a root node that rotates the old roots to the new up axis (nothing baked) | +| `voxelsToPrimitive(voxels, opts?)`, `meshVoxels(scene, opts?)` | greedy meshing of voxel grids (below) | + +```luau +local M = F.ops.mesh +local scene = assert(F.load(texturedGltfText)) +local prim = assert(M.merge(scene)) -- 24 vertices, 36 indices, world space +local solid = assert(M.weld(prim, { positionsOnly = true })) +assert(solid.attributes.POSITION.count == 8) -- the cube's corners +local faceted = assert(M.computeNormals(M.unweld(prim), { flat = true })) +assert(faceted.attributes.NORMAL.count == 36) +-- scale by 2 and move 10 units along x (column-major: translation in elements 13..15) +M.transform(prim, { 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 10, 0, 0, 1 }) +local lo, hi = M.bounds(prim) +assert(lo[1] == 9 and hi[1] == 11) + +local quads = assert(F.load(objText, { format = "obj", triangulate = false })) +local poly = quads.meshes[1].primitives[1] +assert(poly.mode == "polygons" and poly.faces.count == 6) +assert(M.triangulate(poly).indices.count == 36) + +assert(M.setUnit(scene, 0.01)) -- centimetres: positions x 100 +assert(scene.meta.unit == 0.01) +assert(M.setUp(scene, "z") and scene.meta.up == "z") +``` + +Build a mesh from scratch with the constructors: + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local prim = { attributes = { POSITION = pos }, mode = "triangles", material = 1 } +local scene = S.fromPrimitive(prim, "triangle") -- one node, one mesh +scene.materials[1] = S.material("red") +scene.materials[1].baseColor = { 1, 0, 0, 1 } +F.ops.mesh.computeNormals(prim) +local stl = assert(F.save(scene, nil, { format = "stl" })) +assert(buffer.len(stl) == 84 + 50) -- binary STL: header + one facet +``` + +## Saving and converting + +`F.save(scene, dest?, opts?)` picks the writer from `opts.format`, else the destination's extension, else +`scene.meta.source.format`. `glb` and `gltf` are the same format: `format = "glb"` (or a `.glb` destination) writes +the binary container. + +| Writer | Other files | Options | +|---|---|---| +| glTF | `external = true` writes `.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` | +| OBJ | `.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` | +| STL | | `ascii = true` (default binary), `normals = "attribute"` | +| PLY, OFF, FBX, DAE, 3MF, USDA, VOX | see [FORMATS.md](../FORMATS.md) and the format's options | | + +Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the +`opts.files` table you pass, named after `opts.name`: + +```luau +local scene = assert(F.load(texturedGltfText)) +local files = {} +local gltf = assert(F.save(scene, nil, { format = "gltf", external = true, name = "box.gltf", files = files })) +assert(files["box.bin"] ~= nil) -- plus the texture, under its original name or box_1.png +local mtlFiles = {} +local obj = assert(F.save(scene, nil, { format = "obj", name = "box.obj", files = mtlFiles })) +assert(type(mtlFiles["box.mtl"]) == "string") +assert(string.find(buffer.tostring(obj), "mtllib box.mtl", 1, true)) +``` + +Saving to a path writes those files next to the destination: + + +```luau +local scene = assert(F.load("assets/BoxTextured.gltf")) +assert(F.save(scene, "out/box.glb")) -- one file, everything embedded +assert(F.save(scene, "out/box.gltf", { external = true })) -- box.gltf + box.bin + CesiumLogoFlat.png +assert(F.save(scene, "out/box.obj")) -- box.obj + box.mtl + the texture +assert(F.convert("assets/Box.glb", "stl", { out = "out/box.stl" })) +``` + +## Voxels + +MagicaVoxel `.vox` files load as a Scene with `meta.up = "z"`, units of one voxel, and grids in `scene.voxels`; each +node that shows a model has `node.voxels` (an index into `scene.voxels`) and no mesh until you mesh it. + +| Voxels field | Type | Meaning | +|---|---|---| +| `kind` | `"voxels"` | | +| `size` | `{ sx, sy, sz }` | cells per axis (z up) | +| `data` | `buffer` | one byte per cell, `0` = empty, `1..255` = palette index; cell `(x, y, z)` (0-based) at byte `x + sx * (y + sy * z)` | +| `palette` | `{ { r, g, b, a } }` | 255 entries, 0..255 **sRGB**, `palette[i]` for index `i`, shared by a file's models | +| `materials` | `{ [index]: { type, ... } }?` | MATL: `"diffuse"`, `"metal"`, `"glass"`, `"emit"`, ... with their properties | + +```luau +local V = F.Types.Voxels +local scene = assert(F.load(voxBytes)) +local grid = scene.voxels[1] +local sx, sy, sz = grid.size[1], grid.size[2], grid.size[3] +local filled = 0 +for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + if V.get(grid, x, y, z) ~= 0 then + filled += 1 + end + end + end +end +print(sx, sy, sz, filled) -- 20 21 20 398 +V.set(grid, 0, 0, 0, 1) -- paint a cell with palette entry 1 +local r, g, b, a = table.unpack(grid.palette[1]) +assert(a == 255) + +-- greedy meshing: merged faces, per-vertex colours from the palette +assert(F.ops.mesh.meshVoxels(scene)) -- every node with voxels now has a mesh +local prim = scene.meshes[scene.nodes[1].mesh].primitives[1] +assert(prim.attributes.COLOR_0.type == "f32") -- linear RGBA (glTF's COLOR_0 meaning) +local glb = assert(F.save(scene, nil, { format = "glb" })) +``` + +`voxelsToPrimitive(voxels, opts)` meshes one grid. Options (both functions): `pivot = "center"` (default, MagicaVoxel's +placement: cell `x` spans `x - floor(sx / 2)` ..) or `"corner"` (0 .. sx), `scale` (units per voxel, default 1), +`colors = "linear"` (default, `f32`) or `"srgb"` (`unorm8`, the palette bytes), `indexAttribute = true` (adds +`_PALETTE_INDEX`, `u8`). Call `meshVoxels` once per scene, after editing the grids: each call adds meshes. + +```luau +local V = F.Types.Voxels +local grid = V.new(4, 4, 2) -- empty; the default palette is a grey ramp +for x = 0, 3 do + for y = 0, 3 do + V.set(grid, x, y, 0, 200) -- a 4 x 4 floor + end +end +V.set(grid, 1, 1, 1, 10) +local prim = assert(F.ops.mesh.voxelsToPrimitive(grid, { pivot = "corner", colors = "srgb" })) +local lo, hi = F.ops.mesh.bounds(prim) +assert(hi[1] == 4 and hi[3] == 2) +local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves as a one-model .vox +assert(F.load(vox).voxels[1].size[1] == 4) +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`; no Draco / meshopt | +| OBJ + MTL | yes | yes | polygons, vertex colours, Phong + PBR MTL | +| STL | yes | yes | ASCII / binary, colour conventions; a triangle soup | +| PLY | yes | yes | ASCII / binary, point clouds, custom `_` attributes | +| OFF | yes | yes | | +| FBX | yes | yes | binary + ASCII 7.x, skins, animation | +| Collada (DAE / ZAE) | yes | yes | | +| 3MF | yes | yes | | +| USDA (+ USDZ read) | yes | yes | | +| VOX | yes | yes | voxel grids, scene graph, materials | +| STEP | via the CAD plug-in | | see [cad.md](cad.md) | + +Capabilities per format: [FORMATS.md](../FORMATS.md). + +## Gotchas + +- 1-based object indices, 0-based vertex indices and voxel coordinates. +- Matrices are column-major flat arrays of 16; quaternions are `{ x, y, z, w }`. +- Colours: `baseColor`, `emissive` and `f32` `COLOR_0` are linear; the voxel palette and `unorm8` colours from + `colors = "srgb"` are sRGB bytes. +- No format rotates the data to a common up axis: check `meta.up` (VOX, STL and CAD are z-up) and use + `F.ops.mesh.setUp` or your own matrix. +- OBJ UVs are flipped on load (`v = 1 - v`) to glTF's top-left origin, and flipped back on save. +- `F.ops.mesh.transform` and `computeNormals` / `computeTangents` change the primitive in place (and return it); + `merge`, `weld`, `unweld` and `triangulate` return new primitives. +- `merge` ignores skins and morph targets (the rest pose); bake animation yourself if you need a posed mesh. +- A text model (OBJ, ASCII STL / PLY) passed as a string is sniffed by content; pass `format` or `name` when the text + is ambiguous. diff --git a/docs/guide/vector.md b/docs/guide/vector.md new file mode 100644 index 0000000..516cde5 --- /dev/null +++ b/docs/guide/vector.md @@ -0,0 +1,129 @@ +# Vector graphics (SVG) + +SVG files load as a `Vector`: a list of filled and stroked paths, already resolved from the document (shapes turned +into path commands, CSS and inherited styles applied, `use` expanded, gradients resolved). `F.ops.vector.rasterize` +renders any `Vector` to an rgba8 [Image](image.md) with antialiasing; `F.save` writes it back as SVG. + +```luau +local icon = assert(F.vector.load(svgText)) -- a string or buffer of SVG +print(icon.width, icon.height, #icon.paths) -- 64 64 3 +local img = assert(F.ops.vector.rasterize(icon, 128, 128)) +local png = assert(F.save(img, nil, { format = "png" })) +assert(img.width == 128 and F.detect(png) == "png") +``` + +## The type + +`Vector` + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"vector"` | | +| `width`, `height` | number | the document size in CSS pixels (`width` / `height` attributes, units converted; else the viewBox size) | +| `viewBox` | `{ x, y, w, h }` | the user-space rectangle that maps onto `width x height` | +| `paths` | `{ VectorPath }` | in paint order (first is drawn first, at the bottom) | +| `meta` | table | `groups` (group opacity / clips, by index), `clips` (clip paths), `preserveAspectRatio`, `unsupported` (`{ [element]: count }` of skipped elements such as `text`, `image`, `filter`), `source` | + +`VectorPath` + +| Field | Type | Meaning | +|---|---|---| +| `d` | `{ { op, ... } }` | absolute commands: `{ op = "M", x, y }`, `{ op = "L", x, y }`, `{ op = "Q", x1, y1, x, y }`, `{ op = "C", x1, y1, x2, y2, x, y }`, `{ op = "Z" }`; arcs and shapes arrive as these | +| `transform` | `{ a, b, c, d, e, f }?` | maps the path's coordinates to viewBox space: `x' = a x + c y + e`, `y' = b x + d y + f` | +| `fill`, `stroke` | `Paint?` | `nil` = none | +| `fillRule` | `"nonzero"` / `"evenodd"` | | +| `strokeWidth` | number | in the path's user units | +| `strokeLineJoin`, `strokeLineCap`, `strokeMiterLimit`, `strokeDashArray`, `strokeDashOffset` | | as the SVG properties (defaults `"miter"`, `"butt"`, 4, none, 0) | +| `opacity` | number | 0..1, applied to this path | +| `group`, `clip`, `id` | | index into `meta.groups` / `meta.clips`; the element id | + +`Paint`: `{ type = "color", color = { r, g, b, a } }` with 0..255 components (alpha already includes +`fill-opacity` / `stroke-opacity`), or a gradient `{ type = "linear" | "radial", stops = { { offset, r, g, b, a } }, +units = "objectBoundingBox" | "userSpaceOnUse", spread = "pad" | "reflect" | "repeat", transform?, opacity }` plus `x1, y1, x2, y2` (linear) or `cx, cy, r, fx, fy, fr` +(radial), in the units `units` names. + +```luau +local v = assert(F.load(svgText)) +local bg = v.paths[1] +assert(bg.fill.type == "linear" and #bg.fill.stops == 2) +local first = bg.fill.stops[1] -- { offset, r, g, b, a } +assert(first[1] == 0 and first[2] == 0x30 and first[5] == 255) +local sun = v.paths[2] +assert(sun.fill.type == "color" and sun.d[1].op == "M") +local hill = v.paths[3] +assert(hill.stroke ~= nil and hill.strokeWidth == 1) +``` + +## Load + +`F.load` detects SVG from the text (` + skipped]]) +assert(v and #v.paths == 1 and v.meta.unsupported.text == 1) +local _ = err +``` + +## Rasterize + +`F.ops.vector.rasterize(vector, w?, h?, opts?)` returns an rgba8 Image of `w x h` pixels (default: the vector's +size, rounded up). The viewBox maps onto it by `preserveAspectRatio` (default: centred, uniform scale), so a square +icon rendered into a wide image leaves transparent bars. + +| Option | Meaning | +|---|---| +| `background` | `{ r, g, b, a }` 0..255 under the drawing (default transparent) | +| `tolerance` | curve flattening in device pixels (default 0.1; larger is faster and coarser) | + +```luau +local v = assert(F.load(svgText)) +local wide = assert(F.ops.vector.rasterize(v, 256, 128)) +local _, _, _, a = F.ops.image.getPixel(wide, 0, 64) +assert(a == 0) -- the bar left of the centred square +local onWhite = assert(F.ops.vector.rasterize(v, 32, 32, { background = { 255, 255, 255, 255 } })) +assert(select(4, F.ops.image.getPixel(onWhite, 0, 0)) == 255) +``` + +## Build and edit + +```luau +local v = F.Types.Vector.new(100, 100) -- viewBox 0 0 100 100 +table.insert(v.paths, { + d = { { op = "M", 10, 10 }, { op = "L", 90, 10 }, { op = "L", 50, 90 }, { op = "Z" } }, + fill = { type = "color", color = { 0, 128, 255, 255 } }, + fillRule = "nonzero", strokeWidth = 1, opacity = 1, +}) +local svg = assert(F.saveString(v, { format = "svg" })) +assert(string.find(svg, "M 10 10 L 90 10", 1, true)) +local img = assert(F.ops.vector.rasterize(v, 50, 50)) +assert(select(3, F.ops.image.getPixel(img, 25, 10)) == 255) -- inside the triangle: blue +``` + +## Save + +`F.save(vector)` writes SVG (the only vector writer). Gradients become `` entries, transforms become +`transform` attributes. The output is a normalised SVG, not the original text. + +```luau +local v = assert(F.load(svgText)) +local out = assert(F.saveString(v)) +assert(F.load(out).paths[1].fill.type == "linear") +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| SVG | yes | yes | no text, images, patterns, masks, markers or filters (counted in `meta.unsupported`) | + +Tiled maps (`.tmx` / `.tmj`) are in the same category but load as a [TileMap](tilemap.md). See +[FORMATS.md](../FORMATS.md). + +## Gotchas + +- `F.convert(svgText, "png")` does not rasterize: it returns `Err.UNKNOWN_FORMAT` (PNG is not a vector format). + Rasterize first, then save the Image. +- `` is not rendered: convert text to paths in your editor before exporting. +- Colours are 0..255 (not 0..1 as in model materials). +- Coordinates in `d` are in the path's own user space; apply `transform` to get viewBox coordinates. diff --git a/tools/fixtures/docs_2d.py b/tools/fixtures/docs_2d.py new file mode 100644 index 0000000..412744a --- /dev/null +++ b/tools/fixtures/docs_2d.py @@ -0,0 +1,102 @@ +# Docs inputs for the 2D pages (tools/fixtures.py; see tools/docs_check.py): a layered PSD written by ImageMagick (three +# layers: Sky, Box, a half-transparent Glow; the merged image flattened by ImageMagick), a two-frame Aseprite sprite +# (built with the chunk writer of tools/fixtures/aseprite.py), an SVG icon and a Tiled map as TMX and TMJ (hand-written +# from the Tiled format docs). +# tests/gen/docs_2d.luau { files, vars = { psdBytes, asepriteBytes, svgText, tmxText, tmjText } } +import importlib.util, os, struct, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/aseprite.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs2d_" + name, os.path.join(ctx.root, "tools", *name.split("/"))) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +SVG = """ + + + + + + + + + + +""" + +# a 4 x 3 map of 16 x 16 tiles: one tileset (tiles.png, 4 columns), a tile layer, an object layer with a spawn point +TMX = """ + + + + + + + + + + +1,2,2,3, +5,0,0,7, +6,6,6,6 + + + + + + + + +""" + +TMJ = """{ "type": "map", "version": "1.10", "orientation": "orthogonal", "renderorder": "right-down", + "width": 2, "height": 2, "tilewidth": 8, "tileheight": 8, "infinite": false, "nextlayerid": 2, "nextobjectid": 1, + "tilesets": [ { "firstgid": 1, "name": "t", "tilewidth": 8, "tileheight": 8, "tilecount": 4, "columns": 2, + "image": "t.png", "imagewidth": 16, "imageheight": 16 } ], + "layers": [ { "id": 1, "name": "main", "type": "tilelayer", "width": 2, "height": 2, "x": 0, "y": 0, + "opacity": 1, "visible": true, "data": [ 1, 2, 3, 2147483652 ] } ] } +""" + + +def aseprite(ctx): + A = load(ctx, "fixtures/aseprite.py") + W, H = 32, 24 + sky = bytes((40, 90, 160, 255)) * (W * H) + hero = bytes((220, 50, 50, 255)) * 64 + f1 = [ + A.layer_chunk("Background", flags=1 | 2 | 8), + A.layer_chunk("Hero"), + A.tags_chunk([("walk", 0, 1, 0, 0)]), + A.cel_chunk(0, 0, 0, W, H, sky), + A.cel_chunk(1, 4, 8, 8, 8, hero), + ] + f2 = [ + A.cel_chunk(0, 0, 0, W, H, b"", link=0), + A.cel_chunk(1, 12, 8, 8, 8, hero), + ] + return A.sprite(W, H, 32, [(100, f1), (250, f2)]) + + +def generate(ctx): + dc = load(ctx, "docs_check.py") + files = {"icon.svg": SVG, "level.tmx": TMX, "level.tmj": TMJ, "sprite.aseprite": aseprite(ctx)} + with tempfile.TemporaryDirectory() as d: + out = os.path.join(d, "art.psd") + ctx.nix("imagemagick", ["magick", + "(", "-size", "48x32", "xc:#3070c0", "-set", "label", "Sky", ")", + "(", "-size", "16x16", "xc:#e04040", "-set", "page", "+8+8", "-set", "label", "Box", ")", + "(", "-size", "20x10", "xc:rgba(255,255,0,0.5)", "-set", "page", "+24+18", "-set", "label", "Glow", ")", + "(", "-clone", "0--1", "-background", "none", "-flatten", ")", "-insert", "0", + "-depth", "8", "-type", "TrueColorAlpha", out]) + files["art.psd"] = open(out, "rb").read() + dc.emit_inputs(ctx, files, { + "psdBytes": "art.psd", + "asepriteBytes": "sprite.aseprite", + "svgText": "icon.svg", + "tmxText": "level.tmx", + "tmjText": "level.tmj", + }) diff --git a/tools/fixtures/docs_3d.py b/tools/fixtures/docs_3d.py new file mode 100644 index 0000000..d302144 --- /dev/null +++ b/tools/fixtures/docs_3d.py @@ -0,0 +1,167 @@ +# Docs inputs for the 3D, CAD and font guide pages (tools/fixtures.py, tools/docs_check.py): Khronos glTF samples +# from tests/fixtures/gltf (BoxTextured embedded and with external .bin + PNG, Box.glb, RiggedSimple.glb), a +# hand-written OBJ + MTL cube, MagicaVoxel's chr_knight.vox, a small hand-written STEP file, an ASCII subset of +# DejaVu Sans (nixpkgs dejavu_fonts) made by fontTools as TTF, WOFF and WOFF2, and a two-glyph BMFont (text +# descriptor + PNG page) written here. +# tests/gen/docs_3d.luau { files = { [name] = bytes }, vars = { texturedGltfText = ..., ... } } +import importlib.util, json, os, struct, subprocess, zlib + +INPUTS = ["tools/docs_check.py", "tests/fixtures/gltf", "tests/fixtures/vox"] + +OBJ = """# a unit cube, one material +mtllib cube.mtl +o cube +v 0 0 0 +v 1 0 0 +v 1 1 0 +v 0 1 0 +v 0 0 1 +v 1 0 1 +v 1 1 1 +v 0 1 1 +vt 0 0 +vt 1 0 +vt 1 1 +vt 0 1 +usemtl red +f 1/1 4/4 3/3 2/2 +f 5/1 6/2 7/3 8/4 +f 1/1 2/2 6/3 5/4 +f 2/1 3/2 7/3 6/4 +f 3/1 4/2 8/3 7/4 +f 4/1 1/2 5/3 8/4 +""" + +MTL = """newmtl red +Ka 0 0 0 +Kd 0.8 0.1 0.1 +Ks 0.5 0.5 0.5 +Ns 32 +""" + +STEP = """ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('a point and a direction'),'2;1'); +FILE_NAME('part.step','2026-10-31T12:00:00',('docs'),(''),'formats-luau docs','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1=CARTESIAN_POINT('origin',(0.,0.,0.)); +#2=DIRECTION('z',(0.,0.,1.)); +#3=DIRECTION('x',(1.,0.,0.)); +#4=AXIS2_PLACEMENT_3D('',#1,#2,#3); +#5=CARTESIAN_POINT('tip',(10.,20.,5.5)); +#6=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +ENDSEC; +END-ISO-10303-21; +""" + +def docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def png(w, h, rgba): + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff) + raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")) + + +def fonts(ctx): + """ASCII subset of DejaVu Sans as ttf / woff / woff2 bytes""" + out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#dejavu_fonts"], + capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1] + path = os.path.join(out, "share", "fonts", "truetype", "DejaVuSans.ttf") + code = r""" +import io, sys, json, base64 +from fontTools import subset +from fontTools.ttLib import TTFont +res = {} +for flavor in (None, "woff", "woff2"): + f = TTFont(sys.argv[1] if len(sys.argv) > 1 else %r) + opts = subset.Options() + opts.layout_features = ["kern"] + opts.name_IDs = ["*"] + opts.hinting = False + opts.flavor = flavor + s = subset.Subsetter(opts) + s.populate(unicodes=range(32, 127)) + s.subset(f) + b = io.BytesIO() + f.flavor = flavor + f.save(b) + res[flavor or "ttf"] = base64.b64encode(b.getvalue()).decode() +print(json.dumps(res)) +""" % path + import base64 + res = json.loads(ctx.python(["fonttools", "brotli"], code)) + return {k: base64.b64decode(v) for k, v in res.items()} + + +def bmfont(): + """a 16 x 8 page with 'A' (a filled 6 x 7 block) and 'B' (an outline), and its text descriptor""" + w, h = 16, 8 + px = bytearray(w * h * 4) + for y in range(7): + for x in range(6): + o = (y * w + x) * 4 + px[o:o + 4] = b"\xff\xff\xff\xff" + bx = 8 + x + if x in (0, 5) or y in (0, 6): + o = (y * w + bx) * 4 + px[o:o + 4] = b"\xff\xff\xff\xff" + fnt = ('info face="Mini" size=8 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=0 aa=1 ' + 'padding=0,0,0,0 spacing=1,1\n' + 'common lineHeight=9 base=7 scaleW=16 scaleH=8 pages=1 packed=0\n' + 'page id=0 file="mini_0.png"\n' + 'chars count=2\n' + 'char id=65 x=0 y=0 width=6 height=7 xoffset=0 yoffset=0 xadvance=7 page=0 chnl=15\n' + 'char id=66 x=8 y=0 width=6 height=7 xoffset=0 yoffset=0 xadvance=7 page=0 chnl=15\n' + 'kernings count=1\n' + 'kerning first=65 second=66 amount=-1\n') + return fnt, png(w, h, bytes(px)) + + +def generate(ctx): + dc = docs_check(ctx) + g = "tests/fixtures/gltf/" + files = { + "box_textured_embedded.gltf": ctx.read(g + "BoxTextured/glTF-Embedded/BoxTextured.gltf"), + "BoxTextured.gltf": ctx.read(g + "BoxTextured/glTF/BoxTextured.gltf"), + "BoxTextured0.bin": ctx.read(g + "BoxTextured/glTF/BoxTextured0.bin"), + "CesiumLogoFlat.png": ctx.read(g + "BoxTextured/glTF/CesiumLogoFlat.png"), + "Box.glb": ctx.read(g + "Box/glTF-Binary/Box.glb"), + "RiggedSimple.glb": ctx.read(g + "RiggedSimple/glTF-Binary/RiggedSimple.glb"), + "cube.obj": OBJ.encode(), + "cube.mtl": MTL.encode(), + "chr_knight.vox": ctx.read("tests/fixtures/vox/chr_knight.vox"), + "part.step": STEP.encode(), + } + f = fonts(ctx) + files["DejaVuSans-ascii.ttf"] = f["ttf"] + files["DejaVuSans-ascii.woff"] = f["woff"] + files["DejaVuSans-ascii.woff2"] = f["woff2"] + fnt, page = bmfont() + files["mini.fnt"] = fnt.encode() + files["mini_0.png"] = page + dc.emit_inputs(ctx, files, { + "texturedGltfText": "box_textured_embedded.gltf", # glTF with its texture embedded (data: URIs) + "boxGltfText": "BoxTextured.gltf", # glTF referencing BoxTextured0.bin and CesiumLogoFlat.png + "boxBinBytes": "BoxTextured0.bin", + "logoPngBytes": "CesiumLogoFlat.png", + "boxGlbBytes": "Box.glb", + "riggedGlbBytes": "RiggedSimple.glb", # skin + animation + "objText": "cube.obj", + "mtlText": "cube.mtl", + "voxBytes": "chr_knight.vox", + "stepText": "part.step", + "ttfBytes": "DejaVuSans-ascii.ttf", + "woffBytes": "DejaVuSans-ascii.woff", + "woff2Bytes": "DejaVuSans-ascii.woff2", + "fntText": "mini.fnt", + "fntPageBytes": "mini_0.png", + }) diff --git a/tools/fixtures/docs_av.py b/tools/fixtures/docs_av.py new file mode 100644 index 0000000..8019408 --- /dev/null +++ b/tools/fixtures/docs_av.py @@ -0,0 +1,116 @@ +# Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them): +# tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG + +# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of +# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT / +# ASS subtitles. +# tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } } +import importlib.util, os, struct, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/sf2.py", "tools/fixtures/mod.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_av_" + name, os.path.join(ctx.root, "tools", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def vlq(n): + out = [n & 0x7F] + n >>= 7 + while n: + out.append(0x80 | (n & 0x7F)) + n >>= 7 + return bytes(reversed(out)) + + +def track(events): + body = b"".join(vlq(dt) + data for dt, data in events) + b"\x00\xff\x2f\x00" + return b"MTrk" + struct.pack(">I", len(body)) + body + + +def midi(): + """SMF 1, 480 ticks per quarter: track 1 = name + tempo 120 bpm, track 2 = an eight-note melody on channel 0""" + t1 = track([(0, b"\xff\x03\x05Tempo"), (0, b"\xff\x51\x03" + (500000).to_bytes(3, "big")), + (0, b"\xff\x58\x04\x04\x02\x18\x08")]) + ev = [(0, b"\xff\x03\x06Melody"), (0, b"\xc0\x00")] + for i, note in enumerate([60, 62, 64, 65, 67, 65, 64, 62]): + ev.append((0, bytes((0x90, note, 100)))) + ev.append((240, bytes((0x80, note, 0)))) + t2 = track(ev) + return b"MThd" + struct.pack(">IHHH", 6, 1, 2, 480) + t1 + t2 + + +SRT = """1 +00:00:00,500 --> 00:00:02,000 +Hello, world. + +2 +00:00:02,500 --> 00:00:04,250 +Second line +spans two rows. +""" + +VTT = """WEBVTT + +intro +00:00.500 --> 00:02.000 align:start +Hello, world. + +00:02.500 --> 00:04.250 +Second cue. +""" + +ASS = """[Script Info] +Title: Docs +ScriptType: v4.00+ +PlayResX: 640 +PlayResY: 360 + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1 +Style: Sign,Arial,16,&H0000FFFF,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,1,0,8,10,10,10,1 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +Dialogue: 0,0:00:00.50,0:00:02.00,Default,,0,0,0,,Hello, {\\i1}world{\\i0}. +Dialogue: 0,0:00:02.50,0:00:04.25,Sign,,0,0,0,,A sign\\Nwith two lines +""" + + +def generate(ctx): + dc = load(ctx, "docs_check") + files = {} + with tempfile.TemporaryDirectory() as d: + src = ["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1"] + for name, codec in ( + ("clip.mp4", ["-c:v", "libx264", "-profile:v", "baseline", "-pix_fmt", "yuv420p", "-g", "5", + "-c:a", "aac", "-b:a", "64k"]), + ("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]), + ("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]), + ): + out = os.path.join(d, name) + ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out]) + files[name] = open(out, "rb").read() + files["tune.mid"] = midi() + sf2 = load(ctx, "fixtures/sf2") + files["bank.sf2"] = sf2.build_sf2(False)[0] + mod = load(ctx, "fixtures/mod") + files["song.mod"] = mod.song_basic() + files["subs.srt"] = SRT + files["subs.vtt"] = VTT + files["subs.ass"] = ASS + dc.emit_inputs(ctx, files, { + "mp4Bytes": "clip.mp4", + "aviBytes": "clip.avi", + "webmBytes": "clip.webm", + "midiBytes": "tune.mid", + "sf2Bytes": "bank.sf2", + "modBytes": "song.mod", + "srtText": "subs.srt", + "vttText": "subs.vtt", + "assText": "subs.ass", + }) diff --git a/tools/fixtures/docs_data.py b/tools/fixtures/docs_data.py new file mode 100644 index 0000000..218e596 --- /dev/null +++ b/tools/fixtures/docs_data.py @@ -0,0 +1,94 @@ +# Docs inputs for the archive / data / playlist pages (tools/fixtures.py; tools/docs_check.py explains the inputs): +# a zip and a .tar.gz by Python's zipfile / tarfile, a 7z (p7zip), .xz (xz) and .zst (zstd) by the reference tools, +# MessagePack / CBOR by the msgpack / cbor2 Python packages, a binary plist by plistlib, a CSV and playlists as text. +# tests/gen/docs_data.luau { files = { [name] = bytes }, vars = { zipBytes = "files.zip", ... } } +import importlib.util, io, os, plistlib, tarfile, tempfile, zipfile, datetime + +INPUTS = ["tools/docs_check.py"] + +MTIME = 1767225600 # 2026-01-01T00:00:00Z +README = b"formats-luau archive example\n" * 4 +SCORES = "name,score,level\nada,1200,3\nbob,950,2\n\"lee, jr\",400,1\n" +CODE = r""" +import sys, json, msgpack, cbor2, datetime +v = {"name": "ada", "score": 1200, "tags": ["x", "y"], "ratio": 0.5, "none": None, "raw": b"\x00\x01\x02"} +sys.stdout.buffer.write(json.dumps({"msgpack": msgpack.packb(v).hex(), "cbor": cbor2.dumps(v).hex()}).encode()) +""" + + +def docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + import json + dc = docs_check(ctx) + files = {} + tree = {"readme.txt": README, "src/main.luau": b"print('hello')\n", "data/scores.csv": SCORES.encode()} + b = io.BytesIO() + with zipfile.ZipFile(b, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr(zipfile.ZipInfo("src/", (2026, 1, 1, 0, 0, 0)), b"") + for name, data in tree.items(): + info = zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + z.writestr(info, data) + files["files.zip"] = b.getvalue() + b = io.BytesIO() + with tarfile.open(fileobj=b, mode="w:gz", format=tarfile.PAX_FORMAT) as t: + for name, data in tree.items(): + info = tarfile.TarInfo(name) + info.size, info.mtime, info.mode = len(data), MTIME, 0o644 + t.addfile(info, io.BytesIO(data)) + files["files.tar.gz"] = b.getvalue() + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "notes.txt") + with open(src, "wb") as f: + f.write(README) + ctx.nix("xz", ["xz", "-k", "-9", src]) + ctx.nix("zstd", ["zstd", "-q", "-19", src, "-o", src + ".zst"]) + files["notes.txt.xz"] = open(src + ".xz", "rb").read() + files["notes.txt.zst"] = open(src + ".zst", "rb").read() + seven = os.path.join(d, "files.7z") + for name, data in tree.items(): + p = os.path.join(d, "t", name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + ctx.nix("p7zip", ["sh", "-c", "cd '%s' && 7z a -bd -mx=5 '%s' readme.txt src data > /dev/null" % (os.path.join(d, "t"), seven)]) + files["files.7z"] = open(seven, "rb").read() + packed = json.loads(ctx.python(["msgpack", "cbor2"], CODE)) + files["player.msgpack"] = bytes.fromhex(packed["msgpack"]) + files["player.cbor"] = bytes.fromhex(packed["cbor"]) + files["info.plist"] = plistlib.dumps({"CFBundleName": "Demo", "Version": 3, "Beta": False, + "Built": datetime.datetime(2026, 1, 1, 12, 0, 0), + "Icon": b"\x89PNG"}, fmt=plistlib.FMT_BINARY, sort_keys=False) + files["scores.csv"] = SCORES + files["mix.m3u"] = ("#EXTM3U\n#PLAYLIST:Docs Mix\n#EXTINF:215,Ada - First Song\nhttps://example.com/music/first.mp3\n" + "#EXTINF:-1,Live Radio\nhttp://radio.example/stream\nsongs/local.flac\n") + files["master.m3u8"] = ("#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=800000,CODECS=\"avc1.4d401e,mp4a.40.2\",RESOLUTION=640x360\n" + "low/index.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=2400000,RESOLUTION=1280x720\nhigh/index.m3u8\n") + files["radio.pls"] = ("[playlist]\nFile1=http://radio.example/stream\nTitle1=Radio One\nLength1=-1\n" + "File2=https://example.com/music/second.mp3\nTitle2=Second Song\nLength2=187\n" + "NumberOfEntries=2\nVersion=2\n") + files["mix.xspf"] = ("\n\n" + " Docs Mix\n \n \n https://example.com/music/first.mp3\n" + " First Song\n Ada\n 215000\n" + " \n \n\n") + dc.emit_inputs(ctx, files, { + "zipBytes": "files.zip", + "tgzBytes": "files.tar.gz", + "sevenzBytes": "files.7z", + "xzBytes": "notes.txt.xz", + "zstBytes": "notes.txt.zst", + "msgpackBytes": "player.msgpack", + "cborBytes": "player.cbor", + "bplistBytes": "info.plist", + "csvText": "scores.csv", + "m3uText": "mix.m3u", + "hlsText": "master.m3u8", + "plsText": "radio.pls", + "xspfText": "mix.xspf", + })