diff --git a/src/Rosetta/archive/7z/Header.luau b/src/Rosetta/archive/7z/Header.luau index 3164a6a..8bcc386 100644 --- a/src/Rosetta/archive/7z/Header.luau +++ b/src/Rosetta/archive/7z/Header.luau @@ -1,8 +1,5 @@ --!strict --- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain): --- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams / --- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and --- returns; any other error is a bug and propagates (the tests' fuzz pass sees it). +-- archive/7z/Header: the 7z header parser (7zFormat.txt, LZMA SDK, Igor Pavlov, public domain): streams, files info. local Text = require("@rosetta/codecs/text/Text") local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") @@ -505,8 +502,6 @@ local function header(r: Bytes.Reader): Parsed return p end --- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to --- decode and parse again. function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?) local r = Bytes.reader(b, o, n) local ok, res = pcall(function(): Parsed diff --git a/src/Rosetta/archive/7z/init.luau b/src/Rosetta/archive/7z/init.luau index 74e7ab1..fc99d90 100644 --- a/src/Rosetta/archive/7z/init.luau +++ b/src/Rosetta/archive/7z/init.luau @@ -1,12 +1,7 @@ --!strict --- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose --- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed) --- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 / --- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM, --- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes, --- Windows / Unix attributes, folder and file CRC-32s (verified on read). --- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other --- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing. +-- archive/7z: 7z (7zFormat.txt, LZMA SDK, public domain). Supports: encoded headers, solid folders, copy / LZMA / +-- LZMA2 / Deflate / BZip2 / Zstd (7-Zip-zstd frames) with BCJ and delta filters, anti items (skipped), CRC-32s. +-- Not supported: PPMd, BCJ2, Deflate64, other plug-in codecs, AES, multi-volume, external header references, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,8 +26,8 @@ local SevenZip = { } export type DecodeOptions = { - maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30) - checkCrc: boolean?, -- verify CRC-32s on read (default true) + maxBytes: number?, -- default 2^30, per folder or header + checkCrc: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants @@ -99,7 +94,6 @@ local function packStart(ctx: Ctx, s: Header.Streams, index: number): number end local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?) - -- coder -> first in / out stream index local inBase, outBase = {}, {} local ni, no = 0, 0 for i, c in f.coders do @@ -130,7 +124,6 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf if size > ctx.maxBytes then return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) end - -- the coder's input: another coder's output, or a packed stream local inIdx = inBase[ci] local src: buffer, so: number, sl: number local bound = nil @@ -292,7 +285,6 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive? local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } a.meta.folders = #s.folders a.meta.solid = false - -- folder caches and the substream -> folder map local cache: { [number]: buffer } = {} local subFolder: { number }, subOffset: { number } = {}, {} do diff --git a/src/Rosetta/archive/adf/init.luau b/src/Rosetta/archive/adf/init.luau index ca99eab..8c1d822 100644 --- a/src/Rosetta/archive/adf/init.luau +++ b/src/Rosetta/archive/adf/init.luau @@ -1,14 +1,7 @@ --!strict --- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an --- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international, --- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through --- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the --- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked --- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...), --- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are --- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description --- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk --- images (use the partition contents), dircache blocks (not needed to read). +-- archive/adf: Amiga disk images (AmigaDOS OFS / FFS, intl, dircache; ADF-FAQ by Laurent Clévy): 72-slot hash tables, +-- extension blocks / OFS chains, soft and hard links, protection bits, comments, dates since 1978-01-01, ISO-8859-1 +-- names, header checksums. Not supported: writing, DOS\6 / DOS\7, RDB hard-disk images, dircache blocks. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -89,7 +82,6 @@ local function date(d: Disk, blk: number, off: number): number return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH end --- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables) local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?) local out = {} local blk = hdr diff --git a/src/Rosetta/archive/applesingle/init.luau b/src/Rosetta/archive/applesingle/init.luau index 4772c31..7b16bc2 100644 --- a/src/Rosetta/archive/applesingle/init.luau +++ b/src/Rosetta/archive/applesingle/init.luau @@ -1,13 +1,7 @@ --!strict --- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740): --- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2: --- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags). --- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the --- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name --- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds --- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with --- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS / --- MS-DOS / AFP info entries (kept in meta.entries as id + length). +-- archive/applesingle: AppleSingle (0x00051600) / AppleDouble (0x00051607) v1 and v2 (RFC 1740): data fork (1), +-- resource fork (2), real name (3), comment (4), dates (8; v1 file info 7), Finder info (9), as containers/MacFile. +-- Supports: read, write v2. Not supported: icon, ProDOS / MS-DOS / AFP info entries (kept in meta.entries). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,10 +19,10 @@ local AppleSingle = { caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, } -export type DecodeOptions = { name: string?, maxBytes: number? } -- name: the file name (the api passes it) +export type DecodeOptions = { name: string?, maxBytes: number? } export type EncodeOptions = { - double: boolean?, -- write AppleDouble (no data fork) instead of AppleSingle (default false) - name: string?, -- the name of a buffer / string value (default "data") + double: boolean?, -- default false + name: string?, } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/archive/ar/init.luau b/src/Rosetta/archive/ar/init.luau index 25d520f..64807d8 100644 --- a/src/Rosetta/archive/ar/init.luau +++ b/src/Rosetta/archive/ar/init.luau @@ -1,13 +1,7 @@ --!strict --- archive/ar: Unix ar archives ("!\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/" --- and "/SYM64/" symbol tables) and BSD (inline "#1/" names, the "__.SYMDEF" symbol table), read into the standard --- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not --- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their --- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and --- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed --- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and --- deb(5) (dpkg); no code ported. Not supported: thin archives ("!"), writing symbol tables (a re-written --- library needs ranlib), writing .deb control data (any entries write as a plain ar). +-- archive/ar: Unix ar ("!\n"; ar(5), deb(5); no code ported): System V / GNU ("//" names, "/" and "/SYM64/" +-- symbols) and BSD ("#1/", "__.SYMDEF"); .deb payload and control fields. Supports: read, write gnu / bsd. +-- Not supported: thin archives ("!"), writing symbol tables or .deb control data. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,10 +25,10 @@ local Ar = { export type DecodeOptions = { maxEntries: number?, -- default 1e6 - maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26) + maxBytes: number?, -- .deb control.tar limit (default 2^26) } export type EncodeOptions = { - variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu" + variant: ("gnu" | "bsd")?, -- default: the source's ("bsd" for a .deb), else "gnu" } -- ------------------------------------------------------------------------------------------------ constants @@ -134,7 +128,6 @@ local function controlFields(s: string): { [string]: string } return out end --- control.tar[.ext] -> the control file's fields, or nil local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }? local ext = string.match(name, "^control%.tar%.?(%w*)$") local raw: buffer? @@ -183,7 +176,7 @@ function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local variant = "gnu" local longNames: string? = nil local symbols: { { name: string, offset: number } }? = nil - local offsets: { [number]: string } = {} -- header offset (from the start) -> member name + local offsets: { [number]: string } = {} local count = 0 local p = base + 8 while p < e do @@ -281,7 +274,6 @@ function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) a.meta.symbols = out end a.meta.source = { format = "ar", variant = variant } - -- Debian packages local list = a._entries if list[1] and list[1].name == "debian-binary" then a.meta.source.variant = "deb" @@ -400,7 +392,6 @@ function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" }) function Ar.new(): any local a = Archive.new("ar", encode) a.meta.source = { format = "ar", variant = "gnu" } diff --git a/src/Rosetta/archive/arj/init.luau b/src/Rosetta/archive/arj/init.luau index e2cd703..8511227 100644 --- a/src/Rosetta/archive/arj/init.luau +++ b/src/Rosetta/archive/arj/init.luau @@ -1,11 +1,7 @@ --!strict --- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS, --- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style --- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type --- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM). --- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files, --- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those --- entries / calls). +-- archive/arj: ARJ (Robert Jung; arj's technote.txt): headers CRC-32 checked, methods 0 stored, 1..3 Lzh "lh6", 4 Lzh +-- "arj4", directories (file type 3), DOS times as UTC; file CRC-32 verified. Not supported: garbled (encrypted) files, +-- multi-volume archives, chapters, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +21,7 @@ local Arj = { } export type DecodeOptions = { - maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } diff --git a/src/Rosetta/archive/binhex/init.luau b/src/Rosetta/archive/binhex/init.luau index 80cc488..2733860 100644 --- a/src/Rosetta/archive/binhex/init.luau +++ b/src/Rosetta/archive/binhex/init.luau @@ -1,11 +1,7 @@ --!strict --- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name, --- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified: --- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a --- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file --- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter --- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with --- archive/macbinary), several files in one .hqx (only the first is read). +-- archive/binhex: BinHex 4.0 (.hqx; RFC 1741 notes): 6-bit text, RLE90, header and forks each with CRC-16/XMODEM, as +-- containers/MacFile; writes 64 characters a line, as BinHex 4.0 tools do. Not supported: BinHex 2 / 3 / 5, several +-- files in one .hqx (the first is read). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +21,7 @@ local Binhex = { } export type DecodeOptions = { maxBytes: number? } -- default 2^30 -export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data") +export type EncodeOptions = { name: string? } -- ------------------------------------------------------------------------------------------------ constants local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr" @@ -46,7 +42,6 @@ function Binhex.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input) local function unhex(text: string, maxBytes: number): (buffer?, string?) local banner = string.find(text, BANNER, 1, true) if not banner then @@ -190,7 +185,6 @@ function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) body:u16be(Crc16.ccitt(part, 0, buffer.len(part))) end local src = body:finish() - -- RLE90 local rle = Bytes.writer(buffer.len(src) + 16) local n = buffer.len(src) local i = 0 @@ -244,7 +238,6 @@ function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork function Binhex.new(): any local a = Archive.new("binhex", encoder) a.meta.source = { format = "binhex" } diff --git a/src/Rosetta/archive/br/init.luau b/src/Rosetta/archive/br/init.luau index 63a40bb..74bb31d 100644 --- a/src/Rosetta/archive/br/init.luau +++ b/src/Rosetta/archive/br/init.luau @@ -1,9 +1,6 @@ --!strict --- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar --- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data"). --- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number: --- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a --- low confidence, so the extension decides between candidates. +-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (codecs/compress/Brotli). Supports: read. +-- Not supported: write. No magic number: sniff accepts only data that decodes cleanly, at a low confidence. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -22,8 +19,8 @@ local Br = { } export type DecodeOptions = { - name: string?, -- the file name (the api passes it): the entry is named after it - maxBytes: number?, -- refuse output larger than this (default 2^30) + name: string?, + maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/archive/bz2/init.luau b/src/Rosetta/archive/bz2/init.luau index 19c4cc1..26d719f 100644 --- a/src/Rosetta/archive/bz2/init.luau +++ b/src/Rosetta/archive/bz2/init.luau @@ -1,8 +1,6 @@ --!strict --- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated --- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), --- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in rosetta. Not supported: --- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). +-- archive/bz2: a .bz2 file as a single-stream archive of one entry (codecs/compress/Bzip2). Supports: read, +-- concatenated streams joined as bzip2 -d does. Not supported: writing, randomised blocks (bzip2 0.9.0 and older). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -21,8 +19,8 @@ local Bz2 = { } export type DecodeOptions = { - maxBytes: number?, -- refuse larger output (default 2^30) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + name: string?, } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/archive/cab/Sum.luau b/src/Rosetta/archive/cab/Sum.luau index c57c2c3..61e5ee8 100644 --- a/src/Rosetta/archive/cab/Sum.luau +++ b/src/Rosetta/archive/cab/Sum.luau @@ -1,16 +1,14 @@ --!strict --!native --!optimize 2 --- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3 --- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format --- description ([MS-CAB] 2.4, CFDATA.csum). +-- archive/cab/Sum: the CFDATA.csum checksum ([MS-CAB] 2.4): XOR of LE u32 words, the last 1..3 bytes packed most +-- significant first, then the cbData / cbUncomp word. local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift local Sum = {} --- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum) function Sum.of(buf: buffer, off: number, len: number, seed: number): number if off < 0 or len <= 0 or off + len > blen(buf) then return seed @@ -34,7 +32,6 @@ function Sum.of(buf: buffer, off: number, len: number, seed: number): number return bxor(s, tail) end --- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData) function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) end diff --git a/src/Rosetta/archive/cab/init.luau b/src/Rosetta/archive/cab/init.luau index a4a939b..d7ac320 100644 --- a/src/Rosetta/archive/cab/init.luau +++ b/src/Rosetta/archive/cab/init.luau @@ -1,14 +1,7 @@ --!strict --- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and --- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose --- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum --- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local --- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM) --- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same --- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the --- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a --- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one), --- signed / self-extracting stubs before the header. +-- archive/cab: Microsoft Cabinet (MSCF 1.3, [MS-CAB]): folders none / MSZIP ("CK" + raw deflate, dictionary carried +-- over between blocks) / LZX (2^15..2^21) / Quantum (2^10..2^21), DOS times as UTC, checksums verified; writes one +-- stored or MSZIP folder. Not supported: files spanning cabinets of a set, signed / self-extracting stubs. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,14 +23,14 @@ local Cab = { } export type DecodeOptions = { - maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65535 - verify: boolean?, -- check the data block checksums (default true) + verify: boolean?, -- default true } export type EncodeOptions = { compression: ("mszip" | "none")?, -- default "mszip" - level: number?, -- deflate level 0..9 (default 6) - setId: number?, -- the cabinet set id (default 0) + level: number?, -- 0..9 (default 6) + setId: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ constants @@ -63,8 +56,7 @@ type Folder = { } type Block = { at: number, len: number, size: number } --- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next --- cabinet (a block with cbUncomp 0) +-- a block with cbUncomp 0 runs into the next cabinet local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?) local list: { Block } = {} local p = f.dataAt @@ -95,7 +87,6 @@ local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: b return list, total, false end --- the decompressed data of a folder's blocks local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?) local method = bit32.band(typ, 15) local out = buffer.create(total) @@ -191,7 +182,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) flags = flags, reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, } - -- folders local folders: { Folder } = {} local methods = {} for i = 1, cFolders do @@ -216,7 +206,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if cFiles > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries files") end - -- the folder cache: the last decompressed folder local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false local function folderData(f: Folder): (buffer?, Err.Err?, boolean?) if cachedIndex == f.index then @@ -233,7 +222,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) cachedIndex, cachedData, cachedRuns = f.index, data, runs == true return data, nil, runs end - -- files local fr = r:sub(coffFiles) for _ = 1, cFiles do local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() @@ -306,7 +294,6 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names) function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local compression = o.compression or "mszip" @@ -334,7 +321,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) if total > 0x7FFF8000 then return nil, Err.new(Err.ARG, "more than 2 GB of data") end - -- the folder data, in 32 KB blocks local folder = buffer.create(total) local p = 0 for _, f in files do @@ -369,7 +355,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) s += n end local blob = data:finish() - -- names and the file table local table_ = Bytes.writer(64 + #files * 32) local offset = 0 for _, f in files do @@ -417,7 +402,6 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" }) function Cab.new(): any local a = Archive.new("cab", encode) a.meta.source = { format = "cab" } diff --git a/src/Rosetta/archive/cpio/init.luau b/src/Rosetta/archive/cpio/init.luau index e05d8af..65c6954 100644 --- a/src/Rosetta/archive/cpio/init.luau +++ b/src/Rosetta/archive/cpio/init.luau @@ -1,10 +1,6 @@ --!strict --- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the --- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc --- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters), --- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor, --- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1") --- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped). +-- archive/cpio: cpio (newc, crc, odc, old binary in both byte orders; containers/Cpio). Supports: read (lazy), write as +-- newc / crc / odc; tar hard links ("1") share an inode with their target. Not supported: uname / gname (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,12 +20,12 @@ local CpioFormat = { export type DecodeOptions = { maxEntries: number?, -- default 1e6 - verify: boolean?, -- crc archives: check the data sums (default true) + verify: boolean?, -- default true } export type EncodeOptions = { variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc" - format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default - block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none) + format: string?, -- any other value (the api's "cpio") means the variant default + block: number?, -- default 512, as GNU cpio; 1 = none } -- ------------------------------------------------------------------------------------------------ sniff @@ -153,7 +149,6 @@ function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Er rdevminor = num(e.rdevminor), }) end - -- opts.format may also be the api's format name ("cpio"): the variant default then local o: any = opts or {} local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc" @@ -162,7 +157,6 @@ function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Er end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write() function CpioFormat.new(): any local a = Archive.new("cpio", encode) a.meta.source = { format = "cpio" } diff --git a/src/Rosetta/archive/d64/init.luau b/src/Rosetta/archive/d64/init.luau index af3d3c6..6978f9d 100644 --- a/src/Rosetta/archive/d64/init.luau +++ b/src/Rosetta/archive/d64/init.luau @@ -1,14 +1,7 @@ --!strict --- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info --- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and --- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are --- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are --- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII --- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the --- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any --- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS --- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers' --- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents. +-- archive/d64: Commodore D64 (1541: 35 / 40 / 42 tracks, error block), D71, D81 (Peter Schepers' notes); PETSCII names +-- as VICE's c1541 (0x41..0x5A -> a..z, 0xC1..0xDA / 0x61..0x7A -> A..Z, else U+E0xx); writes with interleave 10 as +-- CBM DOS (not a real drive's sectors). Not supported: GEOS VLIR files (first chain), 1581 partition contents. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,8 +21,8 @@ local D64 = { export type DecodeOptions = { maxEntries: number? } -- default 4096 export type EncodeOptions = { variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64" - disk: string?, -- disk name (default "rosetta" / the name read) - id: string?, -- two-character disk id (default "fl") + disk: string?, -- default "rosetta" / the name read + id: string?, -- default "fl" } -- ------------------------------------------------------------------------------------------------ constants @@ -129,7 +122,6 @@ local function encoder(a: any, o: any?): (buffer?, Err.Err?) return D64.encode(a, o) end --- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?) local w = Bytes.writer() local seen: { [number]: boolean } = {} @@ -174,7 +166,6 @@ function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) a.meta.tracks = geo.tracks a.meta.errorInfo = r:size() ~= geo.total a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks } - -- the directory chain local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1) local seen: { [number]: boolean } = {} local count = 0 @@ -236,7 +227,6 @@ end -- ------------------------------------------------------------------------------------------------ encode -- BAM layout per variant: where each track's free count + bitmap lives local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number) - -- returns (offset of the free count, offset of the bitmap, bitmap bytes) local dir = geo.offsets[geo.dirTrack] if geo.kind == "d81" then local side = if t <= 40 then 1 else 2 @@ -286,7 +276,6 @@ function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local function pad16(s: string): string return s .. string.rep("\160", 16 - #s) end - -- header / BAM local firstDir if variant == "d81" then buffer.writestring(img, dir, "\40\3\68\0") @@ -413,7 +402,6 @@ function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" }) function D64.new(variant: string?): any local a = Archive.new("d64", encoder) a.meta.variant = variant or "d64" diff --git a/src/Rosetta/archive/fat/init.luau b/src/Rosetta/archive/fat/init.luau index 0cce624..455f4b2 100644 --- a/src/Rosetta/archive/fat/init.luau +++ b/src/Rosetta/archive/fat/init.luau @@ -1,10 +1,7 @@ --!strict --- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the --- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3 --- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the --- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy --- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a --- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code. +-- archive/fat: FAT12 / FAT16 / FAT32 images (floppy, or the first FAT partition of an MBR) through containers/Fat. +-- Supports: VFAT long names, NT lower-case 8.3, DOS dates as UTC; writes FAT12 floppies (360..2880 KB) that mtools and +-- fsck.fat read. Not supported: writing FAT16 / FAT32, exFAT, boot code. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,12 +20,12 @@ local FatFormat = { } export type DecodeOptions = { - partition: number?, -- MBR partition 1..4 (default: the first FAT partition, or the image itself) + partition: number?, -- 1..4 (default: the first FAT partition, or the image itself) maxEntries: number?, -- default 65536 } export type EncodeOptions = { - size: number?, -- floppy size in KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) - label: string?, -- volume label + size: number?, -- KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) + label: string?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -114,7 +111,6 @@ function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" }) function FatFormat.new(): any local a = Archive.new("fat", encoder) a.meta.source = { format = "fat" } diff --git a/src/Rosetta/archive/grp/init.luau b/src/Rosetta/archive/grp/init.luau index 44ce7fc..f8a081b 100644 --- a/src/Rosetta/archive/grp/init.luau +++ b/src/Rosetta/archive/grp/init.luau @@ -1,9 +1,7 @@ --!strict --- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count, --- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive --- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they --- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken. --- Not supported: the "GRP 2" / RFF / SSI variants. +-- archive/grp: Build engine GRP ("KenSilverman", u32 count, 16-byte entries: 12-byte name + u32 size, then the data), +-- from Ken Silverman's description; no code taken. Supports: read (lazy), write (names stored as given, at most 12 +-- bytes). Not supported: the "GRP 2" / RFF / SSI variants. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +21,7 @@ local Grp = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { maxEntries: number? } -- default 1e6 -export type EncodeOptions = { upper: boolean? } -- upper-case the names (Build looks them up case-insensitively; default false) +export type EncodeOptions = { upper: boolean? } -- Build looks names up case-insensitively; default false -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "KenSilverman" @@ -105,7 +103,6 @@ function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty GRP Archive: a:add(name, data); a:write() function Grp.new(): any local a = Archive.new("grp", encode) a.meta.source = { format = "grp" } diff --git a/src/Rosetta/archive/gzip/init.luau b/src/Rosetta/archive/gzip/init.luau index 6b9a7fa..95921fc 100644 --- a/src/Rosetta/archive/gzip/init.luau +++ b/src/Rosetta/archive/gzip/init.luau @@ -1,9 +1,7 @@ --!strict --- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the --- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d --- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive --- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the --- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification. +-- archive/gzip: gzip (RFC 1952) as a single-stream archive of one entry (FNAME, MTIME; codecs/compress/Deflate). +-- Supports: concatenated members as one stream (as gzip -d); write (several entries: a .tar.gz). +-- Not supported: FHCRC verification. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,11 +21,11 @@ local Gzip = { caps = { decode = true, encode = true, stream = true }, } -export type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME +export type DecodeOptions = { name: string? } export type EncodeOptions = { level: number?, -- 0..9, default 6 - name: string?, -- FNAME (default: the entry's name; none for a buffer) - mtime: number?, -- MTIME (default: the entry's mtime, else 0) + name: string?, -- default: the entry's name; none for a buffer + mtime: number?, -- default: the entry's mtime, else 0 } -- ------------------------------------------------------------------------------------------------ sniff @@ -36,7 +34,6 @@ function Gzip.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent) local function header(b: buffer, o: number, e: number): { [string]: any } local h: { [string]: any } = {} if o + 10 > e then @@ -171,7 +168,6 @@ function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz) function Gzip.new(data: (buffer | string)?, name: string?): any local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) return Gzip.encode(arc, o) diff --git a/src/Rosetta/archive/iso/init.luau b/src/Rosetta/archive/iso/init.luau index 658566c..189b5b4 100644 --- a/src/Rosetta/archive/iso/init.luau +++ b/src/Rosetta/archive/iso/init.luau @@ -1,12 +1,7 @@ --!strict --- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660: --- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories; --- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files. --- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts --- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El --- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one. --- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored --- bytes), multi-session images (the first session). +-- archive/iso: ISO 9660 images through containers/Iso9660. Supports: plain names, Joliet, Rock Ridge (RR, else Joliet, +-- else plain), multi-extent files, El Torito boot catalog (meta.boot). Not supported: writing, UDF, interleaved files +-- (UNSUPPORTED), zisofs (stored bytes), multi-session images (the first session). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +20,7 @@ local Iso = { } export type DecodeOptions = { - prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain) + prefer: ("rockridge" | "joliet" | "iso9660")?, -- default: Rock Ridge, else Joliet, else plain maxEntries: number?, -- default 1e6 } diff --git a/src/Rosetta/archive/lha/init.luau b/src/Rosetta/archive/lha/init.luau index 4977160..c8c19ee 100644 --- a/src/Rosetta/archive/lha/init.luau +++ b/src/Rosetta/archive/lha/init.luau @@ -1,14 +1,7 @@ --!strict --- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their --- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS --- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7, --- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read. --- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower --- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header --- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu --- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc), --- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or --- at the first header found in the first 64 KB). +-- archive/lha: LHA / LZH (and LArc .lzs; Yoshizaki's LHa notes, lhasa's lha_file_header.c, ISC): header levels 0-3, +-- methods lh0 / lz4 / lhd / lh1 / lh4-lh7 / lhx / lzs / lz5, CRC-16 (ARC), "name|target" symlinks; writes level 2, +-- stored. Not supported: PMarc pm0-pm2, compression when writing, multi-volume, stubs beyond the first 64 KB. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,7 +21,7 @@ local Lha = { } export type DecodeOptions = { - maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } export type EncodeOptions = {} @@ -58,7 +51,7 @@ function Lha.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them) +-- "." / ".." collapsed as lhasa does local function path(s: string): string s = string.gsub(s, "[\\\255]", "/") local parts = {} @@ -90,7 +83,6 @@ type Header = { dataAt: number, } --- the extended headers from offset p (size field width w), until a zero size; returns the end offset local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?) local size = first local guard = 0 @@ -138,7 +130,6 @@ local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } --- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker local function header(r: Bytes.Reader, p: number): (Header?, string?) local limit = r:size() if p >= limit or r:sub(p, 1):u8() == 0 then @@ -241,7 +232,6 @@ function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65536 local p = 0 - -- a self-extracting stub: find the first header if not isHeader(r:peek(22)) then local head = r:peek(65536) local at = nil @@ -383,7 +373,7 @@ function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) dirPart, base = full .. "/", "" end local h = Bytes.writer() - h:u16le(0) -- total size, patched + h:u16le(0) h:string(if e.dir then "-lhd-" else "-lh0-") h:u32le(buffer.len(data)) h:u32le(buffer.len(data)) @@ -424,7 +414,6 @@ function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data) function Lha.new(): any local a = Archive.new("lha", encoder) a.meta.source = { format = "lha" } diff --git a/src/Rosetta/archive/lz4/init.luau b/src/Rosetta/archive/lz4/init.luau index 70edae2..61e357e 100644 --- a/src/Rosetta/archive/lz4/init.luau +++ b/src/Rosetta/archive/lz4/init.luau @@ -1,13 +1,7 @@ --!strict --- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the --- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api --- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy --- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed --- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified --- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks --- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size; --- several entries are written as a tar inside. Written from the specification; no code ported. Not supported: --- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames. +-- archive/lz4: LZ4 frames (lz4_Frame_format.md 1.6.x) as a single-stream archive. Supports: concatenated, skippable +-- (0x184D2A50..5F) and legacy (0x184C2102, 8 MB blocks) frames, linked blocks, 64 KB .. 4 MB, XXH32 checksums; writes +-- one frame of independent blocks. Not supported: dictionaries, writing linked blocks or legacy frames. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,15 +21,15 @@ local Lz4Format = { } export type DecodeOptions = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + verify: boolean?, -- default true; the header checksum is always checked + name: string?, } export type EncodeOptions = { blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool) blockChecksum: boolean?, -- default false contentChecksum: boolean?, -- default true - contentSize: boolean?, -- store the content size (default false) + contentSize: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -71,7 +65,6 @@ end type Out = { buf: buffer, n: number, max: number } --- room for k more bytes in the output (doubling, up to max) | false local function room(out: Out, k: number): boolean local need = out.n + k if need > out.max then @@ -85,7 +78,6 @@ local function room(out: Out, k: number): boolean return true end --- one LZ4 frame at p -> the input offset after it | nil, Err local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?) if p + 7 > e then return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) @@ -210,7 +202,6 @@ local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err. return q, nil end --- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then @@ -280,7 +271,6 @@ function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err? end -- ------------------------------------------------------------------------------------------------ encode --- compress(data, opts?) -> one LZ4 frame | nil, Err function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) if not b then @@ -341,7 +331,6 @@ function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffe return w:finish(), nil end --- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local data, err = Archive.streamData(value) if not data then diff --git a/src/Rosetta/archive/macbinary/init.luau b/src/Rosetta/archive/macbinary/init.luau index a561ff7..c5ee83e 100644 --- a/src/Rosetta/archive/macbinary/init.luau +++ b/src/Rosetta/archive/macbinary/init.luau @@ -1,11 +1,7 @@ --!strict --- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags, --- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III --- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its --- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry --- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / --- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the --- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped). +-- archive/macbinary: MacBinary I / II / III (128-byte header, forks padded to 128, Get Info comment; II / III +-- CRC-16/XMODEM, III 'mBIN'), from the MacBinary II / III specs (Lempereur et al.), as containers/MacFile. +-- Supports: read, write III. Not supported: the secondary header's content (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,10 +21,9 @@ local MacBinary = { } export type DecodeOptions = { maxBytes: number? } -- default 2^30 -export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data") +export type EncodeOptions = { name: string? } -- ------------------------------------------------------------------------------------------------ sniff --- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o local function version(b: buffer, o: number, len: number): string? if len < 128 then return nil diff --git a/src/Rosetta/archive/mpq/Crypt.luau b/src/Rosetta/archive/mpq/Crypt.luau index 255918e..797dae3 100644 --- a/src/Rosetta/archive/mpq/Crypt.luau +++ b/src/Rosetta/archive/mpq/Crypt.luau @@ -1,9 +1,7 @@ --!strict --!native --- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file --- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois --- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every --- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree). +-- archive/mpq/Crypt: the MPQ encryption table, name hash (0 = table index, 1 / 2 = name check, 3 = file key) and +-- block decryption, from "The MoPaQ Archive Format" (Olbrantz / Roy) and StormLib's docs; no code taken. Mod 2^32. local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot @@ -26,7 +24,7 @@ do end end --- hash(name, kind) -> u32: ASCII upper case, '/' as '\' +-- name hash: ASCII upper case, '/' as '\' function Crypt.hash(name: string, kind: number): number local s1, s2 = 0x7FED7FED, 0xEEEEEEEE local base = kind * 0x100 @@ -43,7 +41,7 @@ function Crypt.hash(name: string, kind: number): number return s1 end --- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place +-- whole u32s; a trailing partial word is left as is function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) local s2 = 0xEEEEEEEE local k = key % TWO32 @@ -57,7 +55,7 @@ function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) end end --- base name of an archived path (the file key uses it) +-- the file key uses the base name function Crypt.baseName(name: string): string return string.match(name, "([^\\/]*)$") or name end diff --git a/src/Rosetta/archive/mpq/init.luau b/src/Rosetta/archive/mpq/init.luau index e15e6c9..2a96b53 100644 --- a/src/Rosetta/archive/mpq/init.luau +++ b/src/Rosetta/archive/mpq/init.luau @@ -1,16 +1,7 @@ --!strict --- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the --- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset --- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block --- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block --- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded --- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2 --- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks --- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive --- Format", and StormLib's documentation); no code taken. --- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET --- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables, --- writing. +-- archive/mpq: Blizzard MPQ ("The MoPaQ Archive Format", Olbrantz / Roy; StormLib docs; no code taken). Supports: +-- header v1-4, hash / block / hi-block tables, prefixed archives, (listfile), encrypted files, imploded and zlib / +-- PKWARE / bzip2 / LZMA / sparse sectors. Not supported: Huffman / ADPCM sectors, patch files, HET / BET, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,9 +25,9 @@ local Mpq = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - names: { string }?, -- extra file names to look up (beside the archive's own "(listfile)") + names: { string }?, maxEntries: number?, -- default 1e6 - maxBytes: number?, -- the largest file read (default 2^30) + maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants @@ -85,7 +76,6 @@ local function unsparse(b: buffer, at: number, n: number, want: number): (buffer return out, nil end --- one compressed sector (mask byte first) -> want bytes local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?) if n < 1 then return nil, Err.new(Err.CORRUPT, "empty compressed sector") @@ -151,7 +141,6 @@ end type Block = { offset: number, csize: number, size: number, flags: number } --- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key) local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?) local flags = blk.flags if band(flags, FLAG_PATCH) ~= 0 then @@ -250,7 +239,6 @@ local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?) return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") end --- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil local function findHeader(r: Bytes.Reader): number? local size = r.limit - r.base local p = 0 @@ -328,7 +316,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local maxBytes = opts and opts.maxBytes or 2 ^ 30 local mask = hashCount - 1 local pow2 = band(hashCount, mask) == 0 - -- lookup(name) -> block index (1-based) | nil local function lookup(name: string): number? local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) local start = if pow2 then band(h0, mask) else h0 % hashCount @@ -352,7 +339,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local blk = blocks[bi] return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) end - -- names: (listfile) and opts.names local names: { string } = {} for _, internal in { "(attributes)", "(signature)", "(user data)" } do table.insert(names, internal) @@ -413,7 +399,6 @@ function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key) Mpq.hash = Crypt.hash return Mpq diff --git a/src/Rosetta/archive/pak/init.luau b/src/Rosetta/archive/pak/init.luau index 973a548..46dbf1e 100644 --- a/src/Rosetta/archive/pak/init.luau +++ b/src/Rosetta/archive/pak/init.luau @@ -1,9 +1,7 @@ --!strict --- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the --- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored --- bytes) and written from any Archive value. Written from the format description in the Quake source release --- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken. --- Not supported: Daikatana's compressed PAK entries. +-- archive/pak: Quake / Quake II / Half-Life PAK ("PACK": 56-byte names, 64-byte entries) and SiN ("SPAK": 120-byte +-- names), from Quake's common.c (dpackheader_t / dpackfile_t) and the Quake specs; no code taken. Supports: read +-- (lazy), write. Not supported: Daikatana's compressed entries. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -125,7 +123,6 @@ function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write() function Pak.new(variant: ("quake" | "sin")?): any local a = Archive.new("pak", encode) a.meta.source = { format = "pak", variant = variant or "quake" } diff --git a/src/Rosetta/archive/rpm/init.luau b/src/Rosetta/archive/rpm/init.luau index 6d8e9d5..c0c2afb 100644 --- a/src/Rosetta/archive/rpm/init.luau +++ b/src/Rosetta/archive/rpm/init.luau @@ -1,13 +1,7 @@ --!strict --- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature --- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in --- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with --- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload --- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed --- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not --- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package --- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio" --- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms. +-- archive/rpm: RPM v3 / v4 (rpm.org, LSB package format; no code ported): 96-byte lead, signature header (8-byte +-- aligned), main header; the payload (gzip / bzip2 / xz / lzma / zstd / none) is cpio; %ghost files not listed. +-- Not supported: writing, signature / digest checks, "stripped cpio" (files over 4 GiB), delta rpms. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,7 +24,7 @@ local Rpm = { } export type DecodeOptions = { - maxBytes: number?, -- the largest decompressed payload (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 1e6 } @@ -39,7 +33,6 @@ local LEAD_MAGIC = "\237\171\238\219" local HEADER_MAGIC = "\142\173\232\1" local RPMFILE_GHOST = 64 --- the tags meta.rpm names local NAMES: { [number]: string } = { [1000] = "name", [1001] = "version", @@ -73,7 +66,6 @@ function Rpm.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a header structure at p -> { [tag] = value }, end offset | nil, Err local function header(b: buffer, p: number, e: number): (any, any) if p + 16 > e then return nil, Err.new(Err.TRUNCATED, "header past the end", p) @@ -146,7 +138,6 @@ local function header(b: buffer, p: number, e: number): (any, any) return tags, se end --- the file list of the header: { name, size, mode, mtime, link, user, group, flags } local function files(tags: { [number]: any }): { any } local names: { string } = {} local bn, dn, di = tags[1117], tags[1118], tags[1116] @@ -181,7 +172,6 @@ local function strip(name: string): string return (string.gsub(name, "^%.?/+", "")) end --- the payload: decompressed, then its cpio entries by stripped name local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?) local n = e - p local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 } @@ -313,7 +303,6 @@ function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local a, err = Rpm.decode(r, opts) if not a then diff --git a/src/Rosetta/archive/tar/init.luau b/src/Rosetta/archive/tar/init.luau index 373ab15..6d43abc 100644 --- a/src/Rosetta/archive/tar/init.luau +++ b/src/Rosetta/archive/tar/init.luau @@ -1,9 +1,6 @@ --!strict --- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value --- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() + --- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which --- unwraps the single-stream archive and sniffs again (meta.compression names the outer format). --- Not supported: sparse files, multi-volume archives. +-- archive/tar: tar archives (ustar, pax, GNU long names; containers/Tar). Supports: read (lazy), write from any +-- Archive. Not supported: sparse files, multi-volume archives. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -110,7 +107,6 @@ function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write() function TarFormat.new(): any local a = Archive.new("tar", encode) a.meta.source = { format = "tar" } diff --git a/src/Rosetta/archive/uu/init.luau b/src/Rosetta/archive/uu/init.luau index 34efa09..e50d159 100644 --- a/src/Rosetta/archive/uu/init.luau +++ b/src/Rosetta/archive/uu/init.luau @@ -1,11 +1,7 @@ --!strict --- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin " block of a --- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode); --- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each --- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and --- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils --- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings --- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex). +-- archive/uu: uuencode (POSIX), xxencode and GNU "begin-base64" blocks, one entry each (variant detected per block); +-- written as GNU sharutils does (45 bytes a line, "`" for zero; base64 60 characters + "===="). Not supported: postings +-- split over several files, yEnc (archive/yenc), BinHex (archive/binhex). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,11 +19,11 @@ local Uu = { caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, } -export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30 +export type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 export type EncodeOptions = { variant: ("uu" | "xx" | "base64")?, -- default "uu" - mode: number?, -- file mode when the entry has none (default 0o644) - name: string?, -- the name of a buffer / string value (default "data") + mode: number?, -- default 0o644 + name: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -50,7 +46,6 @@ function Uu.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the value of character c in a variant, or nil local function value(c: number, xx: boolean): number? if xx then return XX_VALUE[c] @@ -61,7 +56,6 @@ local function value(c: number, xx: boolean): number? return nil end --- does a data line fit the variant: every character valid and the length matching the count character local function fits(line: string, xx: boolean): boolean local n = value(string.byte(line, 1) or 0, xx) if not n then @@ -79,7 +73,6 @@ local function fits(line: string, xx: boolean): boolean return true end --- decode the uu / xx lines of a block into a buffer (nil, message on a bad line) local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?) local total = 0 for _, l in lines do @@ -266,7 +259,6 @@ function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant }) function Uu.new(): any local a = Archive.new("uu", encoder) a.meta.source = { format = "uu" } diff --git a/src/Rosetta/archive/vpk/init.luau b/src/Rosetta/archive/vpk/init.luau index 8a09ab5..a1ee106 100644 --- a/src/Rosetta/archive/vpk/init.luau +++ b/src/Rosetta/archive/vpk/init.luau @@ -1,13 +1,7 @@ --!strict --- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the --- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes --- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the --- numbered part files "_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes --- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's --- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload), --- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the --- Valve Developer Community VPK file format page; no code taken. --- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. +-- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes, +-- embedded (index 0x7fff) or part-file data ("_NNN.vpk"), CRC-32 checked; writes one self-contained v2 file +-- with its MD5s. Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,10 +23,10 @@ local Vpk = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - verify: boolean?, -- check each entry's CRC-32 on read (default true) - resolve: ((name: string) -> (buffer | string)?)?, -- the part files ("pak01_000.vpk", ...) + verify: boolean?, -- default true + resolve: ((name: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - name: string?, -- the directory file's name ("pak01_dir.vpk"), for the part file names + name: string?, -- "pak01_dir.vpk" -> "pak01_000.vpk" maxEntries: number?, -- default 1e6 } export type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2) @@ -55,7 +49,6 @@ local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Vpk.encode(archive, opts) end --- the part file `index` as a buffer (cached per archive) local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?) local cache: { [number]: buffer } = {} local prefix = "pak01" @@ -307,7 +300,6 @@ function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write() function Vpk.new(version: number?): any local a = Archive.new("vpk", encode) a.meta.source = { format = "vpk", version = version or 2 } diff --git a/src/Rosetta/archive/wad/Map.luau b/src/Rosetta/archive/wad/Map.luau index 3959981..0ec6051 100644 --- a/src/Rosetta/archive/wad/Map.luau +++ b/src/Rosetta/archive/wad/Map.luau @@ -1,12 +1,7 @@ --!strict --- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS, --- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a --- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with --- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the --- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one --- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z --- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not --- supported. +-- archive/wad/Map: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) to tables and a Scene, with +-- vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the Unofficial Doom Specs and +-- the Hexen specs; no code taken. Not supported: UDMF (TEXTMAP). local Types = require("@rosetta/Types") local Polygon = require("@rosetta/codecs/model/Polygon") @@ -29,7 +24,6 @@ export type MapData = { vertices: { number }, -- x1, y1, x2, y2, ... sectors: { Sector }, } --- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows export type Textures = { size: (kind: string, name: string) -> (number?, number?), image: ((kind: string, name: string) -> Types.Image?)?, @@ -46,7 +40,6 @@ local function side(v: number): number? return if v == 0xFFFF then nil else v + 1 end --- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump) function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?) for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do if not lumps[k] then @@ -144,9 +137,8 @@ function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string end -- ------------------------------------------------------------------------------------------------ sector outlines --- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1; --- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks; --- chains that do not close are dropped +-- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest +-- right turn at forks; unclosed chains dropped local function loops(m: MapData): { [number]: { { number } } } local edges: { [number]: { { number } } } = {} local nv = #m.vertices // 2 @@ -247,7 +239,6 @@ type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 --- scene(m, tex, name) -> Scene function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene local batches: { [string]: Batch } = {} local order: { string } = {} @@ -269,7 +260,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene end local V = m.vertices local nv = #V // 2 - -- floors and ceilings local secLoops = loops(m) for sec, ls in secLoops do local s = m.sectors[sec] @@ -301,7 +291,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene end end end - -- walls local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number) if tname == "-" or tname == "" or zt <= zb then return @@ -363,7 +352,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene end end end - -- the scene local scene = Scene.new() scene.meta.up = "z" local mesh: Types.Mesh = { name = name, primitives = {} } @@ -410,7 +398,6 @@ function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene table.insert(scene.meshes, mesh) scene.nodes[1] = { name = name, children = {}, mesh = 1 } scene.roots[1] = 1 - -- things, on the floor of the sector under them for i, th in m.things do local z = th.z or 0 for sec, ls in secLoops do diff --git a/src/Rosetta/archive/wad/Picture.luau b/src/Rosetta/archive/wad/Picture.luau index c6b0a30..0e86e38 100644 --- a/src/Rosetta/archive/wad/Picture.luau +++ b/src/Rosetta/archive/wad/Picture.luau @@ -1,16 +1,12 @@ --!strict --!native --- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column --- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of --- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative) --- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip). --- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's --- r_data.c description; no code taken. Never throws: every read is checked against the lump's end. +-- archive/wad/Picture: Doom picture lumps (column posts: topdelta / length / pad / pixels / pad; DeePsea tall patches: +-- a topdelta not above the previous is relative) and raw flats to rgba8, from the Unofficial Doom Specs and r_data.c; +-- no code taken. Transparent pixels are 0. local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 local Picture = {} --- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it) function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) if n < 8 then return nil, 0, 0, 0 @@ -28,7 +24,6 @@ function Picture.header(b: buffer, at: number, n: number): (number?, number, num return w, h, readi16(b, at + 4), readi16(b, at + 6) end --- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed) function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) local stop = at + n for x = 0, w - 1 do @@ -63,7 +58,6 @@ function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buff return true, nil end --- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits) function Picture.flatSize(n: number): (number?, number) if n == 4096 then return 64, 64 @@ -84,15 +78,12 @@ function Picture.flatSize(n: number): (number?, number) return nil, 0 end --- flat(b, at, w, h, pal, out): raw indexes, row by row function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) for i = 0, w * h - 1 do writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) end end --- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy), --- clipped (composite wall textures from patches) function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do diff --git a/src/Rosetta/archive/wad/init.luau b/src/Rosetta/archive/wad/init.luau index 080d9e2..41ff289 100644 --- a/src/Rosetta/archive/wad/init.luau +++ b/src/Rosetta/archive/wad/init.luau @@ -1,20 +1,7 @@ --!strict --- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the --- standard Archive and written from any Archive value, plus the lumps as game data: --- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map --- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer --- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image --- (meta.offset = { left, top } for pictures; transparent pixels alpha 0) --- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES) --- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts) --- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene --- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map) --- Entry names: the lump names, except lumps of a map, named "/" ("MAP01/THINGS"), and later lumps --- repeating an earlier name, named "~" (n = 2, 3, ...), so every entry is unique; writing strips both again --- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom --- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken. --- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant, --- big-endian (Jaguar) WADs, compressed Jaguar lumps. +-- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps, +-- palettes, pictures, wall textures and maps. Entry names: "/", repeats "~". Not supported: UDMF +-- geometry (lumps listed), Strife's TEXTURE variant, big-endian (Jaguar) WADs, compressed Jaguar lumps. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -39,18 +26,18 @@ local Wad = { export type DecodeOptions = { maxEntries: number? } -- default 1e6 export type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD" export type Lump = { - name: string, -- the lump name as stored (upper case) - entry: string, -- the Archive entry name - index: number, -- 1-based position in the directory + name: string, + entry: string, + index: number, offset: number, size: number, - namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers) - map: string?, -- the map this lump belongs to + namespace: string?, -- between *_START / *_END markers + map: string?, marker: boolean?, -- a zero-size marker (F_START, MAP01, ...) } export type MapOptions = { - textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true) - palette: number?, -- PLAYPAL palette index (default 0) + textures: boolean?, -- default true + palette: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ constants @@ -139,7 +126,6 @@ function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if isMapMarker then map, udmf = name, nextName == "TEXTMAP" end - -- namespaces local marker: boolean = false local pre = string.match(name, "^(%w+)_START$") local post = string.match(name, "^(%w+)_END$") @@ -215,7 +201,7 @@ local function info(a: any): any return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil end --- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given +-- the last lump named name (PWAD order: later lumps override) local function find(w: any, name: string, ns: string?): Lump? local up = string.upper(name) local best: Lump? = nil @@ -238,20 +224,17 @@ local function find(w: any, name: string, ns: string?): Lump? return best end --- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write() function Wad.new(kind: ("IWAD" | "PWAD")?): any local a = Archive.new("wad", encode) a.meta.source = { format = "wad", type = kind or "PWAD" } return a end --- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD) function Wad.lumps(a: any): { Lump }? local w = info(a) return w and w.lumps end --- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) local w = info(a) if not w then @@ -265,8 +248,6 @@ function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil end --- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic) --- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding. function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?) local w = info(a) if not w then @@ -307,7 +288,6 @@ function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? return img, nil end --- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } } local function textureDefs(w: any): { [string]: any } if w.textures then return w.textures @@ -359,7 +339,6 @@ local function textureDefs(w: any): { [string]: any } return defs end --- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette) function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?) local w = info(a) if not w then @@ -383,7 +362,6 @@ function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types. return img, nil end --- maps(a) -> { map names } in file order function Wad.maps(a: any): { string } local w = info(a) local out: { string } = {} @@ -399,7 +377,6 @@ function Wad.maps(a: any): { string } return out end --- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references) function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) local w = info(a) if not w then @@ -425,9 +402,6 @@ function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) return m, nil end --- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and --- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes --- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?) local m, err = Wad.mapData(a, name) if not m then diff --git a/src/Rosetta/archive/xz/init.luau b/src/Rosetta/archive/xz/init.luau index 20b342f..9420c24 100644 --- a/src/Rosetta/archive/xz/init.luau +++ b/src/Rosetta/archive/xz/init.luau @@ -1,10 +1,7 @@ --!strict --- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one --- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block --- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters +-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma). +-- Supports: concatenated streams, padding, checks none / CRC-32 / CRC-64 (SHA-256 unverified), LZMA2, delta, BCJ -- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters. --- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true: --- the api unwraps an inner archive (a .tar.xz loads as the tar). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,8 +21,8 @@ local Xz = { } export type DecodeOptions = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + name: string?, } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/archive/yenc/init.luau b/src/Rosetta/archive/yenc/init.luau index 89134ae..ee013b8 100644 --- a/src/Rosetta/archive/yenc/init.luau +++ b/src/Rosetta/archive/yenc/init.luau @@ -1,11 +1,7 @@ --!strict --- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive: --- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart --- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified --- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a --- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one --- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space --- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first). +-- archive/yenc: yEnc 1.3 (=ybegin / =ypart / =yend, byte + 42, "=" escapes; Jürgen Helbing's draft): parts in one text +-- joined, pcrc32 / crc32 / size verified; writes one 128-character-line part per file, escaping NUL, LF, CR, "=" and a +-- leading / trailing TAB, space or ".", as uuenview / yencode do. Not supported: parts spread over several files. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,10 +19,10 @@ local Yenc = { caps = { decode = true, encode = true, multipart = true }, } -export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30 +export type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 export type EncodeOptions = { - line: number?, -- characters per line (default 128) - name: string?, -- the name of a buffer / string value (default "data") + line: number?, -- default 128 + name: string?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -53,7 +49,6 @@ local function fields(line: string): { [string]: string } return f end --- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out) local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number local lim = buffer.len(out) local esc = false @@ -78,7 +73,6 @@ local function decodeData(src: buffer, i: number, j: number, out: buffer, o: num return o end --- count the decoded bytes of the data lines [i, j) local function countData(src: buffer, i: number, j: number): number local n, esc = 0, false for p = i, j - 1 do @@ -267,7 +261,6 @@ function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line }) function Yenc.new(): any local a = Archive.new("yenc", encoder) a.meta.source = { format = "yenc" } diff --git a/src/Rosetta/archive/z/init.luau b/src/Rosetta/archive/z/init.luau index 77c5f84..8664c20 100644 --- a/src/Rosetta/archive/z/init.luau +++ b/src/Rosetta/archive/z/init.luau @@ -1,9 +1,7 @@ --!strict --- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one --- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a --- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed, --- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is --- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files. +-- archive/z: Unix compress (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream archive of one +-- entry (codecs/compress/UnixCompress). Supports: read; write byte for byte as ncompress (several entries: a .tar.Z). +-- Not supported: pack (.z, 1F 1E) and compact (1F FF) files. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -22,8 +20,8 @@ local Z = { } export type DecodeOptions = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - name: string?, -- the file name (the api passes it): names the entry + maxBytes: number?, -- default 2^30 + name: string?, } export type EncodeOptions = { maxBits: number?, -- 9..16 (compress -b), default 16 @@ -39,7 +37,6 @@ function Z.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the entry name: the file name without .Z; .taz / .tz name a tar local function entryName(opts: DecodeOptions): string local name = Archive.streamName(opts, { "z" }) local stem, ext = string.match(name, "^(.+)%.(%w+)$") @@ -84,7 +81,6 @@ function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- new(data?, name?) -> a .Z Archive holding one entry function Z.new(data: (buffer | string)?, name: string?): any local a = Archive.new("z", encode) a.meta.stream = true diff --git a/src/Rosetta/archive/zip/init.luau b/src/Rosetta/archive/zip/init.luau index 4ec5ab7..c10b68e 100644 --- a/src/Rosetta/archive/zip/init.luau +++ b/src/Rosetta/archive/zip/init.luau @@ -1,18 +1,7 @@ --!strict --- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip. --- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new --- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments, --- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated --- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed. --- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2, --- LZMA, zstd entries are listed but not readable), multi-disk archives. --- --- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf) --- for _, e in a:list() do print(e.name, e.size, e.method) end --- local data = a:read("dir/file.txt") --- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() } --- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" }) --- local b = Zip.create() -- an empty archive +-- archive/zip: ZIP archives on containers/Zip, absorbed from zip-luau 121d4b0 (same author) plus a new writer. +-- Supports: stored / deflated entries (CRC-checked), ZIP64, data descriptors, comments, self-extractors, UTF-8 names; +-- writing, unchanged entries copied. Not supported: encryption, methods other than store / deflate, multi-disk. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -32,7 +21,7 @@ local Zip = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - verify: boolean?, -- check every entry's CRC-32 on read (default true) + verify: boolean?, -- default true } export type AddOptions = Container.AddOptions export type WriteOptions = Container.FinishOptions @@ -78,7 +67,6 @@ function Zip.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Archive | nil, Err function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) local zip, err = Container.open(r) if not zip then @@ -87,14 +75,11 @@ function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err return new(zip, not (opts and opts.verify == false)), nil end --- create() -> an empty Archive function Zip.create(): Types.Archive return new(nil, true) end -- ------------------------------------------------------------------------------------------------ encode --- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written --- here), or a plain table { [name] = buffer | string }. function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") @@ -132,9 +117,7 @@ function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- the Archive methods (Types.Archive) --- list() -> { ArchiveEntry } in archive order (+ crc32, comment) function Archive.list(self: any): { Types.ArchiveEntry } local out = {} for _, name in self._order do @@ -165,7 +148,6 @@ function Archive.list(self: any): { Types.ArchiveEntry } return out end --- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup function Archive.read(self: any, name: string): (buffer?, Err.Err?) if type(name) ~= "string" then return nil, Err.new(Err.ARG, "read: name must be a string") @@ -188,7 +170,6 @@ function Archive.read(self: any, name: string): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "no entry " .. name) end --- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/") function Archive.add(self: any, name: string, data: any, opts: AddOptions?) local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) if self._items[name] == nil then @@ -197,7 +178,6 @@ function Archive.add(self: any, name: string, data: any, opts: AddOptions?) self._items[name] = { data = b, opts = opts or {} } end --- remove(name) -> true when there was such an entry function Archive.remove(self: any, name: string): boolean if self._items[name] == nil then return false @@ -210,7 +190,6 @@ function Archive.remove(self: any, name: string): boolean return true end --- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?) local w = Container.writer() for _, name in self._order do diff --git a/src/Rosetta/archive/zoo/init.luau b/src/Rosetta/archive/zoo/init.luau index b33e281..fd8563f 100644 --- a/src/Rosetta/archive/zoo/init.luau +++ b/src/Rosetta/archive/zoo/init.luau @@ -1,10 +1,7 @@ --!strict --- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of --- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers), --- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit --- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read --- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not --- supported: writing, file generations beyond keeping the newest (older versions of a name get ";"). +-- archive/zoo: Zoo 1.x / 2.x (zoo 2.10's zoo.h / ar.h): directory entries type 1 and 2, methods 0 stored, 1 LZW +-- (13-bit), 2 lh5; CRC-16 (ARC) verified; MS-DOS dates as UTC. Not supported: writing, file generations beyond the +-- newest (older versions of a name get ";"). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +22,7 @@ local Zoo = { } export type DecodeOptions = { - maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } diff --git a/src/Rosetta/archive/zst/init.luau b/src/Rosetta/archive/zst/init.luau index 40d5bc0..6c8105e 100644 --- a/src/Rosetta/archive/zst/init.luau +++ b/src/Rosetta/archive/zst/init.luau @@ -1,7 +1,6 @@ --!strict --- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded --- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else --- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only. +-- archive/zst: a Zstandard file (.zst, RFC 8878) as a single-stream archive of one entry (codecs/compress/Zstd). +-- Supports: read; the entry is named after the file without its extension (".tzst" -> ".tar"), else "data". -- Not supported: dictionaries, writing. -- ------------------------------------------------------------------------------------------------ requires @@ -21,9 +20,9 @@ local Zst = { } export type DecodeOptions = { - maxBytes: number?, -- refuse a decompressed size over this (default 2^30) - verify: boolean?, -- check the content checksum (default true) - name: string?, -- the file name, for the entry name (the api passes it) + maxBytes: number?, -- default 2^30 + verify: boolean?, -- default true + name: string?, } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/audio/aac/init.luau b/src/Rosetta/audio/aac/init.luau index 877738f..d53b849 100644 --- a/src/Rosetta/audio/aac/init.luau +++ b/src/Rosetta/audio/aac/init.luau @@ -1,8 +1,7 @@ --!strict --- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams --- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected --- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by --- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM. +-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3). Supports: AAC-LC via codecs/audio/Aac (1-8 +-- channels, every rate), CRC-protected headers, a leading ID3v2 tag, resync, seeking by frame; HE-AAC plays its +-- AAC-LC core. Not supported: writing, ADIF, LATM. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,13 +23,12 @@ local AacFormat = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22) + maxFrames: number?, -- default 2^22 } -- ------------------------------------------------------------------------------------------------ constants local readu8 = buffer.readu8 --- the size of an ID3v2 tag at p (0 if none) local function id3Size(b: buffer, p: number, limit: number): number if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 @@ -43,7 +41,6 @@ local function id3Size(b: buffer, p: number, limit: number): number return 10 + s + footer end --- a few ID3v2.3 / 2.4 text frames -> tags local ID3_TAGS: { [string]: string } = { TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", COMM = "comment", TCOM = "composer", TPE2 = "albumartist", @@ -94,7 +91,6 @@ function AacFormat.sniff(r: Bytes.Reader): number if not h then return 0 end - -- a second header right after the first makes it certain local h2 = Aac.adts(b, p + h.frameSize, limit) if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then return 0.9 @@ -103,7 +99,6 @@ function AacFormat.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the frame index: offsets of every ADTS frame (resyncing over garbage) local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) local b, limit = r.buf, r.limit local p = r.base + id3Size(b, r.base, limit) @@ -112,14 +107,14 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number while p + 7 <= limit do local h = Aac.adts(b, p, limit) if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then - h = nil -- a false sync inside the data + h = nil end if not h then p += 1 continue end if p + h.frameSize > limit then - break -- a truncated last frame + break end if not first then first = h @@ -178,7 +173,7 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, tags = tags, codec = "aac", } - -- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking + -- 1024 samples per ADTS frame; one frame of pre-roll for the overlap return Stream.packets(out, { count = nframes, start = function(i: number): number diff --git a/src/Rosetta/audio/ac3/init.luau b/src/Rosetta/audio/ac3/init.luau index ef195ea..72d7af8 100644 --- a/src/Rosetta/audio/ac3/init.luau +++ b/src/Rosetta/audio/ac3/init.luau @@ -1,10 +1,7 @@ --!strict --- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through --- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) --- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block --- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and --- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). --- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) via codecs/audio/Ac3. Supports: every channel layout (WAVE order, no +-- downmix), 32 / 44.1 / 48 kHz, every bit rate, the CRC check, resync, exact seeking; drc 0 .. 1, off by default. +-- Not supported: writing, E-AC-3 (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,13 +23,13 @@ local Ac3Format = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxFrames: number?, -- refuse streams with more syncframes (default 2^22) - drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full - crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM) + maxFrames: number?, -- default 2^22 + drc: number?, -- 0 = off (default), 1 = full + crc: boolean?, -- default true; a bad frame ends the stream with Err.CHECKSUM } -- ------------------------------------------------------------------------------------------------ sniff --- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format) +-- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than an unknown format function Ac3Format.sniff(r: Bytes.Reader): number local b, p, limit = r.buf, r.pos, r.limit local h = Ac3.header(b, p, limit) @@ -47,7 +44,7 @@ function Ac3Format.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +-- a header counts when the next one follows it, or the data ends local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) local b, limit = r.buf, r.limit local p = r.base @@ -61,7 +58,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number if h and not first and p + h.frameSize + 8 <= limit then local h2 = Ac3.header(b, p + h.frameSize, limit) if not h2 then - h = nil -- a false sync word + h = nil end end if not h then @@ -77,7 +74,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number end end if p + h.frameSize > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, h.frameSize) diff --git a/src/Rosetta/audio/adpcm/init.luau b/src/Rosetta/audio/adpcm/init.luau index 11ff5fa..4f260ff 100644 --- a/src/Rosetta/audio/adpcm/init.luau +++ b/src/Rosetta/audio/adpcm/init.luau @@ -1,20 +1,8 @@ --!strict --- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in --- rosetta. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by --- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such --- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs --- here are the layouts those containers use: --- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first --- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order --- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024) --- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024) --- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime --- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16) --- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients --- live in a header: see audio/brstm and audio/adx). --- --- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 }) --- local raw = Adpcm.encode(a, { codec = "ima" }) +-- audio/adpcm: headerless ADPCM (.adpcm / .ima / .vox) via codecs/audio/Adpcm; sniff is 0, the layout comes from opts. +-- "ima": DVI nibbles, high first; "ima_wav": MS IMA blocks; "ms": MS ADPCM, 7 standard coefficient pairs; "ima_qt": +-- Apple ima4 (34-byte packets, 64 frames); "psx": PS-ADPCM (16-byte frames, 28 samples). Encode: ima, ima_wav, ms. +-- Not supported: raw DSP / ADX (their coefficients live in a header). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -40,10 +28,10 @@ export type Options = { codec: Codec?, -- default "ima" sampleRate: number?, -- default 22050 (decode) channels: number?, -- default 1 (decode) - blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding) - lowFirst: boolean?, -- ima: the low nibble first - interleave: number?, -- psx: bytes per channel before the next channel (default 16) - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + blockAlign: number?, -- ima_wav / ms; default 1024 decoding, 256 * channels encoding + lowFirst: boolean?, + interleave: number?, -- psx: bytes per channel (default 16) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -51,7 +39,7 @@ local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = tru -- ------------------------------------------------------------------------------------------------ sniff function Raw.sniff(_r: Bytes.Reader): number - return 0 -- no header: found by extension or opts.format only + return 0 end -- ------------------------------------------------------------------------------------------------ decode diff --git a/src/Rosetta/audio/adx/init.luau b/src/Rosetta/audio/adx/init.luau index c1509dc..0217acd 100644 --- a/src/Rosetta/audio/adx/init.luau +++ b/src/Rosetta/audio/adx/init.luau @@ -1,15 +1,7 @@ --!strict --- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in --- rosetta; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), --- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder --- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff), --- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and --- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels, --- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and --- exponential (4) encoding types, AHX. --- --- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff) --- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } }) +-- audio/adx: CRI ADX via codecs/audio/Adpcm; header and decoder follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact with it. Supports: encoding type 3, versions 3-5, 1-8 channels, loop +-- points; encode as version 4. Not supported: encrypted ADX (0x0408 / 0x0409), encoding types 2 and 4, AHX. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -32,11 +24,11 @@ local Adx = { -- ------------------------------------------------------------------------------------------------ types export type Loop = { start: number, stop: number } export type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + maxFrames: number?, -- default 2^28 } export type EncodeOptions = { - loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none - cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders) + loop: Loop?, -- frames, stop exclusive; default the source's meta.source.loop + cutoff: number?, -- Hz, default 500 (as CRI's encoders) } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/audio/aiff/init.luau b/src/Rosetta/audio/aiff/init.luau index c6dfdb2..f58681b 100644 --- a/src/Rosetta/audio/aiff/init.luau +++ b/src/Rosetta/audio/aiff/init.luau @@ -1,11 +1,7 @@ --!strict --- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. --- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw --- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated --- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / --- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm; --- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6, --- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. +-- audio/aiff: AIFF / AIFF-C (Apple AIFF 1.3, AIFF-C draft 1991). Supports: PCM 1-32 bits; AIFF-C NONE / twos / +-- sowt / raw / in24 / in32 / fl32 / fl64 / ulaw / alaw / ima4; text chunks as tags; truncated SSND; encode 8-32 bit, +-- sowt, fl32, fl64, ulaw, alaw. Not supported: other compressed AIFF-C codecs, MARK / INST, the ID3 chunk. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,13 +22,12 @@ local Aiff = { } export type DecodeOptions = { - maxFrames: number?, -- refuse more sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } export type EncodeOptions = { sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" - littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only - -- take 16-bit sowt, so other formats return Err.ARG) - aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it) + littleEndian: boolean?, -- 16-bit only, as AIFF-C "sowt" (ffmpeg reads no other sowt); default false + aifc: boolean?, -- default: only when the sample format needs it } -- ------------------------------------------------------------------------------------------------ constants @@ -40,7 +35,6 @@ local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANN local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } local AIFC_VERSION = 0xA2805140 --- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) local function ext80(b: buffer, o: number): number local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) local hi = bit32.byteswap(buffer.readu32(b, o + 2)) @@ -56,7 +50,6 @@ local function ext80(b: buffer, o: number): number return if se >= 0x8000 then -v else v end --- the 10 bytes of x (> 0) as an 80-bit extended float local function writeExt80(w: Bytes.Writer, x: number) if x <= 0 or x ~= x then w:fill(0, 10) @@ -69,7 +62,7 @@ local function writeExt80(w: Bytes.Writer, x: number) while x < 2 ^ e do e -= 1 end - local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local m = x * 2 ^ (63 - e) local hi = math.floor(m / 4294967296) local lo = m - hi * 4294967296 w:u16be(e + 16383) @@ -77,7 +70,6 @@ local function writeExt80(w: Bytes.Writer, x: number) w:u32be(math.floor(lo)) end --- the sample format of a COMM chunk: Pcm format name | nil, message local function sampleFormat(comp: string, bits: number): (string?, string?) if comp == "NONE" or comp == "twos" or comp == "" then if bits >= 1 and bits <= 8 then @@ -118,7 +110,7 @@ local function sampleFormat(comp: string, bits: number): (string?, string?) elseif comp == "alaw" or comp == "ALAW" then return "alaw", nil elseif comp == "ima4" then - return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks + return "ima4", nil end return nil, "compression " .. string.format("%q", comp) end @@ -142,12 +134,11 @@ type Info = { compression: string, aifc: boolean, dataOffset: number, -- absolute in r.buf - dataSize: number, -- bytes of sample data present + dataSize: number, truncated: boolean, tags: Types.Tags, } --- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) local function parse(r: Bytes.Reader): (Info?, Err.Err?) local b = r.buf local base, limit = r.base, r.limit @@ -165,7 +156,7 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) local ssnd: number? = nil local ssndLen = 0 local tags: Types.Tags = {} - -- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body) + -- a FORM size that undercounts still reads the last chunk's body for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start if p + 8 > formEnd then @@ -250,7 +241,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) return fi, nil end --- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) return parse(r) end @@ -300,14 +290,13 @@ function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local aifc = o.aifc or comp ~= "NONE" local w = Bytes.writer(65536) w:string("FORM") - w:u32be(0) -- patched + w:u32be(0) w:string(if aifc then "AIFC" else "AIFF") if aifc then w:string("FVER") w:u32be(4) w:u32be(AIFC_VERSION) end - -- text chunks from the tags for _, pair in TEXT_ORDER do local id, key = pair[1], pair[2] local s = src.tags[key] diff --git a/src/Rosetta/audio/ape/init.luau b/src/Rosetta/audio/ape/init.luau index d4fb67f..42e511a 100644 --- a/src/Rosetta/audio/ape/init.luau +++ b/src/Rosetta/audio/ape/init.luau @@ -1,13 +1,7 @@ --!strict --- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag), --- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end --- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt). --- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32 --- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding. --- --- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5 --- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them --- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/ape: Monkey's Audio (.ape) via codecs/audio/Ape and ApeTag, from the Monkey's Audio SDK 13.28 (BSD 3-clause, +-- licenses/monkeys-audio-LICENSE.txt). Supports: versions 3.95+, every level, 8-32-bit integer and 32-bit float, 1-32 +-- channels, an ID3v2 prefix, seeking by the seek table. Not supported: files before 3.95, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,7 +24,7 @@ local Ape = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - maxFrames: number?, -- decode(): refuse longer streams (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -59,7 +53,6 @@ function Ape.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Ape.open(r, opts) if not dec then @@ -74,7 +67,6 @@ function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) diff --git a/src/Rosetta/audio/au/init.luau b/src/Rosetta/audio/au/init.luau index b50f38c..2c5025e 100644 --- a/src/Rosetta/audio/au/init.luau +++ b/src/Rosetta/audio/au/init.luau @@ -1,9 +1,7 @@ --!strict --- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. --- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), --- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); --- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). --- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. Supports: encodings 1 (mu-law), 2-5 (8-32-bit linear), 6 / 7 +-- (float), 27 (A-law), data size 0xFFFFFFFF (to the end), the annotation as tags.comment; encode to any of them. +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -22,7 +20,7 @@ local Au = { } export type DecodeOptions = { - maxFrames: number?, -- refuse more sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } export type EncodeOptions = { sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" @@ -90,7 +88,7 @@ function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local w = Bytes.writer(65536) w:string(".snd") w:u32be(24 + alen) - w:u32be(0xFFFFFFFF) -- patched + w:u32be(0xFFFFFFFF) w:u32be(spec[1]) w:u32be(src.sampleRate) w:u32be(src.channels) diff --git a/src/Rosetta/audio/brstm/init.luau b/src/Rosetta/audio/brstm/init.luau index 2bf41ef..46b29f3 100644 --- a/src/Rosetta/audio/brstm/init.luau +++ b/src/Rosetta/audio/brstm/init.luau @@ -1,13 +1,7 @@ --!strict --- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and --- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in rosetta; the layouts --- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP --- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16 --- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop } --- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions --- (the whole stream plays), the track table (channels are not grouped). --- --- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec) +-- audio/brstm: Nintendo BRSTM (Wii, "RSTM", BE), BCSTM (3DS, "CSTM", LE), BFSTM (Wii U BE / Switch LE, "FSTM"); layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), bit-exact. Supports: DSP ADPCM, PCM16 / PCM8, 1-255 +-- channels, loop points. Read only. Not supported: BCSTM IMA ADPCM, BRSTM 0.1, BFSTM regions, the track table. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,7 +22,7 @@ local Brstm = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -44,7 +38,6 @@ function Brstm.sniff(r: Bytes.Reader): number return if bom == "\254\255" or bom == "\255\254" then 1 else 0 end --- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect function Brstm.variant(r: Bytes.Reader): string? local m = r:peek(4) return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil @@ -65,8 +58,6 @@ function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err end -- ------------------------------------------------------------------------------------------------ open --- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file --- start); a read out of range records the error in .err and returns 0 local function view(r: Bytes.Reader, be: boolean) local v = { err = nil :: string? } local size = r.limit - r.base @@ -109,7 +100,7 @@ type Layout = { frames: number, blockSize: number, lastPadded: number, - data: number, -- the first block (absolute in the file) + data: number, -- absolute adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2) hist: number?, -- the per-block history table: (yn1, yn2) per channel per block histEntries: number, diff --git a/src/Rosetta/audio/caf/init.luau b/src/Rosetta/audio/caf/init.luau index 29cf6ac..763518e 100644 --- a/src/Rosetta/audio/caf/init.luau +++ b/src/Rosetta/audio/caf/init.luau @@ -1,10 +1,7 @@ --!strict --- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear --- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac, --- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown --- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / --- 24-bit) with info tags. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported: --- other compressed formats (UNSUPPORTED). +-- audio/caf: Apple Core Audio Format (CAF 1.0 spec). Supports: linear PCM (8-32-bit integer, 32 / 64-bit float, either +-- endian), ALAC, AAC-LC (kuki esds), mu-law, A-law, IMA4; pakt trimming, data size -1, info tags, seeking; encode PCM +-- (16 / 24-bit BE, 32-bit float) and ALAC (16 / 20 / 24-bit). Not supported: other compressed formats. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,7 +26,7 @@ local Caf = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxPackets: number?, -- packet table limit (default 2^24) + maxPackets: number?, -- default 2^24 } export type EncodeOptions = { codec: ("pcm" | "alac")?, -- default "alac" @@ -48,7 +45,6 @@ for k, v in INFO_TAGS do TAG_INFO[v] = k end --- mu-law / A-law -> linear 16-bit local ULAW, ALAW = table.create(256, 0), table.create(256, 0) for i = 0, 255 do local u = 255 - i @@ -76,7 +72,7 @@ end type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } type Parsed = { desc: Desc, - dataStart: number, -- absolute offset of the audio data + dataStart: number, -- absolute dataEnd: number, cookie: buffer?, packets: { number }?, -- sizes (pakt) @@ -236,7 +232,6 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) return p, nil end --- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err type Source = { channels: number, rate: number, @@ -333,7 +328,6 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) } return src, nil end - -- packetised codecs local sizes = p.packets if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none if d.bytesPerPacket > 0 then @@ -505,7 +499,6 @@ local function chunk(w: Bytes.Writer, typ: string, size: number) w:i64be(size) end --- encode(audio | decoder, opts?) -> buffer | nil, Err function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then @@ -523,7 +516,6 @@ function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if ch < 1 or ch > 64 or sr <= 0 then return nil, Err.new(Err.ARG, "bad sample rate / channels") end - -- the source frames local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if not isAudio and type(value.read) ~= "function" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") diff --git a/src/Rosetta/audio/flac/Meta.luau b/src/Rosetta/audio/flac/Meta.luau index 12392b8..3b14a5f 100644 --- a/src/Rosetta/audio/flac/Meta.luau +++ b/src/Rosetta/audio/flac/Meta.luau @@ -1,9 +1,7 @@ --!strict --!native --!optimize 2 --- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is --- left in place); every other block is skipped. Nothing throws: bad data gives nil, err. --- Absorbed from flac-luau 7083d0d (same author, no third-party code). +-- audio/flac/Meta: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE blocks; absorbed from flac-luau 7083d0d. local VorbisComment = require("@rosetta/codecs/audio/VorbisComment") local readu8, readu32 = buffer.readu8, buffer.readu32 @@ -51,7 +49,7 @@ export type Info = { seekTable: { SeekPoint }, vendor: string, tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; " - comments: { { key: string, value: string } }, -- every comment in order + comments: { { key: string, value: string } }, pictures: { Picture }, firstFrame: number, -- byte offset just after the last metadata block } @@ -150,7 +148,6 @@ local function picture(b: buffer, p: number, e: number): Picture? return pic end --- Parse the metadata blocks that follow "fLaC" at pos (data ends at len) function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then return nil, "Flac: no fLaC marker" @@ -195,7 +192,7 @@ function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) end end elseif typ == 4 then - vorbisComment(b, p, e, info) -- a broken comment block leaves what was read + vorbisComment(b, p, e, info) elseif typ == 6 then local pic = picture(b, p, e) if pic then diff --git a/src/Rosetta/audio/flac/Stream.luau b/src/Rosetta/audio/flac/Stream.luau index 9cb810b..76c94e6 100644 --- a/src/Rosetta/audio/flac/Stream.luau +++ b/src/Rosetta/audio/flac/Stream.luau @@ -1,11 +1,7 @@ --!strict --!native --!optimize 2 --- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through --- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table, --- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed --- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an --- injected module). Nothing throws: open returns nil, message, code. +-- audio/flac/Stream: streaming FLAC decoder (native and Ogg FLAC); absorbed from flac-luau 7083d0d (same author). local Bytes = require("@rosetta/core/Bytes") local Ogg = require("@rosetta/containers/Ogg") local Frame = require("@rosetta/codecs/audio/Flac/Frame") @@ -41,12 +37,10 @@ export type Decoder = { local Dec = {} Dec.__index = Dec --- the sample number of a frame local function sampleOf(self: any, h: Header): number return if h.variable then h.number else h.number * self._nominal end --- a header that also matches the stream (guards the sync search against false syncs) local function plausible(self: any, h: Header): boolean if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then return false @@ -80,7 +74,6 @@ local function ensure(self: any, n: number) end end --- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end. local function decodeAt(self: any, pos: number): boolean local b, len = self._b, self._len while true do @@ -114,7 +107,7 @@ local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): local ch = self.channels local want = math.floor(tonumber(maxFrames) or 0) if not (want >= 0) then - want = 0 -- negative or NaN + want = 0 end want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 @@ -159,29 +152,23 @@ local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): return out, got end --- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is --- reused when big enough. function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, false, out) end --- The same as interleaved i32 integer samples (bit-exact, right-aligned) function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, true, out) end --- seconds, sample frame of the next frame read() returns function Dec.position(self: any): (number, number) local s = self._fs + self._cur return s / self.sampleRate, s end --- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets --- by sync search, then walks frame headers forward. Returns false if the stream has no frame there. function Dec.seekSample(self: any, t: number): boolean t = math.floor(tonumber(t) or 0) if not (t >= 0) then - t = 0 -- negative or NaN + t = 0 end if self.frames > 0 and t >= self.frames then self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 @@ -228,7 +215,7 @@ function Dec.seekSample(self: any, t: number): boolean self._cur = t - self._fs return true elseif self._fs > t then - return false -- a hole in the stream: we are at the next frame + return false end pos = self._pos else @@ -244,7 +231,6 @@ function Dec.seek(self: any, seconds: number): boolean return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) end --- Find the total length from the last frame (when STREAMINFO does not give it) local function scanLength(self: any): number local len = self._len local step = math.max(65536, 2 * self._si.maxFrameSize) @@ -284,7 +270,6 @@ local function skipId3(b: buffer, base: number, len: number): number return p end --- opts.crc16 = false skips the per-frame CRC-16 check function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) local b, len, container if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then diff --git a/src/Rosetta/audio/flac/init.luau b/src/Rosetta/audio/flac/init.luau index 2d7b268..bc80fbb 100644 --- a/src/Rosetta/audio/flac/init.luau +++ b/src/Rosetta/audio/flac/init.luau @@ -1,19 +1,7 @@ --!strict --- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author, --- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module. --- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals --- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame --- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in --- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when --- STREAMINFO has none. Encode (codecs/audio/Flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels --- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5 --- verification on decode, chained Ogg streams, Ogg FLAC output. --- The codec itself is codecs/audio/Flac; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...) --- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end --- local i32, n = dec:readInt(4096) -- bit-exact integer samples --- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/flac: FLAC (RFC 9639), native and Ogg FLAC; absorbed from flac-luau 7083d0d (same author). Supports: every +-- subframe type, Rice / Rice2, 4-32 bits, 1-8 channels, CRC-16 resync, seeking, an ID3v2 prefix, the main metadata +-- blocks; encode levels 0-8 (libFLAC presets), 4-24 bits. Not supported: MD5 check on decode, chained Ogg, Ogg output. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -37,12 +25,12 @@ local Flac = { -- ------------------------------------------------------------------------------------------------ types export type Decoder = Stream.Decoder export type OpenOptions = { - crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) - maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) + crc16: boolean?, -- default true; a bad frame is skipped by resyncing + maxFrames: number?, -- default 2^28 } export type EncodeOptions = { level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) - bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16) + bits: number?, -- 4..24; default the source's bit depth if 4..24, else 16 blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) padding: number?, -- bytes of PADDING after the metadata (default 0) @@ -79,7 +67,6 @@ function Flac.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Flac.open(r, opts) if not dec then @@ -94,7 +81,6 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er end -- ------------------------------------------------------------------------------------------------ encode --- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then @@ -139,7 +125,6 @@ function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) diff --git a/src/Rosetta/audio/m4a/init.luau b/src/Rosetta/audio/m4a/init.luau index 991de8f..282a55b 100644 --- a/src/Rosetta/audio/m4a/init.luau +++ b/src/Rosetta/audio/m4a/init.luau @@ -1,9 +1,7 @@ --!strict --- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading --- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless --- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures); --- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs --- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files. +-- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC (HE-AAC plays +-- its core), ALAC, edit-list gapless trimming, seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8 +-- channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,13 +27,13 @@ local M4a = { export type DecodeOptions = { track: number?, -- the track id to play (default: the first AAC / ALAC track) gapless: boolean?, -- apply the edit list (default true) - maxSamples: number?, -- sample table limit (default 2^25) + maxSamples: number?, -- default 2^25 } export type EncodeOptions = { bitDepth: number?, -- 16 (default), 20 or 24 frameLength: number?, -- samples per packet, default 4096 tags: Types.Tags?, -- default: the audio's tags - pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures) + pictures: { { mime: string, data: buffer } }?, -- default: audio.meta.pictures } -- ------------------------------------------------------------------------------------------------ constants @@ -57,7 +55,6 @@ function M4a.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats type PacketDecoder = { channels: number, sampleRate: number, @@ -121,7 +118,6 @@ local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") end --- open(r, opts?) -> Types.Decoder | nil, Err function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local o: DecodeOptions = opts or {} local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) @@ -155,7 +151,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E end local p = pd :: PacketDecoder local channels, sr = p.channels, p.sampleRate - -- media ticks -> sample frames local tickScale = sr / t.timescale local gapless = o.gapless ~= false local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 @@ -219,7 +214,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E }) end --- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = M4a.open(r, opts) if not dec then @@ -234,7 +228,6 @@ function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then @@ -254,7 +247,6 @@ function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local ints = table.create(fl * ch, 0) local floor = math.floor local readf32 = buffer.readf32 - -- frames from an Audio buffer or a streaming Decoder local src: buffer, srcFrames = nil :: any, 0 local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if isAudio then diff --git a/src/Rosetta/audio/mp3/Index.luau b/src/Rosetta/audio/mp3/Index.luau index 244a03b..998a8be 100644 --- a/src/Rosetta/audio/mp3/Index.luau +++ b/src/Rosetta/audio/mp3/Index.luau @@ -1,10 +1,7 @@ --!strict --!native --!optimize 2 --- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame --- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so --- it knows in advance which frames give output and where each one's samples land. That makes the total length --- exact and seeking sample-accurate. Never throws. +-- audio/mp3/Index: the frame index as minimp3_ex's mp3dec_load_buf walks it, simulating the layer III bit reservoir. local Header = require("@rosetta/codecs/audio/Mpa/Header") local Core = require("@rosetta/codecs/audio/Mpa/Core") @@ -29,7 +26,6 @@ export type Index = { main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II) outTotal: number, -- samples (per channel) of a continuous decode, delay not cut bytes: number, -- audio bytes in indexed frames - -- format of the first frame sampleRate: number, channels: number, -- the most channels of any frame layer: number, @@ -89,7 +85,6 @@ function Index.build(b: buffer, start: number, stop: number): Index? pos += i end if fs < 4 or fs > Core.MAX_FRAME then - -- cannot happen with a well-formed header, but never index an impossible frame prev = -1 pos += max(fs, 1) continue diff --git a/src/Rosetta/audio/mp3/Stream.luau b/src/Rosetta/audio/mp3/Stream.luau index ec5d8b5..2f346b1 100644 --- a/src/Rosetta/audio/mp3/Stream.luau +++ b/src/Rosetta/audio/mp3/Stream.luau @@ -1,7 +1,6 @@ --!strict --!optimize 2 --- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact --- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws. +-- audio/mp3/Stream: streaming Decoder over the frame index (gapless, exact seeking); from mp3-luau (same author). local Core = require("@rosetta/codecs/audio/Mpa/Core") local Index = require("@rosetta/audio/mp3/Index") @@ -44,7 +43,6 @@ export type Decoder = typeof(setmetatable( Decoder )) --- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build) function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count @@ -92,7 +90,6 @@ function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): end --- decodes frames until one has samples inside [minAbs, endAbs); false at the end local function fill(self: Decoder): boolean local idx = self._idx local n = idx.n @@ -127,9 +124,6 @@ local function fill(self: Decoder): boolean return false end --- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream. --- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a --- smaller out is ignored. function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number) local ch = self.channels local want = tonumber(maxFrames) or 4096 @@ -138,7 +132,7 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, end want = floor(max(0, min(want, self.frames - self._pos))) if out and buffer.len(out) < want * ch * 4 then - out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough) + out = nil end local dst = out or buffer.create(want * ch * 4) local got = 0 @@ -163,8 +157,6 @@ function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, return dst, got end --- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier --- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped. function Decoder.seek(self: Decoder, seconds: number) local hz = self.sampleRate local target = floor((tonumber(seconds) or 0) * hz + 0.5) @@ -172,7 +164,6 @@ function Decoder.seek(self: Decoder, seconds: number) self:seekFrame(target) end --- Seeks to a sample frame (0 .. frames). function Decoder.seekFrame(self: Decoder, target: number) target = tonumber(target) or 0 if target ~= target then @@ -190,7 +181,6 @@ function Decoder.seekFrame(self: Decoder, target: number) self._cur = n return end - -- last frame starting at or before abs local lo, hi = 0, n - 1 while lo < hi do local mid = (lo + hi + 1) // 2 @@ -218,12 +208,10 @@ function Decoder.seekFrame(self: Decoder, target: number) self._cur = s end --- Current position: (seconds, sample frame) function Decoder.position(self: Decoder): (number, number) return self._pos / self.sampleRate, self._pos end --- Decodes everything from the current position to the end: (buffer of interleaved f32, frames) function Decoder.readAll(self: Decoder): (buffer, number) return self:read(max(0, self.frames - self._pos)) end diff --git a/src/Rosetta/audio/mp3/Tags.luau b/src/Rosetta/audio/mp3/Tags.luau index d4be6d2..ad84cb6 100644 --- a/src/Rosetta/audio/mp3/Tags.luau +++ b/src/Rosetta/audio/mp3/Tags.luau @@ -1,8 +1,6 @@ --!strict --!optimize 2 --- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 / --- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way --- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short. +-- audio/mp3/Tags: ID3v2.2-2.4 and ID3v1 / 1.1 tags (APEv2 skipped); the audio range as minimp3_ex's mp3dec_skip_id3. local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local ru8 = buffer.readu8 @@ -97,7 +95,6 @@ local function decodeText(b: buffer, i: number, j: number, enc: number): string return table.concat(out) end --- trim trailing NULs / spaces, join multi-value NUL separators with " / " local function clean(s: string): string s = string.gsub(s, "[%z%s]+$", "") s = string.gsub(s, "%z+", " / ") @@ -166,7 +163,6 @@ local function setField(tags: any, id: string, text: string) end end --- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags local function parseV2(b: buffer, o: number, size: number, tags: any) local ver = ru8(b, o + 3) local flags = ru8(b, o + 5) @@ -258,9 +254,6 @@ local function v1String(b: buffer, o: number, n: number): string return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) end --- Parses tags and returns (tags, audio start, audio end) for the buffer b. --- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?, --- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? } function Tags.parse(b: buffer): (any, number, number) local len = buffer.len(b) local tags: any = { raw = {} } diff --git a/src/Rosetta/audio/mp3/init.luau b/src/Rosetta/audio/mp3/init.luau index 76a9356..655d3d8 100644 --- a/src/Rosetta/audio/mp3/init.luau +++ b/src/Rosetta/audio/mp3/init.luau @@ -1,18 +1,7 @@ --!strict --- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf --- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5 --- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing / --- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync --- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped). --- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, codecs/audio/Mpa/Encode3 + Encode2): layer III --- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from --- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel --- extension, CRC checks, VBR / Xing output. --- The codec itself is codecs/audio/Mpa; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay, --- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll()) --- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file) +-- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of +-- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless, +-- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -39,7 +28,7 @@ local Mp3 = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31) + maxFrames: number?, -- default 2^31 } export type Decoder = Stream.Decoder export type EncodeOptions = { @@ -58,7 +47,6 @@ export type EncodeOptions = { local MAX_FRAMES = 2 ^ 31 -- ------------------------------------------------------------------------------------------------ sniff --- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on function Mp3.sniff(r: Bytes.Reader): number local b, p, lim = r.buf, r.pos, r.limit local id3 = false @@ -87,7 +75,6 @@ function Mp3.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts) -> Types.Audio (the whole stream, through open) function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Mp3.open(r, opts) if not dec then @@ -113,7 +100,6 @@ local ID3_FRAMES = { { "composer", "TCOM" }, } --- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write local function id3Tag(tags: { [string]: any }): buffer? local w = Bytes.writer(256) local seen: { [string]: boolean } = {} @@ -162,7 +148,6 @@ local function id3Tag(tags: { [string]: any }): buffer? return out:finish() end --- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then @@ -174,8 +159,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "layer must be 2 or 3") end local Enc = if layer == 3 then Encode3 else Encode2 - -- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else - -- the highest); other input rates go through codecs/audio/Resample local rate = o.sampleRate or src.sampleRate if o.sampleRate and not Enc.RATES[o.sampleRate] then return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate))) @@ -209,7 +192,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if layer == 2 and mode == "joint" then mode = "stereo" end - -- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) if type(bitrate) == "number" and bitrate >= 1000 then bitrate /= 1000 @@ -234,7 +216,6 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment) local function stringTags(t: any): { [string]: string } local out: { [string]: string } = {} for k, v in t do @@ -245,7 +226,6 @@ local function stringTags(t: any): { [string]: string } return out end --- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) local b = r.buf if r.base ~= 0 or r.limit ~= buffer.len(b) then @@ -273,6 +253,6 @@ function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end) +Mp3.Tags = Tags return Mp3 diff --git a/src/Rosetta/audio/mpc/init.luau b/src/Rosetta/audio/mpc/init.luau index 023580c..c9d653c 100644 --- a/src/Rosetta/audio/mpc/init.luau +++ b/src/Rosetta/audio/mpc/init.luau @@ -1,10 +1,7 @@ --!strict --- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec --- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 / --- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking --- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags --- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported: --- writing, SV4 - SV6 (UNSUPPORTED), chapters. +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp) SV7 and SV8 via codecs/audio/Musepack (a libmpcdec port). Supports: mono / +-- stereo, 32-48 kHz, gapless length, seeking (SV8 exact; SV7 with 32 frames of pre-roll, as libmpcdec), APEv2 tags, +-- an ID3v2 prefix, ReplayGain in meta. Not supported: writing, SV4-SV6 (UNSUPPORTED), chapters. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,11 +24,10 @@ local Mpc = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31) + maxFrames: number?, -- default 2^31 } -- ------------------------------------------------------------------------------------------------ constants --- the size of an ID3v2 tag at p (0 if none) local function id3v2(b: buffer, p: number, limit: number): number if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 diff --git a/src/Rosetta/audio/opus/Encode.luau b/src/Rosetta/audio/opus/Encode.luau index d28c797..64cc53a 100644 --- a/src/Rosetta/audio/opus/Encode.luau +++ b/src/Rosetta/audio/opus/Encode.luau @@ -1,9 +1,5 @@ --!strict --- audio/opus/Encode: Ogg Opus writing (RFC 7845) around codecs/audio/Opus/CeltEncoder: CELT-only packets (TOC config 31: --- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor + --- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at --- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in --- rosetta. +-- audio/opus/Encode: Ogg Opus writing (RFC 7845), CELT only (TOC config 31: full band, 20 ms, code 0), family 0. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Ogg = require("@rosetta/containers/Ogg") @@ -24,7 +20,6 @@ export type Options = { local floor = math.floor --- encode(audio | decoder, opts) -> buffer | nil, Err function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) local o: Options = opts or {} local src, serr = Pcm.source(value) @@ -41,12 +36,11 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) end local bitrate = o.bitrate or 64000 * ch if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then - bitrate *= 1000 -- kbit/s + bitrate *= 1000 end if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end - -- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats if rate ~= 48000 then local rs, rerr = Resample.source(src, 48000) if not rs then @@ -68,7 +62,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) local FRAME = CeltEncoder.FRAME local preSkip = CeltEncoder.DELAY local packets = (n48 + preSkip + FRAME - 1) // FRAME - -- zero padding to whole frames for i = n48 * ch + 1, packets * FRAME * ch do pcm[i] = 0 end @@ -100,7 +93,6 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) tw:string(field) end s:packet(tw:finish(), 0, { flush = true }) - -- audio local toc = 31 * 8 + (if ch == 2 then 4 else 0) for p = 0, packets - 1 do local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) diff --git a/src/Rosetta/audio/opus/init.luau b/src/Rosetta/audio/opus/init.luau index a5eecfe..0006c3a 100644 --- a/src/Rosetta/audio/opus/init.luau +++ b/src/Rosetta/audio/opus/init.luau @@ -1,22 +1,7 @@ --!strict --- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a --- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK --- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255). --- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, --- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms --- pre-roll), damaged files (concealment). Output is always 48 kHz f32. --- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant --- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. --- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics --- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only). --- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an --- optional output buffer; decode() fully decodes to an Audio. --- The codec itself is codecs/audio/Opus; this folder maps it onto the file (container, tags, seeking, writing). --- --- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... --- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio --- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets --- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) +-- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD: +-- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC; +-- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -75,7 +60,7 @@ export type Head = { mapping: { number }, } --- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message. +-- OpusHead (RFC 7845 section 5.1) local function parseHead(b: buffer, off: number, size: number): (Head?, string?) if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then return nil, "not an OpusHead packet" @@ -127,8 +112,7 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?) return head, nil end --- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined --- with "; "), the raw fields +-- OpusTags (RFC 7845 section 5.2) local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field }) if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then return "", {}, {} @@ -173,7 +157,6 @@ Opus.parseTags = parseTags Opus.SAMPLE_RATE = SAMPLE_RATE -- ------------------------------------------------------------------------------------------------ sniff --- 1 when the file starts with an Ogg page whose first packet is an OpusHead function Opus.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 @@ -186,7 +169,6 @@ function Opus.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32) function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Opus.open(r, opts) if not dec then @@ -196,7 +178,6 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) return Encode.encode(value, opts) end @@ -205,7 +186,6 @@ end local Stream = {} Stream.__index = Stream --- Decodes the next packet into the pending buffer. Returns false at the end of the stream. local function decodeNext(self: any): boolean local p = self.demux:nextPacket(self.serial) if p == nil then @@ -239,8 +219,6 @@ local function decodeNext(self: any): boolean return true end --- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if --- given and big enough) is filled instead of a new buffer. function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number) local ch = self.channels local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0 @@ -255,7 +233,6 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb break end end - -- skip decoded samples before the next wanted one (pre-skip, seek pre-roll) local s = self.pendStart + self.pendPos if s < self.next then self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) @@ -280,17 +257,15 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb buffer.copy(trimmed, 0, out, 0, got * ch * 4) out = trimmed end - self.endSample = self.next -- the stream ended early (truncated file) + self.endSample = self.next end return out, got end --- current playback position in seconds function Stream.position(self: any): number return (self.next - self.preSkip) / SAMPLE_RATE end --- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll function Stream.seek(self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) @@ -315,7 +290,6 @@ function Stream.seek(self: any, seconds: number) self.next = target end --- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer) function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) if not demux then diff --git a/src/Rosetta/audio/qoa/init.luau b/src/Rosetta/audio/qoa/init.luau index a019dec..ac13eb2 100644 --- a/src/Rosetta/audio/qoa/init.luau +++ b/src/Rosetta/audio/qoa/init.luau @@ -1,13 +1,7 @@ --!strict --- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in --- rosetta. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order --- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its --- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame): --- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel --- count or rate change mid-stream (Err.UNSUPPORTED). --- --- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder --- local file = Qoa.encode(audio) +-- audio/qoa: QOA "Quite OK Audio" via codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). Supports: static and +-- streaming files, 1-255 channels, rates up to 16777215 Hz, frame-accurate seeking; encode byte-for-byte as qoa_encode, +-- 1-8 channels. Not supported: channel count or rate changes mid-stream. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,7 +23,7 @@ local Qoa = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -122,7 +116,6 @@ function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) return nil, h.err end local buf = r.buf - -- the frame index: offsets, first frames local offs, starts = {}, {} local p, total = r.base + 8, 0 local ch, rate = 0, 0 diff --git a/src/Rosetta/audio/tta/init.luau b/src/Rosetta/audio/tta/init.luau index dcca011..a4a4305 100644 --- a/src/Rosetta/audio/tta/init.luau +++ b/src/Rosetta/audio/tta/init.luau @@ -1,11 +1,7 @@ --!strict --- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the --- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag). --- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count. --- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding. --- --- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt --- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/tta: True Audio (.tta, TTA1) via codecs/audio/Tta, from the TTA1 format description. Supports: 8 / 16 / 24 +-- bits, any channel count, seeking by the seek table, APEv2 tags, an ID3v2 prefix. Not supported: password-protected +-- files, TTA2, ID3v2 contents, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,11 +24,10 @@ local Tta = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - maxFrames: number?, -- decode(): refuse longer streams (default 2^28) + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff --- the size of an ID3v2 tag at the reader's start (0 when none) local function id3Size(r: Bytes.Reader): number if r:peek(3) ~= "ID3" then return 0 @@ -54,7 +49,6 @@ function Tta.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Tta.open(r, opts) if not dec then @@ -69,7 +63,6 @@ function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) diff --git a/src/Rosetta/audio/vag/init.luau b/src/Rosetta/audio/vag/init.luau index 37cfd4f..502559c 100644 --- a/src/Rosetta/audio/vag/init.luau +++ b/src/Rosetta/audio/vag/init.luau @@ -1,16 +1,7 @@ --!strict --- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same --- extension), over codecs/audio/Adpcm. New in rosetta; the header variants and the PS-ADPCM decoding follow --- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono --- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and --- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono / --- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it. --- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame --- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game --- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...). --- --- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant) --- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } }) +-- audio/vag: Sony VAG (PS-ADPCM: VAGp mono, VAGi stereo) and KVAG (IMA); layouts follow vgmstream r2117 (ISC, +-- licenses/vgmstream-LICENSE.txt), bit-exact, Sony's leading blank frame included. Supports: loop points; encode VAGp / +-- VAGi. Not supported: HEVAG (0x00020001 / 0x00030000), game-specific variants (pGAV, VAG1 / VAG2, Jak, ...). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,7 +24,7 @@ local Vag = { -- ------------------------------------------------------------------------------------------------ types export type Loop = { start: number, stop: number } export type DecodeOptions = { - maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) + maxFrames: number?, -- default 2^28 } export type EncodeOptions = { loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the @@ -144,8 +135,7 @@ function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end --- flag 3), or nil +-- vgmstream's loop reading: channel 0's first start flag 6 and first end flag 3 local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop? local ls, le = -1, -1 for k = 0, frames - 1 do diff --git a/src/Rosetta/audio/voc/init.luau b/src/Rosetta/audio/voc/init.luau index 49b5a90..fe5ab0e 100644 --- a/src/Rosetta/audio/voc/init.luau +++ b/src/Rosetta/audio/voc/init.luau @@ -1,11 +1,7 @@ --!strict --- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. --- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), --- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit --- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played --- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version --- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM --- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). +-- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9 +-- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9 +-- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,7 +20,7 @@ local Voc = { } export type DecodeOptions = { - maxFrames: number?, -- refuse more sample frames (default 2^28) + maxFrames: number?, -- default 2^28 } export type EncodeOptions = { sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" @@ -73,7 +69,6 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E local truncated = false local tags: Types.Tags = {} local p = base + hsize - -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? if channels == 0 then channels, rate = ch, sr @@ -177,7 +172,7 @@ function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E local n = s.frames * channels if s.fmt then Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) - end -- silence: the buffer is already zero + end o += n * 4 end a.tags = tags @@ -238,7 +233,7 @@ function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) blockAt = w:tell() blockFrames = 0 w:u8(9) - w:u24le(0) -- patched + w:u24le(0) w:u32le(src.sampleRate) w:u8(spec[3]) w:u8(src.channels) diff --git a/src/Rosetta/audio/vorbis/Encode.luau b/src/Rosetta/audio/vorbis/Encode.luau index d75363b..0914c6a 100644 --- a/src/Rosetta/audio/vorbis/Encode.luau +++ b/src/Rosetta/audio/vorbis/Encode.luau @@ -1,15 +1,8 @@ --!strict --!native --!optimize 2 --- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification --- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the --- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a --- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality- --- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer --- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then --- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian --- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact --- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws. +-- audio/vorbis/Encode: Vorbis I encoder in Ogg, from the Vorbis I spec (no libvorbis code): long blocks only (2048), +-- one floor 1 per channel (30 posts), square-polar coupling, residue type 2, a fixed codebook set with Laplacian lengths. local Mdct = require("@rosetta/codecs/audio/Mdct") local Pcm = require("@rosetta/codecs/audio/Pcm") local VorbisComment = require("@rosetta/codecs/audio/VorbisComment") @@ -99,7 +92,6 @@ type Book = { values: number, -- lookup1 values per dimension } --- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) local function huffmanLengths(w: { number }): { number } local n = #w local total = 0 @@ -112,7 +104,6 @@ local function huffmanLengths(w: { number }): { number } return lens end local minw = total * 2 ^ -20 - -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues local order = table.create(n, 0) for i = 1, n do order[i] = i @@ -128,8 +119,8 @@ local function huffmanLengths(w: { number }): { number } end return a < b end) - local q1, h1 = order, 1 -- leaves, ascending - local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local q1, h1 = order, 1 + local q2, h2, t2 = table.create(n, 0), 1, 0 local nextId = n local function pop(): number local a = if h1 <= n then q1[h1] else nil @@ -161,7 +152,7 @@ local function huffmanLengths(w: { number }): { number } return lens end --- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +-- the spec's codeword assignment (lowest free leaf, in entry order) local function assign(lens: { number }): { number } local codes = table.create(#lens, 0) local available = table.create(33, 0) @@ -208,7 +199,6 @@ local function makeBook(dims: number, entries: number, weight: (number) -> numbe return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } end --- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book local values = 2 * h + 1 local entries = values ^ dims @@ -302,7 +292,6 @@ do table.insert(xs, x) end table.sort(xs) - -- bisection order over the sorted list local queue = { { 1, #xs } } local qh = 1 while qh <= #queue do @@ -424,7 +413,7 @@ local function floorVal(Y: { number }, j: number): number end end end - return 0 -- unreachable for t in range; fall back to the prediction + return 0 end -- ------------------------------------------------------------------------------------------------ headers @@ -559,7 +548,6 @@ export type Options = { serial: number, } --- the residue of one partition: vectors of each pass for class c local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) local b = CLASS_BOOKS[c][pass] if b < 0 then @@ -639,7 +627,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) local k = 0 local lastWanted = -1 -- the last packet index needed (known once the input ends) while true do - -- shift in the next 1024 input samples (zeros past the end) for c = 1, ch do local fr = frame[c] table.move(fr, N2 + 1, N, 1) @@ -678,8 +665,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) end -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) - -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) - -- MDCT per channel local energy = 0 for c = 1, ch do local fr = frame[c] @@ -821,7 +806,6 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?) return mux:finish(), nil end --- the codebooks (tests check the Huffman lengths are a valid prefix code) Encode.BOOKS = BOOKS return Encode diff --git a/src/Rosetta/audio/vorbis/init.luau b/src/Rosetta/audio/vorbis/init.luau index 5cd7aa9..b7e1c97 100644 --- a/src/Rosetta/audio/vorbis/init.luau +++ b/src/Rosetta/audio/vorbis/init.luau @@ -1,15 +1,7 @@ --!strict --- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau --- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct, --- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last --- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position). --- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2, --- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level --- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic --- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook --- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since --- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder. --- The codec itself is codecs/audio/Vorbis; this folder maps it onto the file (container, tags, seeking, writing). +-- audio/vorbis: Ogg Vorbis (Vorbis I spec; RFC 5215); the decoder is a port of stb_vorbis 1.22 (public domain / MIT, +-- licenses/stb_vorbis-LICENSE.txt) with libvorbis' sample-exact trimming and seeking. Supports: 1-255 channels, +-- floor 1, residues 0-2, packetDecoder for Matroska / MP4; an encoder. Not supported: floor 0, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -42,7 +34,6 @@ export type EncodeOptions = { } -- ------------------------------------------------------------------------------------------------ constants --- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels) local function waveOrder(ch: number): { number } local m = Pcm.WAVE_FROM_VORBIS[ch] if m then @@ -55,7 +46,6 @@ local function waveOrder(ch: number): { number } return id end --- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?) local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id then @@ -98,7 +88,6 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then @@ -130,7 +119,6 @@ end local Stream = {} Stream.__index = Stream --- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) local lo = math.max(g0, self.startG, self.skipTo) if hi > g0 + count then @@ -152,7 +140,6 @@ local function copyOut(self: any, count: number): { { number } } return t end --- decode packets until something is queued; false at the end of the stream local function decodeMore(self: any): boolean local reader, st = self.reader, self.st while not self.ended do @@ -251,7 +238,6 @@ function Stream.position(self: any): number return (self.next - self.startG) / self.sampleRate end --- back to the first audio packet local function restart(self: any) local r = self.reader r:rewind() @@ -430,11 +416,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three --- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. --- local pd = Vorbis.packetDecoder(h1, h2, h3) --- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] --- pd:reset() -- after a seek +-- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?) local function pk(b: buffer): any return { data = b, offset = 0, size = buffer.len(b) } diff --git a/src/Rosetta/audio/wav/Codecs.luau b/src/Rosetta/audio/wav/Codecs.luau index 5b219bc..32757d8 100644 --- a/src/Rosetta/audio/wav/Codecs.luau +++ b/src/Rosetta/audio/wav/Codecs.luau @@ -1,10 +1,7 @@ --!strict --!native --!optimize 2 --- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The --- ADPCM block decoders moved to codecs/audio/Adpcm. --- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau) --- only calls them with ranges it has checked against the source length and the output size. +-- audio/wav/Codecs: PCM / float / G.711 sample loops into interleaved f32 and back; absorbed from wav-luau fd9a909. local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 @@ -13,8 +10,7 @@ local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, b local Codecs = {} --- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian, --- from src[off] to dst (f32) starting at sample index d. +-- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) local o = d * 4 if bytes == 1 then @@ -64,7 +60,6 @@ function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: num end end --- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values. function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, tmp: buffer) local o = d * 4 @@ -95,7 +90,6 @@ function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: n end end --- 8-bit companded (A-law / mu-law) through a 256-entry f32 table function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) local o = d * 4 for i = 0, count - 1 do @@ -103,13 +97,10 @@ function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: num end end --- copy frames from a block cache into the output: count f32 values function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) end --- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"), --- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller. function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) local so = s * 4 if kind == "f32" then diff --git a/src/Rosetta/audio/wav/init.luau b/src/Rosetta/audio/wav/init.luau index 72acb75..2998b76 100644 --- a/src/Rosetta/audio/wav/init.luau +++ b/src/Rosetta/audio/wav/init.luau @@ -1,18 +1,8 @@ --!strict --!optimize 2 --- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no --- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder. --- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE --- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF --- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has). --- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when --- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags, --- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request. --- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. --- --- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames --- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio --- local file = Wav.encode(audio, { sampleFormat = "s24" }) +-- audio/wav: WAVE in RIFF / RIFX / RF64 / BW64; absorbed from wav-luau fd9a909 (same author). Supports: PCM 8-32 bit, +-- float 32 / 64, A-law, mu-law, IMA / MS ADPCM, EXTENSIBLE, LIST/INFO tags, data size 0 / 0xFFFFFFFF (to the end); +-- encode PCM and f32, EXTENSIBLE and RF64 as ffmpeg. Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -36,14 +26,14 @@ local Wav = { -- ------------------------------------------------------------------------------------------------ types export type Tags = { [string]: string } export type OpenOptions = { - maxBytes: number?, -- unused (the file is already in memory); kept for symmetry + maxBytes: number?, } export type EncodeOptions = { sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16" rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count) - tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...) + tags: Tags?, -- default: the Audio's tags rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF) } @@ -144,7 +134,6 @@ export type Decoder = typeof(setmetatable( )) local function trimTag(s: string): string - -- strip trailing NULs / spaces local e = #s while e > 0 do local c = string.byte(s, e) @@ -166,7 +155,6 @@ function Wav.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole file function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Wav.open(r, opts) if not dec then @@ -191,7 +179,6 @@ local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTY local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } local BLOCK = 65536 -- frames per data piece when streaming a Decoder --- the body of the encoder: { buffer } pieces of the file | nil, Err local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") @@ -312,19 +299,15 @@ local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): return w:finish({ parts = asParts }) end --- encode(audio or decoder, opts?) -> buffer | nil, Err function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return encodeParts(value, opts, false) end --- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other --- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?) return encodeParts(value, opts, true) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) if type(r) == "buffer" or type(r) == "string" then r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any) @@ -550,8 +533,6 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples --- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end). function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number) local ch = self.channels local req = math.floor(tonumber(maxFrames) or 0) @@ -581,7 +562,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, self._pos += want return dst, want end - -- block formats: decode a block into the cache, copy out of it local spb, ba = self._spb, self.blockAlign local cache = self._cache :: buffer local done = 0 @@ -612,7 +592,6 @@ function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, return dst, done end --- Moves to a time in seconds (clamped to the stream). function Decoder.seek(self: Decoder, seconds: number) local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) if f ~= f then @@ -621,7 +600,6 @@ function Decoder.seek(self: Decoder, seconds: number) self._pos = math.clamp(f, 0, self.frames) end --- Moves to a frame index (clamped). function Decoder.seekFrame(self: Decoder, frame: number) local f = math.floor(tonumber(frame) or 0) if f ~= f then @@ -630,12 +608,10 @@ function Decoder.seekFrame(self: Decoder, frame: number) self._pos = math.clamp(f, 0, self.frames) end --- Current position in seconds. function Decoder.position(self: Decoder): number return self._pos / self.sampleRate end --- Current position in frames. function Decoder.tell(self: Decoder): number return self._pos end diff --git a/src/Rosetta/audio/wavpack/init.luau b/src/Rosetta/audio/wavpack/init.luau index 4ac5202..9efe420 100644 --- a/src/Rosetta/audio/wavpack/init.luau +++ b/src/Rosetta/audio/wavpack/init.luau @@ -1,17 +1,7 @@ --!strict --- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction --- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0 --- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt). --- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the --- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("c") --- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking --- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file --- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding. --- --- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ... --- local f32, n = dec:read(4096) --- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them --- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio +-- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's +-- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as +-- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -35,9 +25,9 @@ local WavPack = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given) - resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths) - name: string?, -- the file name (the api passes it) - maxFrames: number?, -- decode(): refuse longer streams (default 2^28) + resolve: ((uri: string) -> buffer?)?, + name: string?, + maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -50,7 +40,6 @@ function WavPack.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = WavPack.open(r, opts) if not dec then @@ -67,7 +56,6 @@ end -- ------------------------------------------------------------------------------------------------ open type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? } --- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence local function index(buf: buffer, base: number, limit: number): (Index?, string?) local at = base local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } @@ -142,7 +130,6 @@ local function correctionFile(opts: OpenOptions?): buffer? return nil end --- open(r, opts?) -> Decoder | nil, Err function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) @@ -167,7 +154,6 @@ function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err local count = #idx.offsets local last = idx.starts[count] + idx.samples[count] local frames = if idx.total >= 0 then math.min(idx.total, last) else last - -- the correction file: its frames by start sample local cbuf = if info.hybrid then correctionFile(opts) else nil local cfor: { [number]: { number } } = {} if cbuf then diff --git a/src/Rosetta/cad/step/Brep.luau b/src/Rosetta/cad/step/Brep.luau index de05024..00da05c 100644 --- a/src/Rosetta/cad/step/Brep.luau +++ b/src/Rosetta/cad/step/Brep.luau @@ -1,16 +1,7 @@ --!strict --- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; rosetta never requires a kernel). Normalises --- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a --- Scene. Interpreted on purpose: the plug-in's errors unwind through here. --- --- The interface (every function may throw; results are checked): --- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?, --- body.color? = Color3 | { r, g, b } | { 1, 2, 3 }) --- write(bodies: { Body }, opts) -> string bodies -> STEP text --- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based --- triples }, faceOf = { [triangle] = Face (face.color?) }? } --- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read = --- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body). +-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; never required by rosetta), called under pcall. +-- Interface (each may throw): read(text, opts) -> { bodies, stats? }; write(bodies, opts) -> text; +-- tessellate(body, opts) -> { positions, normals?, indices (1-based triples), faceOf? }; or brep-luau's modules as-is. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") @@ -30,7 +21,7 @@ local function rgbOf(c: any): (number?, number?, number?) if type(c) == "table" then return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] end - return (c :: any).R, (c :: any).G, (c :: any).B -- Color3 + return (c :: any).R, (c :: any).G, (c :: any).B end) if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then return r, g, b @@ -38,7 +29,6 @@ local function rgbOf(c: any): (number?, number?, number?) return nil, nil, nil end --- plugin(p) -> the normalised interface, or nil + the reason function Brep.plugin(p: any): (Plugin?, string?) if type(p) ~= "table" then return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" @@ -82,7 +72,6 @@ function Brep.plugin(p: any): (Plugin?, string?) return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" end --- find(opts) -> the plug-in from opts.brep or opts.plugins.brep function Brep.find(opts: any): (Plugin?, Err.Err?) local p = nil if type(opts) == "table" then @@ -98,7 +87,6 @@ function Brep.find(opts: any): (Plugin?, Err.Err?) return plug, nil end --- read(plug, text, opts) -> bodies, result | nil, Err function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?) local ok, res = pcall(plug.read, text, opts) if not ok then @@ -110,7 +98,6 @@ function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err return res.bodies, res, nil end --- write(plug, bodies, opts) -> text | nil, Err function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?) local w = plug.write if not w then @@ -130,7 +117,7 @@ local function xyz(p: any): (number, number, number) if type(p) == "table" then return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 end - return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3 + return (p :: any).X, (p :: any).Y, (p :: any).Z end local function linear(c: number): number @@ -138,8 +125,7 @@ local function linear(c: number): number return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 end --- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by --- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written) +-- baseColor = the STEP colour converted from sRGB to linear; extras.color = the colour as written function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?) local tess = plug.tessellate if not tess then @@ -196,7 +182,6 @@ function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Er end end local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) - -- triangles grouped by colour, in first-seen order local groups: { { mat: number, tris: { number } } } = {} local byMat: { [number]: { mat: number, tris: { number } } } = {} local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {} diff --git a/src/Rosetta/cad/step/Parse.luau b/src/Rosetta/cad/step/Parse.luau index 1a86bf3..6080b3d 100644 --- a/src/Rosetta/cad/step/Parse.luau +++ b/src/Rosetta/cad/step/Parse.luau @@ -1,15 +1,7 @@ --!strict --!native --- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass --- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`), --- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every --- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary, --- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset. --- --- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v }; --- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`) --- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so --- the writer prints it back as a real; integral numbers without that mark are written as integers. +-- cad/step/Parse: ISO 10303-21 text -> header + entity instances, one pass; never throws (nil, message, offset). +-- An integral real (`0.`, `1.E2`) is marked in its holder's metatable (`__reals = { [index | "value"] = true }`). local Parse = {} local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor @@ -32,7 +24,6 @@ local function fail(ctx: Ctx, msg: string, at: number): nil return nil end --- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error) local function skip(ctx: Ctx, i: number): number local s, n = ctx.s, ctx.n while i <= n do @@ -60,7 +51,6 @@ local function isWord(c: number): boolean return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) end --- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none local function keyword(ctx: Ctx, i: number): (string?, number) local s, n = ctx.s, ctx.n local j = i @@ -77,7 +67,6 @@ local function keyword(ctx: Ctx, i: number): (string?, number) return string.upper(ssub(s, i, j - 1)), j end --- UTF-8 of a code point local function utf8char(cp: number): string if cp < 0x80 then return schar(cp) @@ -100,9 +89,7 @@ local function hexAt(s: string, i: number, k: number): number? return tonumber(h, 16) end --- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\, --- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed) --- pass through. +-- Part 21 escapes: '' \\ \S\c \X\hh \X2\..\X0\ \X4\..\X0\; \P?\ ignored (ISO 8859-1); raw bytes >= 0x80 pass through function Parse.unescape(raw: string): string if not sfind(raw, "[\\']") then return raw @@ -185,11 +172,9 @@ local function markReal(t: { [any]: any }, key: any) mt.__reals[key] = true end --- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure) local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) - -- i is just past "(" local s = ctx.s local out = {} i = skip(ctx, i) @@ -309,7 +294,6 @@ value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean) end Parse.value = value --- the simple record at i: NAME(params) -> type, args, next local function record(ctx: Ctx, i: number): (string?, { any }?, number) local word, j = keyword(ctx, i) if not word then @@ -326,7 +310,6 @@ local function record(ctx: Ctx, i: number): (string?, { any }?, number) return word, args, k end --- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil local function expect(ctx: Ctx, i: number, ch: number, what: string): number? i = skip(ctx, i) if sbyte(ctx.s, i) ~= ch then @@ -353,7 +336,6 @@ export type Result = { terminated: boolean, } --- parse(s, opts) -> Result | nil, message, offset (1-based position in s) function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } local res: Result = { diff --git a/src/Rosetta/cad/step/Write.luau b/src/Rosetta/cad/step/Write.luau index 0045126..6543a5c 100644 --- a/src/Rosetta/cad/step/Write.luau +++ b/src/Rosetta/cad/step/Write.luau @@ -1,16 +1,13 @@ --!strict --!native --- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings --- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid --- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws: --- failures return nil, message. +-- cad/step/Write: header + entity instances -> ISO 10303-21 text (escaped strings, shortest round-trip reals). local Write = {} local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge local MAX_DEPTH = 100 --- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E) +-- Part 21 real: a '.' always, upper-case E function Write.real(v: number): string? if v ~= v or v == huge or v == -huge then return nil @@ -45,7 +42,6 @@ local function hex(v: number, k: number): string return table.concat(out) end --- a string's Part 21 literal (with the quotes) function Write.str(s: string): string if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ return "'" .. s .. "'" @@ -72,7 +68,6 @@ function Write.str(s: string): string end i += 1 else - -- a UTF-8 sequence -> code point local cp: number? = nil local len = 1 if c >= 0xC2 and c < 0xE0 then @@ -235,7 +230,6 @@ value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean end Write.value = value --- record(ctx, type, args) -> appends TYPE(args) function Write.record(ctx: Ctx, t: any, args: any): boolean if not isName(t) then ctx.err = "bad entity type " .. tostring(t) diff --git a/src/Rosetta/cad/step/init.luau b/src/Rosetta/cad/step/init.luau index da6c4e6..1d05f65 100644 --- a/src/Rosetta/cad/step/init.luau +++ b/src/Rosetta/cad/step/init.luau @@ -1,24 +1,7 @@ --!strict --- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema). --- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME / --- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and --- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers; --- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to --- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" }, --- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE / --- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same --- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII). --- --- B-rep bodies and tessellation come from an injected kernel, never required by rosetta: --- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text, --- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } } --- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = } --- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) / --- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies / --- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up, --- millimetres (meta.unit = 0.001). --- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT), --- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored). +-- cad/step: STEP physical files (ISO 10303-21 eds 1-3; AP203 / AP214 / AP242 / any schema). Supports: header, DATA +-- sections, simple and complex instances, every parameter kind, ANCHOR / REFERENCE / SIGNATURE kept raw; B-rep via the +-- injected plug-in (cad/step/Brep). Not supported: STEP-XML (10303-28), .stpZ, ed. 3 value instances, \P?\ code pages. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,19 +24,19 @@ local Step = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 2^30) - maxEntities: number?, -- refuse more instances (default 2^24) + maxBytes: number?, -- default 2^30 + maxEntities: number?, -- default 2^24 } export type EncodeOptions = { - schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA - name: string?, -- FILE_NAME name (default: the header's, else "model") - timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00") - crlf: boolean?, -- CRLF line ends (default LF) + schema: string?, -- overrides the header's FILE_SCHEMA + name: string?, -- default: the header's, else "model" + timestamp: string?, -- default "1970-01-01T00:00:00" + crlf: boolean?, } export type BrepOptions = { - brep: any?, -- the plug-in (else opts.plugins.brep) + brep: any?, plugins: { [string]: any }?, - chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead + chord: number?, -- millimetres (default 0.05) tess: { [string]: any }?, } @@ -68,7 +51,6 @@ local SCHEMAS = { } Step.SCHEMAS = SCHEMAS --- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself local function schemaOf(name: string): string local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then @@ -203,7 +185,6 @@ function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) end end end - -- entities by section, in id order local ids = {} for id, e in cad.entities do if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then @@ -257,7 +238,6 @@ function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- get(cad, id | { ref = id }) -> the entity function Step.get(cad: Types.Cad, id: any): Types.StepEntity? if type(id) == "table" then id = id.ref @@ -265,7 +245,6 @@ function Step.get(cad: Types.Cad, id: any): Types.StepEntity? return cad.entities[id] end --- ids(cad) -> the instance ids in ascending order function Step.ids(cad: Types.Cad): { number } local out = {} for id in cad.entities do @@ -275,7 +254,6 @@ function Step.ids(cad: Types.Cad): { number } return out end --- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending function Step.byType(cad: Types.Cad, name: string): { number } local n = string.upper(name) local out = {} @@ -295,7 +273,6 @@ function Step.byType(cad: Types.Cad, name: string): { number } return out end --- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance) function Step.part(e: Types.StepEntity?, name: string): { any }? if not e then return nil @@ -313,7 +290,6 @@ function Step.part(e: Types.StepEntity?, name: string): { any }? return nil end --- add(cad, type, args) -> id: a new instance after the highest id function Step.add(cad: Types.Cad, type: string, args: { any }): number local top = 0 for id in cad.entities do @@ -327,7 +303,6 @@ function Step.add(cad: Types.Cad, type: string, args: { any }): number return id end --- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`) function Step.real(t: { [any]: any }, key: any): { [any]: any } local mt: any = getmetatable(t) if not mt then @@ -338,12 +313,10 @@ function Step.real(t: { [any]: any }, key: any): { [any]: any } return t end --- new(schema?) -> an empty Cad ("AP214" by default) function Step.new(schema: string?): Types.Cad return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } end --- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason Step.plugin = Brep.plugin local function textOf(cad: Types.Cad): (string?, Err.Err?) @@ -354,7 +327,6 @@ local function textOf(cad: Types.Cad): (string?, Err.Err?) return buffer.tostring(buf), nil end --- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) local plug, perr = Brep.find(opts) if not plug then @@ -371,7 +343,6 @@ function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) return bodies, res end --- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?) if type(bodies) ~= "table" then return nil, Err.new(Err.ARG, "needs a list of bodies") @@ -387,7 +358,6 @@ function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err. return Step.decode(Bytes.reader(buffer.fromstring(text))) end --- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?) local plug, perr = Brep.find(opts) if not plug then diff --git a/src/Rosetta/data/cbor/Codec.luau b/src/Rosetta/data/cbor/Codec.luau index f99bb05..26ff2ff 100644 --- a/src/Rosetta/data/cbor/Codec.luau +++ b/src/Rosetta/data/cbor/Codec.luau @@ -1,7 +1,6 @@ --!strict --!native --- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil, --- message, offset. +-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset). local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -16,14 +15,13 @@ end } local SimpleMeta = { __tostring = function(s: any): string return "cbor.simple(" .. s.value .. ")" end } --- tagged(tag, value) -> { tag, value }: a tag this library does not interpret function Codec.tagged(tag: number, value: any): { tag: number, value: any } return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any end function Codec.isTagged(v: any): boolean return type(v) == "table" and getmetatable(v) == TaggedMeta end --- simple(n) -> an unassigned simple value (0..19, 32..255) +-- unassigned simple values: 0..19, 32..255 function Codec.simple(n: number): { value: number } return setmetatable({ value = n }, SimpleMeta) :: any end @@ -34,7 +32,6 @@ Codec.undefined = table.freeze(setmetatable({}, { __tostring = function() return "undefined" end })) --- decimal text of a big-endian unsigned byte string (any length) local function bigText(s: string): string local limbs = {} -- base 1e7, little-endian for i = 1, #s do @@ -58,7 +55,6 @@ local function bigText(s: string): string end return table.concat(out) end --- text + 1 for a decimal string local function incText(s: string): string local digits: { number } = table.create(#s) :: { number } for i = 1, #s do @@ -81,18 +77,18 @@ local function incText(s: string): string end export type DecodeOptions = { - bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text - null: any?, -- the value for null (default Types.null) - undefined: any?, -- the value for undefined (default Codec.undefined) + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + undefined: any?, -- default Codec.undefined maxDepth: number?, -- default 512 - dates: boolean?, -- tags 0 / 1 as Types.Date (default true) + dates: boolean?, -- default true } type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean } -local BREAK = {} -- the 0xFF stop code, inside indefinite items +local BREAK = {} -- 0xFF break stop code --- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31) +-- additional information 31: indefinite length local function arg(st: St, ai: number): (number?, string?, string?) local r = st.r if ai < 24 then @@ -169,7 +165,7 @@ local function tag(st: St, t: number, v: any): (any, string?) n = n * 256 + string.byte(s, i) end if n >= 9007199254740992 then - -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum) + -- read back from the exact text: correctly rounded, unlike the running sum local text = bigText(s) if t == 3 then text = incText(text) @@ -347,7 +343,6 @@ function item(st: St, depth: number): (any, string?) if v == BREAK then return nil, "unexpected break" end - -- bignum content arrives as a buffer: hand the tag its bytes if (n == 2 or n == 3) and type(v) == "buffer" then return tag(st, n, buffer.tostring(v)) end @@ -355,7 +350,6 @@ function item(st: St, depth: number): (any, string?) end end --- decode(r, opts) -> value | nil, message, offset (one item; r is left after it) function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { @@ -378,10 +372,10 @@ end -- ------------------------------------------------------------------------------------------------ encode export type EncodeOptions = { - compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) - emptyTable: ("array" | "map")?, -- a plain empty table (default "array") - dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds + compactFloats: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" + dates: ("string" | "epoch")?, -- tag 0 text (default) or tag 1 epoch seconds maxDepth: number?, -- default 512 (also catches cycles) } @@ -410,7 +404,6 @@ local function head(w: Bytes.Writer, major: number, n: number) end end --- the half-float bits of x when x is exactly representable, else nil local function toHalf(x: number): number? if x ~= x then return 0x7E00 @@ -423,7 +416,7 @@ local function toHalf(x: number): number? if a == 0 then return sign end - local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1 + local m, e = math.frexp(a) local exp = e - 1 + 15 if exp >= 31 then return nil @@ -554,7 +547,6 @@ local function enc(st: ESt, v: any, depth: number): boolean return true end --- encode(v, opts) -> buffer | nil, message function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { diff --git a/src/Rosetta/data/cbor/init.luau b/src/Rosetta/data/cbor/init.luau index 9867917..4865c60 100644 --- a/src/Rosetta/data/cbor/init.luau +++ b/src/Rosetta/data/cbor/init.luau @@ -1,10 +1,7 @@ --!strict --- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half / --- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text, --- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n), --- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences --- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats, --- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values. +-- data/cbor: CBOR (RFC 8949), new code. Supports: every major type, indefinite lengths, half / single / double +-- floats, tags 0 / 1 (Types.Date), 2 / 3 (bignums), 55799 (stripped), others as Cbor.tagged; simple values; sequences +-- (RFC 8742). Encode: shortest heads, definite lengths. Not supported: other semantic tags (kept as tagged values). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -22,11 +19,11 @@ local Cbor = { } export type DecodeOptions = Codec.DecodeOptions & { - all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item) + all: boolean?, -- default false } export type EncodeOptions = Codec.EncodeOptions & { - all: boolean?, -- the value is an array of items, written as a sequence - selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7) + all: boolean?, + selfDescribe: boolean?, -- 55799 tag prefix (d9 d9 f7) } -- ------------------------------------------------------------------------------------------------ sniff @@ -91,9 +88,9 @@ function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag +Cbor.tagged = Codec.tagged Cbor.isTagged = Codec.isTagged -Cbor.simple = Codec.simple -- simple(n) -> a simple value +Cbor.simple = Codec.simple Cbor.isSimple = Codec.isSimple Cbor.undefined = Codec.undefined diff --git a/src/Rosetta/data/csv/init.luau b/src/Rosetta/data/csv/init.luau index b4638f8..8f733b4 100644 --- a/src/Rosetta/data/csv/init.luau +++ b/src/Rosetta/data/csv/init.luau @@ -1,10 +1,7 @@ --!strict --- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any --- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded --- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column --- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only --- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters --- other than the doubled quote, multi-byte delimiters. +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv), new code. Supports: one-byte or +-- "auto" delimiter, quoted fields with "" and line breaks, CRLF / LF / CR, header rows, numbers by option; encode +-- quotes minimally (QUOTE_MINIMAL) or always. Not supported: other escapes, multi-byte delimiters. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,19 +21,19 @@ local Csv = { } export type DecodeOptions = { - delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |) - quote: string?, -- the quote byte (default '"') - header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays) - numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string) - maxRows: number?, -- refuse more rows (default unlimited) + delimiter: string?, -- default ","; "auto": one of , ; tab | + quote: string?, -- default '"' + header: boolean?, -- default false + numbers: boolean?, -- default false + maxRows: number?, -- default unlimited } export type EncodeOptions = { delimiter: string?, -- default "," quote: string?, -- default '"' - newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv) - quoteAll: boolean?, -- quote every field (default false: only those that need it) - columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order) - header: boolean?, -- keyed rows: write the header row (default true) + newline: string?, -- default "\r\n" (RFC 4180) + quoteAll: boolean?, -- default false + columns: { string }?, -- default: keys in first-seen order + header: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants @@ -80,7 +77,6 @@ local function guess(s: string, q: string): string return best end --- rows(s, opts) -> { { string } } | nil, Err function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) local o: DecodeOptions = opts or {} local q = o.quote or '"' @@ -98,7 +94,7 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) local row: { string } = {} local n = #s local i = 1 - local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) + local rowEmpty = true while true do local c = byte(s, i) local field: string @@ -141,7 +137,6 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) rowEmpty = false i += 1 else - -- end of the row: CRLF / LF / CR / end of data if c == 13 and byte(s, i + 1) == 10 then i += 2 elseif c ~= nil then diff --git a/src/Rosetta/data/ini/init.luau b/src/Rosetta/data/ini/init.luau index 48f9f70..9a9914d 100644 --- a/src/Rosetta/data/ini/init.luau +++ b/src/Rosetta/data/ini/init.luau @@ -1,11 +1,7 @@ --!strict --- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code. --- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value, --- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at --- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a --- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level --- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested --- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes. +-- data/ini: INI files read the way Python's configparser does (interpolation off, key case kept), new code. Supports: +-- [sections], key = / key:, ; and # comments, continuation lines, top-level keys, duplicates (last wins), inline +-- comments, keys without values, typed values by option. Not supported: interpolation, DEFAULT inheritance, escapes. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,10 +21,10 @@ local Ini = { } export type DecodeOptions = { - inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser) - allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error) - types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans - strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge) + inlineComments: boolean?, -- default false (configparser) + allowNoValue: boolean?, -- default false + types: boolean?, + strict: boolean?, -- default false } export type EncodeOptions = { delimiter: string?, -- default " = " @@ -92,9 +88,8 @@ function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if trimmed == "" then lastKey = nil elseif string.match(trimmed, "^[;#]") then - -- a comment line (configparser: also when indented); it does not end a continuation + -- configparser: comment lines may be indented and do not end a continuation elseif lastKey and indent > lastIndent then - -- continuation of the previous value local v = trimmed if o.inlineComments then v = string.match(v, "^(.-)%s+[;#]") or v diff --git a/src/Rosetta/data/json/init.luau b/src/Rosetta/data/json/init.luau index 8a07bb2..945d893 100644 --- a/src/Rosetta/data/json/init.luau +++ b/src/Rosetta/data/json/init.luau @@ -1,7 +1,6 @@ --!strict --- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). --- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or --- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. +-- data/json: JSON (RFC 8259) over codecs/text/Json. Supports: decode to Luau values, compact / pretty encode, JSON +-- Lines. Not supported: JSON5 / comments / trailing commas. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -20,10 +19,10 @@ local JsonFormat = { } export type DecodeOptions = Json.DecodeOptions & { - lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value) + lines: boolean?, -- default false } export type EncodeOptions = Json.EncodeOptions & { - lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line + lines: boolean?, } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/data/msgpack/Codec.luau b/src/Rosetta/data/msgpack/Codec.luau index 93fe14c..9ba109d 100644 --- a/src/Rosetta/data/msgpack/Codec.luau +++ b/src/Rosetta/data/msgpack/Codec.luau @@ -1,7 +1,6 @@ --!strict --!native --- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with --- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset. +-- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws. local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -9,7 +8,7 @@ local Codec = {} local TWO32 = 4294967296 --- an extension value: { type = -128..127, data = buffer } +-- ext type: -128..127 local ExtMeta = { __tostring = function(e: any): string return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" end } @@ -20,13 +19,11 @@ function Codec.isExt(v: any): boolean return type(v) == "table" and getmetatable(v) == ExtMeta end --- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact local function u64text(hi: number, lo: number): string if hi == 0 then return string.format("%d", lo) end local digits = {} - -- long division by 10 on four 16-bit limbs local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 } while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do local rem = 0 @@ -42,11 +39,11 @@ end Codec.u64text = u64text export type DecodeOptions = { - bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text - null: any?, -- the value for nil (default Types.null) - maxDepth: number?, -- nesting limit (default 512) - timestamps: boolean?, -- ext -1 as a Types.Date (default true) - ordered: boolean?, -- maps as Types.object with key order (default true) + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + maxDepth: number?, -- default 512 + timestamps: boolean?, -- default true + ordered: boolean?, -- default true } type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean } @@ -55,7 +52,6 @@ local function int64(st: St, signed: boolean): any local r = st.r local hi, lo = r:u32be(), r:u32be() if signed and hi >= 0x80000000 then - -- negative: two's complement local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo if nlo == TWO32 then nlo = 0 @@ -239,7 +235,6 @@ function value(st: St, depth: number): (any, string?) return nil, string.format("reserved type byte 0x%02x", b) end --- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it) function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { @@ -259,11 +254,11 @@ end -- ------------------------------------------------------------------------------------------------ encode export type EncodeOptions = { - float32: boolean?, -- non-integer numbers as float32 (default false: float64) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) - emptyTable: ("array" | "map")?, -- a plain empty table (default "array") + float32: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" maxDepth: number?, -- default 512 (also catches cycles) - stringsAsBin: boolean?, -- strings as bin (default false: str) + stringsAsBin: boolean?, -- default false } type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? } @@ -425,7 +420,6 @@ local function enc(st: ESt, v: any, depth: number): boolean return true end --- encode(v, opts) -> buffer | nil, message function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { diff --git a/src/Rosetta/data/msgpack/init.luau b/src/Rosetta/data/msgpack/init.luau index ac8183c..28b2d02 100644 --- a/src/Rosetta/data/msgpack/init.luau +++ b/src/Rosetta/data/msgpack/init.luau @@ -1,9 +1,7 @@ --!strict --- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the --- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as --- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a --- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for --- non-integers unless opts.float32). Not supported: nothing in the spec. +-- data/msgpack: MessagePack (str8 / bin / ext revision), new code. Supports: every type, timestamps (ext -1) as +-- Types.Date, other ext as Msgpack.ext, exact 64-bit integers by option, concatenated streams; encode picks the +-- smallest forms. Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -21,10 +19,10 @@ local Msgpack = { } export type DecodeOptions = Codec.DecodeOptions & { - all: boolean?, -- decode every concatenated value into an array (default false: exactly one value) + all: boolean?, -- default false } export type EncodeOptions = Codec.EncodeOptions & { - all: boolean?, -- the value is an array of values, written one after another + all: boolean?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -83,7 +81,6 @@ function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v) Msgpack.ext = Codec.ext Msgpack.isExt = Codec.isExt diff --git a/src/Rosetta/data/nbt/init.luau b/src/Rosetta/data/nbt/init.luau index b78d266..e4473d9 100644 --- a/src/Rosetta/data/nbt/init.luau +++ b/src/Rosetta/data/nbt/init.luau @@ -1,10 +1,7 @@ --!strict --- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and --- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and --- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / --- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression --- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. --- Not supported: nothing in the format. +-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT +-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info). +-- Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -54,7 +51,7 @@ function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.info = Nbt.info NbtFormat.Nbt = Nbt return NbtFormat diff --git a/src/Rosetta/data/plist/Binary.luau b/src/Rosetta/data/plist/Binary.luau index 01aec05..02dd5f1 100644 --- a/src/Rosetta/data/plist/Binary.luau +++ b/src/Rosetta/data/plist/Binary.luau @@ -1,10 +1,6 @@ --!strict --!native --- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in --- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte --- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, --- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles --- are errors. Never throws: errors return nil, message. +-- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes. local Types = require("@rosetta/Types") local Binary = {} @@ -44,7 +40,6 @@ end export type Options = { bigInts: ("number" | "string")?, maxDepth: number? } --- decode(buf, base, len, opts) -> value | nil, message function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) if len < 40 then return nil, "truncated: shorter than header + trailer" @@ -130,7 +125,6 @@ function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (a if h >= 0x80000000 and nib == 3 then v = (h - TWO32) * TWO32 + l elseif opts and opts.bigInts == "string" and h >= 0x200000 then - -- exact decimal text of h * 2^32 + l local digits = {} local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 } while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do diff --git a/src/Rosetta/data/plist/init.luau b/src/Rosetta/data/plist/init.luau index 30f68d5..bbe7867 100644 --- a/src/Rosetta/data/plist/init.luau +++ b/src/Rosetta/data/plist/init.luau @@ -1,9 +1,7 @@ --!strict --- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is --- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> --- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> --- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past --- 2^63. Note: Luau has one number type, so a real with an integral value is written back as . +-- data/plist: Apple property lists, new code. Supports: XML read / write (byte-identical to Python's plistlib), +-- binary "bplist00" read, UIDs as Plist.uid. Not supported: binary write, OpenStep text, integers past 2^63; integral +-- reals write back as . -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,11 +23,11 @@ local Plist = { } export type DecodeOptions = { - bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text + bigInts: ("number" | "string")?, maxDepth: number?, -- default 512 } export type EncodeOptions = { - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) + sortKeys: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ sniff @@ -300,7 +298,7 @@ function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.uid = Binary.uid Plist.isUid = Binary.isUid return Plist diff --git a/src/Rosetta/data/snbt/init.luau b/src/Rosetta/data/snbt/init.luau index af13706..1973576 100644 --- a/src/Rosetta/data/snbt/init.luau +++ b/src/Rosetta/data/snbt/init.luau @@ -1,7 +1,5 @@ --!strict --- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over --- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt --- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print. -- Not supported: the 1.21.5 bool(...) / uuid(...) operations. -- ------------------------------------------------------------------------------------------------ requires @@ -22,8 +20,8 @@ local SnbtFormat = { export type DecodeOptions = { maxDepth: number? } export type EncodeOptions = { - indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) - quote: string?, -- '"' (default) or "'" + indent: (number | string)?, -- default: compact + quote: string?, -- default '"' } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/data/toml/Decode.luau b/src/Rosetta/data/toml/Decode.luau index 1ca6e2e..01b06fd 100644 --- a/src/Rosetta/data/toml/Decode.luau +++ b/src/Rosetta/data/toml/Decode.luau @@ -1,8 +1,5 @@ --!strict --- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with --- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control --- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and --- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +-- data/toml/Decode: TOML 1.0.0 parser with the 1.0 validity rules; never throws (nil, message, 0-based offset). local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") @@ -11,7 +8,7 @@ local Decode = {} local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char export type Options = { - bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number") + bigInts: ("number" | "string")?, -- default "number" } local utf8char = Text.utf8char @@ -32,7 +29,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return nil end - -- input checks: BOM, UTF-8, control characters, bare CR if sub(s, 1, 3) == "\239\187\191" then s = sub(s, 4) end @@ -80,7 +76,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) local function ws(i: number): number return match(s, "^[ \t]*()", i) :: any end - -- whitespace, newlines and comments (inside arrays) local function wsnl(i: number): number while true do i = match(s, "^[ \t\n]*()", i) :: any @@ -114,7 +109,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return fail("bad escape", p) end - -- strings: value, next | nil local function basic(i: number): (string?, number) local parts = {} local j = i + 1 @@ -204,7 +198,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return sub(s, j, e - 1) .. string.rep("'", extra), q end - -- a (dotted) key: { parts }, next | nil local function key(i: number): ({ string }?, number) local keys: { string } = {} while true do @@ -242,7 +235,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end end - -- numbers and datetimes local function number(i: number): (any, number) local tok = match(s, "^[%+%-]?[%w_%.]+", i) if not tok then @@ -556,7 +548,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end ni += 1 end - -- walk to the parent local t = root for j = 1, #keys - 1 do local k = keys[j] diff --git a/src/Rosetta/data/toml/Encode.luau b/src/Rosetta/data/toml/Encode.luau index 3652827..679bc28 100644 --- a/src/Rosetta/data/toml/Encode.luau +++ b/src/Rosetta/data/toml/Encode.luau @@ -1,9 +1,5 @@ --!strict --- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables --- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as --- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date --- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, --- message. +-- data/toml/Encode: TOML 1.0.0 writer: plain values, then [a.b] sections and [[a.b]] arrays of tables; never throws. local Types = require("@rosetta/Types") local Json = require("@rosetta/codecs/text/Json") @@ -12,8 +8,8 @@ local Encode = {} local format, gsub, find = string.format, string.gsub, string.find export type Options = { - inline: boolean?, -- write every sub-table as an inline table (default false: [sections]) - indent: (number | string)?, -- indent keys of nested sections (default none) + inline: boolean?, -- default false + indent: (number | string)?, -- default none } local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" } @@ -36,7 +32,6 @@ local function keyText(k: string): string return quote(k) end --- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays local function isMap(t: { [any]: any }): boolean if Types.isObject(t) then return true @@ -56,7 +51,6 @@ local function isDate(v: any): boolean return Types.Date.is(v) end --- an array of tables: non-empty, every element a map local function isAot(v: any): boolean if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then return false @@ -196,7 +190,6 @@ local function section(st: State, t: any, path: string, out: { string }, inlineA return true end --- encode(t, opts) -> text | nil, message function Encode.encode(t: any, opts: Options?): (string?, string?) if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then return nil, "the top level must be a table with string keys" diff --git a/src/Rosetta/data/toml/init.luau b/src/Rosetta/data/toml/init.luau index 9977ad1..0b1db54 100644 --- a/src/Rosetta/data/toml/init.luau +++ b/src/Rosetta/data/toml/init.luau @@ -1,11 +1,7 @@ --!strict --- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables, --- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range --- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules --- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables / --- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to --- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral --- values are written as integers). +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0), new code, tested against toml-test. Supports: the whole 1.0 +-- grammar and validity rules; tables as Types.object, datetimes as Types.Date. Not supported: TOML 1.1; the integer / +-- float distinction (integral values write as integers). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,8 +23,7 @@ export type DecodeOptions = Decode.Options export type EncodeOptions = Encode.Options -- ------------------------------------------------------------------------------------------------ sniff --- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same, --- so this stays low and the extension decides +-- INI looks the same: a [table] or key = value start scores low and the extension decides function Toml.sniff(r: Bytes.Reader): number local head = r:peek(512) if string.find(head, "%z") then diff --git a/src/Rosetta/data/xml/init.luau b/src/Rosetta/data/xml/init.luau index b493ce1..d3f8004 100644 --- a/src/Rosetta/data/xml/init.luau +++ b/src/Rosetta/data/xml/init.luau @@ -1,7 +1,6 @@ --!strict --- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: --- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not --- supported: external entities / DTDs, validation. +-- data/xml: XML 1.0 over codecs/text/Xml. Supports: decode to a "#document" XmlNode tree, encode a document or an +-- element. Not supported: external entities / DTDs, validation. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") diff --git a/src/Rosetta/data/yaml/Emit.luau b/src/Rosetta/data/yaml/Emit.luau index c46d2fd..b01a1c4 100644 --- a/src/Rosetta/data/yaml/Emit.luau +++ b/src/Rosetta/data/yaml/Emit.luau @@ -1,9 +1,5 @@ --!strict --- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when --- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars --- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as --- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad --- values (cycles, functions, collection keys) return nil, message. +-- data/yaml/Emit: YAML block-style writer; plain scalars only when they read back the same (core schema, no 1.1 bools). local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") local Parse = require("@rosetta/data/yaml/Parse") @@ -11,11 +7,11 @@ local Parse = require("@rosetta/data/yaml/Parse") local Emit = {} export type Options = { - indent: number?, -- spaces per level (default 2) - all: boolean?, -- the value is an array of documents, written with "---" separators - explicitStart: boolean?, -- start the (first) document with "---" (default false) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order) - null: any?, -- the value written as null besides Types.null + indent: number?, -- default 2 + all: boolean?, + explicitStart: boolean?, -- default false + sortKeys: boolean?, -- default true + null: any?, } local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub @@ -96,7 +92,6 @@ local function plainOk(s: string): boolean return true end --- a string as a scalar on a line at indentation ind (for block scalars) local function str(s: string, ind: string, key: boolean): string if plainOk(s) then return s @@ -126,7 +121,6 @@ local keyLess = Types.keyLess type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? } --- count references to tables (anchors for those seen twice); false on a cycle local function count(st: St, v: any, onStack: { [any]: boolean }): boolean if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then return true @@ -150,7 +144,6 @@ local function count(st: St, v: any, onStack: { [any]: boolean }): boolean return true end --- scalar text for a non-collection value, or nil local function scalar(st: St, v: any, ind: string, key: boolean): string? local tv = type(v) if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then @@ -171,7 +164,6 @@ end local write: (st: St, v: any, depth: number) -> string? --- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline) function write(st: St, v: any, depth: number): string? local ind = string.rep(" ", st.step * (depth + 1)) local s = scalar(st, v, ind, false) @@ -244,19 +236,16 @@ local function document(st: St, v: any): string? if not t then return nil end - -- the top level: drop the separator write() put before the first line if string.sub(t, 1, 1) == "\n" then return string.sub(t, 2) end local body = string.sub(t, 2) if string.sub(body, 1, 1) == "&" then - -- "&id001\n- a": an anchored top-level collection return body end return body end --- encode(v, opts) -> text | nil, message function Emit.encode(v: any, opts: Options?): (string?, string?) local o: Options = opts or {} local st: St = { diff --git a/src/Rosetta/data/yaml/Parse.luau b/src/Rosetta/data/yaml/Parse.luau index 425d08e..fdcf2e5 100644 --- a/src/Rosetta/data/yaml/Parse.luau +++ b/src/Rosetta/data/yaml/Parse.luau @@ -1,11 +1,5 @@ --!strict --- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized): --- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with --- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared --- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless --- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core --- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a --- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +-- data/yaml/Parse: YAML 1.2 recursive-descent parser; raises { yamlErr } tables caught by run(), never throws past it. local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") @@ -15,11 +9,11 @@ local Parse = {} local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char export type Options = { - all: boolean?, -- every document as an array (default false: the first document; none -> Types.null) - tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged - maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard - maxDepth: number?, -- nesting limit (default 500) - null: any?, -- the value for null (default Types.null) + all: boolean?, -- default false + tags: ("error" | "ignore")?, -- default "error" + maxAliasNodes: number?, -- default 1e6 (billion laughs guard) + maxDepth: number?, -- default 500 + null: any?, -- default Types.null } type St = { @@ -54,7 +48,7 @@ local function col(s: string, p: number): number return p - q end -local function isWsEnd(c: number?): boolean -- space, tab, newline or the end +local function isWsEnd(c: number?): boolean return c == nil or c == 32 or c == 9 or c == 10 end @@ -66,7 +60,6 @@ local function docMarker(s: string, p: number): boolean return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) end --- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end) local function skip(s: string, p: number): number local n = #s while p <= n do @@ -86,7 +79,6 @@ local function skip(s: string, p: number): number return p end --- the number of leading spaces on p's line, and whether a tab comes before p on it local function lineIndent(s: string, p: number): (number, boolean) local q = p while q > 1 and byte(s, q - 1) ~= 10 do @@ -105,7 +97,6 @@ local function noTabs(s: string, p: number, ind: number?) end end --- skip spaces / tabs on the line local function skipLine(s: string, p: number): number return match(s, "^[ \t]*()", p) :: any end @@ -120,7 +111,6 @@ end local utf8char = Text.utf8char -- ------------------------------------------------------------------------------------------------ resolution --- the core schema: a plain scalar's value function Parse.resolve(t: string, nullv: any): any if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then return nullv @@ -168,7 +158,6 @@ local function base64(t: string): buffer? return (Base64.decode(t)) end --- a scalar's value given its tag (nil = untagged, "!" = non-specific) local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any if tag == nil then return if plain then Parse.resolve(raw, st.null) else raw @@ -237,7 +226,6 @@ local function collectionTag(st: St, tag: string?, kind: string, p: number) end end --- expansion size of a value (nodes), memoized local function size(st: St, v: any): number if type(v) ~= "table" or v == st.null then return 1 @@ -257,7 +245,6 @@ end -- ------------------------------------------------------------------------------------------------ properties type Props = { anchor: string?, tag: string?, at: number } --- anchors / tags at p -> props?, the position after them (and the spaces after them) local function properties(st: St, p: number): (Props?, number) local s = st.s local props: Props? = nil @@ -348,8 +335,7 @@ local function alias(st: St, p: number): (any, number) end -- ------------------------------------------------------------------------------------------------ scalars --- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content. --- Lines holding only spaces / tabs count as empty. +-- line folding: lines holding only spaces / tabs count as empty local function fold(s: string, p: number): (string, number) local empties = 0 local q = p + 1 @@ -385,7 +371,6 @@ local ESC: { [number]: string } = { [80] = "\226\128\169", } --- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote local function quoted(st: St, p: number, ind: number): (string, number) local s = st.s local dq = byte(s, p) == 34 @@ -456,15 +441,13 @@ local function quoted(st: St, p: number, ind: number): (string, number) end end --- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind --- (block context); flow: the flow-context rules (stops at , [ ] { }). +-- plain scalar: continuation lines indented deeper than ind (block context); flow context stops at , [ ] { } local function plain(st: St, p: number, ind: number, flow: boolean): (string, number) local s = st.s local parts: { string } = {} local i = p local lastEnd = p while true do - -- one line's worth local j = i local stopAt = nil while true do @@ -492,7 +475,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu if stopAt or byte(s, j) == nil then return table.concat(parts), lastEnd end - -- a continuation line? local f, q = fold(s, j) local r = skipLine(s, q) local c = byte(s, r) @@ -507,7 +489,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu end end --- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it local function blockScalar(st: St, p: number, ind: number): (string, number) local s = st.s local folded = byte(s, p) == 62 @@ -529,7 +510,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) end local nl = find(s, "\n", q, true) local lines: { string } = {} - local trailing = 0 -- empty lines after the last content line + local trailing = 0 if not nl then return "", #s + 1 end @@ -568,7 +549,6 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) indent = ind + 1 end end - -- the lines local r = ls local pendingEmpty = 0 local endPos = ls @@ -625,7 +605,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) empties = 0 end end - trailing += empties -- empty lines after the last content line (or all of them) + trailing += empties body = table.concat(out) end if not folded then @@ -666,7 +646,6 @@ local function enter(st: St, p: number) end end --- a flow node at p (after skip) -> value, next, wasEmpty local function flowNode(st: St, p: number, ind: number): (any, number, boolean) local s = st.s local props, q = properties(st, p) @@ -688,7 +667,6 @@ local function flowNode(st: St, p: number, ind: number): (any, number, boolean) local t, r = quoted(st, q, ind) return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then - -- an empty node return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then corrupt("unexpected character in a flow collection", q) @@ -819,7 +797,7 @@ end -- ------------------------------------------------------------------------------------------------ block local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number) --- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':' +-- implicit key: on one line, followed by ':' and a space or the end of the line local function implicitKey(st: St, p: number): (any, number?) local s = st.s local c = byte(s, p) @@ -847,7 +825,6 @@ local function implicitKey(st: St, p: number): (any, number?) end return nil, nil elseif c == 91 or c == 123 then - -- a flow collection used as a key? local e = find(s, "\n", p, true) or #s + 1 local line = sub(s, p, e - 1) if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then @@ -892,7 +869,7 @@ local function readKey(st: St, p: number, props: Props?): (any, number) end k, q = alias(st, p) q = skipLine(s, q) - q += 1 -- the ':' + q += 1 elseif c == 34 or c == 39 then local t, r = quoted(st, p, -1) if find(sub(s, p, r - 1), "\n", 1, true) then @@ -912,7 +889,6 @@ local function readKey(st: St, p: number, props: Props?): (any, number) return checkKey(st, k, p), q end --- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number) local s = st.s local r = skip(s, p) @@ -926,7 +902,6 @@ local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapP return st.null, p end --- the value after a ':' (at p, just past it) of a mapping at column mc local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number) local s = st.s local r = skipLine(s, p) @@ -1044,7 +1019,6 @@ local function blockSeq(st: St, sc: number, p: number): (any, number) return t, q end --- the node at q after its properties (props may be nil); start = where the properties began local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number) local s = st.s local tag = props and props.tag @@ -1111,9 +1085,6 @@ local function afterProps(st: St, ind: number, start: number, q: number, props: return finish(st, props, scalarValue(st, text, true, tag, q)), e end --- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the --- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's --- indentation may follow properties that end their line. function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number) local s = st.s local props, q = properties(st, p) @@ -1253,7 +1224,6 @@ local function stream(st: St): { any } p = q else if explicit and not find(sub(s, p, q), "\n", 1, true) then - -- content on the "---" line local ok, _, q2 = pcall(properties, st, q) local c = byte(s, q2) if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then @@ -1282,7 +1252,6 @@ local function stream(st: St): { any } return docs end --- run(text, opts) -> docs | nil, code, message, offset function Parse.run(text: string, opts: Options?): (any, any, any, any) local o: Options = opts or {} local s = text diff --git a/src/Rosetta/data/yaml/init.luau b/src/Rosetta/data/yaml/init.luau index 7c6c355..53ac771 100644 --- a/src/Rosetta/data/yaml/init.luau +++ b/src/Rosetta/data/yaml/init.luau @@ -1,11 +1,7 @@ --!strict --- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain / --- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as --- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null --- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams. --- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables). --- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore"; --- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings. +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block / flow styles, every scalar style, anchors and aliases +-- (shared, alias-bomb limit), core tags + !!binary / !!timestamp, %TAG, multi-document streams; writes block style. +-- Not supported (Err.UNSUPPORTED): complex keys, collections as keys; merge keys stay keys; YAML 1.1 types are strings. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -47,7 +43,6 @@ function Yaml.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local text = buffer.readstring(r.buf, r.base, r.limit - r.base) local docs, code, msg, at = Parse.run(text, opts) @@ -65,7 +60,6 @@ function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents) function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local s, err = Emit.encode(value, opts) if not s then diff --git a/src/Rosetta/font/bdf/init.luau b/src/Rosetta/font/bdf/init.luau index b63322e..8c0a38f 100644 --- a/src/Rosetta/font/bdf/init.luau +++ b/src/Rosetta/font/bdf/init.luau @@ -1,13 +1,7 @@ --!strict --- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the --- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in --- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used), --- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to --- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for --- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and --- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font --- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification. --- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored). +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1 +-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes +-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,9 +21,9 @@ local Bdf = { export type DecodeOptions = { maxGlyphs: number? } -- default 1114112 export type EncodeOptions = { - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) - name: string?, -- the FONT (XLFD) name (default built from the font's family / style) + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + name: string?, -- XLFD; default built from the family / style } -- ------------------------------------------------------------------------------------------------ sniff @@ -223,7 +217,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil local px = strike.size - -- the font bounding box local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge for _, g in strike.glyphs do if g.width > 0 and g.height > 0 then @@ -244,7 +237,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) string.format("SIZE %d 75 75", px), string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), } - -- the default glyph: the strike's default, else glyph 0 local defaultIndex = (strike.default or 0) + 1 local props: { { any } } = { { "FAMILY_NAME", quote(family) }, diff --git a/src/Rosetta/font/bmfont/Parse.luau b/src/Rosetta/font/bmfont/Parse.luau index d4a0076..2b8d8e4 100644 --- a/src/Rosetta/font/bmfont/Parse.luau +++ b/src/Rosetta/font/bmfont/Parse.luau @@ -1,10 +1,5 @@ --!strict --- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one --- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation --- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the --- descriptor has no nesting that matters, no text content). --- --- Never throws on bad input: parse functions return nil, message. +-- font/bmfont/Parse: BMFont text / XML / binary v3 descriptors (angelcode.com/products/bmfont/doc/file_format.html). local Bytes = require("@rosetta/core/Bytes") local Parse = {} @@ -24,12 +19,12 @@ export type Char = { export type Desc = { info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl - pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1]) + pages: { string }, -- by page id: page id 0 is pages[1] chars: { Char }, kernings: { { number } }, -- { first, second, amount } } -local LIMIT = 1000000 -- chars / kernings +local LIMIT = 1000000 local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } @@ -54,7 +49,6 @@ local function new(): Desc return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } end --- one tag's attributes (already split into key -> string) into the description local function apply(d: Desc, tag: string, a: { [string]: string }): string? if tag == "info" then d.info.face = a.face or "" diff --git a/src/Rosetta/font/bmfont/init.luau b/src/Rosetta/font/bmfont/init.luau index 617c9fa..2049d5e 100644 --- a/src/Rosetta/font/bmfont/init.luau +++ b/src/Rosetta/font/bmfont/init.luau @@ -1,11 +1,7 @@ --!strict --- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and --- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize --- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are --- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the --- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / --- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. --- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). +-- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont +-- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages. +-- Not supported: packed multi-channel glyphs (read as alpha). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,25 +20,24 @@ local Bmfont = { } export type DecodeOptions = { - pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first) - loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one) + pages: { Types.Image }?, -- page id 0 first + loadPage: ((file: string, page: number) -> any)?, } export type EncodeOptions = { variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" - px: number?, -- fonts without a BMFont description are baked first (see bake) + px: number?, chars: (string | { number })?, - file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font") - name: string?, -- the destination's file name (set by the api) - files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes - -- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages + file: string?, -- default: opts.name without its extension, else "font" + name: string?, + files: { [string]: any }?, encodeImage: ((img: any, format: string) -> (buffer?, any))?, } export type BakeOptions = { - px: number?, -- pixels per em (default 32) - chars: (string | { number })?, -- code points to include (default printable ASCII 32..126) - pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096) - padding: number?, -- empty pixels around each glyph (default 1) - file: string?, -- page file name prefix (default "font"): pages are _.png + px: number?, -- default 32 + chars: (string | { number })?, -- default printable ASCII 32..126 + pageSize: number?, -- default: the smallest power of two that fits, up to 4096 + padding: number?, -- default 1 + file: string?, -- default "font"; pages are _.png } -- ------------------------------------------------------------------------------------------------ sniff @@ -61,7 +56,6 @@ function Bmfont.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the Font value local Face = {} Face.__index = Face @@ -80,10 +74,9 @@ function Face.kern(self: any, a: number, b: number): number return self._kern[ca.id * 2097152 + cb.id] or 0 end function Face.outline(_self: any, _g: number): { any }? - return nil -- bitmap font + return nil end --- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) local load = loader or self.meta.pageLoader if type(load) ~= "function" then @@ -103,8 +96,6 @@ end local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 --- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; --- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. function Face.rasterize(self: any, g: number, px: number?): Types.Image? local c = self._chars[g] if not c then @@ -141,7 +132,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image? return img end --- the Font value of a description local function face(d: Parse.Desc, variant: string): any local f: any = setmetatable({ kind = "font", @@ -244,7 +234,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) local d = type(font.meta) == "table" and font.meta.bmfont or nil local pages = font.pages if d == nil then - -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" local file = opts and opts.file if file == nil and opts and type(opts.name) == "string" then file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") @@ -262,7 +251,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not validDesc(d) then return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") end - -- the page images into opts.files, under the names the descriptor gives them local files = opts and opts.files local encodeImage = opts and opts.encodeImage if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then @@ -310,9 +298,6 @@ local function codepoints(chars: any): { number } return out end --- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are --- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are --- kept (rounded to pixels). function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?) if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then return nil, Err.new(Err.ARG, "bake: expected an outline Font") diff --git a/src/Rosetta/font/eot/init.luau b/src/Rosetta/font/eot/init.luau index e3e9bc4..83ecdc1 100644 --- a/src/Rosetta/font/eot/init.luau +++ b/src/Rosetta/font/eot/init.luau @@ -1,10 +1,7 @@ --!strict --- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset, --- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and --- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot --- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string, --- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C --- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures. +-- font/eot: Embedded OpenType (versions 0x00010000, 0x00020001, 0x00020002; W3C EOT submission, 2008): the header +-- and the font data (XOR-0x50 obfuscated or not) through codecs/font/TrueType; writes EOT 2.1 around TrueType bytes. +-- Not supported: MicroType Express compression (flag 0x4: Err.UNSUPPORTED), signatures. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,8 +21,8 @@ local Eot = { export type DecodeOptions = {} export type EncodeOptions = { - xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false) - rootString: string?, -- the URLs allowed to use the font (default "") + xor: boolean?, -- XOR 0x50; default false + rootString: string?, -- default "" } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/font/fon/init.luau b/src/Rosetta/font/fon/init.luau index b4bef4d..ab869d1 100644 --- a/src/Rosetta/font/fon/init.luau +++ b/src/Rosetta/font/fon/init.luau @@ -1,10 +1,6 @@ --!strict --- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the --- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE --- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first --- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI --- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset). --- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts. +-- font/fon: Windows raster fonts: .fnt resources (versions 2.0 / 3.0) and .fon NE / PE executables holding them as +-- RT_FONT, from Microsoft's KB65123 and the NE / PE resource layouts; ANSI charset maps through Windows-1252. -- Not supported: vector FNT (Err.UNSUPPORTED), writing. -- ------------------------------------------------------------------------------------------------ requires @@ -24,7 +20,7 @@ local Fon = { caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, } -export type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first) +export type DecodeOptions = { size: number? } -- default: the first strike -- ------------------------------------------------------------------------------------------------ sniff local function isFnt(h: string): boolean @@ -50,7 +46,6 @@ function Fon.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- one FNT resource -> Font local function fnt(r: Bytes.Reader): (any, Err.Err?) local version = r:u16le() local total = r:u32le() @@ -145,7 +140,6 @@ local function fnt(r: Bytes.Reader): (any, Err.Err?) }), nil end --- the RT_FONT resources of an NE executable: { { offset, length } } local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) local rt = r:sub(ne + 0x24, 2):u16le() local t = r:sub(ne + rt) @@ -175,7 +169,7 @@ local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) return out, nil end --- the RT_FONT (8) resources of a PE executable: { { offset, length } } +-- RT_FONT: resource type 8 local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) local h = r:sub(pe + 4, 20) h:skip(2) @@ -190,7 +184,6 @@ local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) if opt.err or rsrcRva == 0 then return {}, nil end - -- the section holding the resources local secs = r:sub(pe + 24 + optSize, nsec * 40) local base, rva0 = -1, 0 for _ = 1, nsec do diff --git a/src/Rosetta/font/hershey/init.luau b/src/Rosetta/font/hershey/init.luau index 3ca26d9..275a81f 100644 --- a/src/Rosetta/font/hershey/init.luau +++ b/src/Rosetta/font/hershey/init.luau @@ -1,13 +1,7 @@ --!strict --- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph --- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R", --- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths --- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster --- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of --- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i --- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph --- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported: --- writing, the Hershey "occidental" index files (.hmp), filled rendering. +-- font/hershey: Hershey vector fonts, JHF layout (5-column id, 3-column vertex count, extents, vertices as character +-- pairs offset by "R", " R" lifts the pen; records continue over 72-column lines). Units: unitsPerEm 32, y up. +-- Not supported: writing, .hmp index files, filled rendering. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,8 +20,8 @@ local Hershey = { } export type DecodeOptions = { - map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii") - strokeWidth: number?, -- stroke width in font units for rasterize (default 2) + map: ("ascii" | "id")?, -- default "ascii" + strokeWidth: number?, -- font units; default 2 maxGlyphs: number?, -- default 65536 } @@ -93,7 +87,6 @@ function Face.outline(self: any, g: number): { any }? return out end --- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels) function Face.rasterize(self: any, g: number, px: number): Types.Image? local gl = self._glyphs[g + 1] if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then diff --git a/src/Rosetta/font/pcf/init.luau b/src/Rosetta/font/pcf/init.luau index f34e7c1..c309ea3 100644 --- a/src/Rosetta/font/pcf/init.luau +++ b/src/Rosetta/font/pcf/init.luau @@ -1,11 +1,6 @@ --!strict --- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the --- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties), --- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad --- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES. --- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets --- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver --- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS. +-- font/pcf: X11 Portable Compiled Format bitmap fonts, from the PCF description in libXfont / FreeType's pcf driver +-- docs (no code copied); code points as font/bdf. Not supported: writing, INK_METRICS. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -38,7 +33,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Table = { format: number, size: number, offset: number } --- a reader positioned after a table's format word, with the integer readers for its byte order type TR = { r: Bytes.Reader, format: number, big: boolean } local function open(r: Bytes.Reader, t: Table?): TR? @@ -91,7 +85,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- properties local props: { [string]: any } = {} local pt = open(r, tables[PROPERTIES]) if pt then @@ -122,14 +115,12 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) return nil, Err.new(Err.TRUNCATED, "properties table") end end - -- accelerators: ascent / descent local ascent: number?, descent: number? = nil, nil local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) if at then at.r:skip(8) ascent, descent = i32(at), i32(at) end - -- metrics local mt = open(r, tables[METRICS]) if not mt then return nil, Err.new(Err.CORRUPT, "no METRICS table") @@ -152,7 +143,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if mt.r.err then return nil, Err.new(Err.TRUNCATED, "metrics table") end - -- bitmaps local bt = open(r, tables[BITMAPS]) if not bt then return nil, Err.new(Err.CORRUPT, "no BITMAPS table") @@ -202,7 +192,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local px = Bitmap.unpack(bits, offsets[k], w, h, stride) glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } end - -- encodings local encodings: { [number]: number } = {} local default: number? = nil local et = open(r, tables[BDF_ENCODINGS]) @@ -233,7 +222,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- glyph names local nt = open(r, tables[GLYPH_NAMES]) if nt then local n = u32(nt) diff --git a/src/Rosetta/font/psf/init.luau b/src/Rosetta/font/psf/init.luau index 0fcd14f..1b71bd2 100644 --- a/src/Rosetta/font/psf/init.luau +++ b/src/Rosetta/font/psf/init.luau @@ -1,14 +1,7 @@ --!strict --- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2 --- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and --- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry --- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map --- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell --- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing: --- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through --- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps --- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd --- project's psf documentation (Andries Brouwer). +-- font/psf: Linux console fonts (kbd project's psf docs, Andries Brouwer): PSF 1 (magic 36 04, UCS-2 table, FFFF / +-- FFFE) and PSF 2 (magic 72 B5 4A 86, UTF-8 table, FF / FE), read and written (PSF 2 by default); the ascent is the +-- cell height. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,10 +21,10 @@ local Psf = { export type DecodeOptions = { maxGlyphs: number? } -- default 65536 export type EncodeOptions = { - version: number?, -- 1 or 2 (default 2) - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) - unicode: boolean?, -- write the Unicode table (default true) + version: number?, -- 1 or 2; default 2 + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + unicode: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ sniff @@ -103,7 +96,7 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end local map: { [number]: number } = {} local sequences = {} - local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order + local unicodeTable: { { any } } = {} if hasTable then local t = r:sub(glyphAt + count * size) for i = 0, count - 1 do @@ -141,7 +134,6 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) inSeq = true continue end - -- UTF-8 local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1 if n < 0 then return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table") @@ -208,7 +200,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) if n == 0 then return nil, Err.new(Err.ARG, "no glyphs") end - -- the cell local width = 0 for _, g in glyphs do width = math.max(width, g.advance, g.left + g.width) @@ -241,7 +232,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) end buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride)) end - -- the Unicode table: each glyph's code point and the extra mappings onto it local cps: { { number } } = {} for i = 1, count do cps[i] = {} diff --git a/src/Rosetta/font/ttf/init.luau b/src/Rosetta/font/ttf/init.luau index c65b2bd..b671265 100644 --- a/src/Rosetta/font/ttf/init.luau +++ b/src/Rosetta/font/ttf/init.luau @@ -1,9 +1,7 @@ --!strict --- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the --- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, --- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / --- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. --- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. +-- font/ttf: TrueType / OpenType (glyf or CFF) fonts and collections via codecs/font/TrueType, ported from stb_truetype +-- 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua. Not supported: hinting, variable fonts, bitmap / +-- colour glyphs, GSUB, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -21,7 +19,7 @@ local Ttf = { } export type DecodeOptions = { - index: number?, -- the font of a collection (default 0) + index: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ sniff @@ -44,7 +42,6 @@ function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- count(r) -> the number of fonts in the file (1 unless a collection) function Ttf.count(r: Bytes.Reader): number return TrueType.count(r.buf, r.base) end diff --git a/src/Rosetta/font/type1/Charstring.luau b/src/Rosetta/font/type1/Charstring.luau index e1b4f4a..036542b 100644 --- a/src/Rosetta/font/type1/Charstring.luau +++ b/src/Rosetta/font/type1/Charstring.luau @@ -1,15 +1,8 @@ --!strict --- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted --- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side --- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div, --- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement; --- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes, --- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the --- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops). +-- font/type1/Charstring: Type 1 charstring interpreter (Adobe Type 1 Font Format, chapters 6 and 8); hints ignored. local Charstring = {} export type Result = { cmds: { any }, advance: number, sbx: number } --- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? } local readu8 = buffer.readu8 @@ -18,7 +11,7 @@ function Charstring.run(cs: buffer, ctx: Context): (Result?, string?) local cmds: { any } = {} local stack: { number } = {} local sp = 0 - local ps: { number } = {} -- the PostScript stack callothersubr / pop use + local ps: { number } = {} local x, y = 0, 0 local advance, sbx = 0, 0 local open = false diff --git a/src/Rosetta/font/type1/init.luau b/src/Rosetta/font/type1/init.luau index bbca329..1024e34 100644 --- a/src/Rosetta/font/type1/init.luau +++ b/src/Rosetta/font/type1/init.luau @@ -1,12 +1,7 @@ --!strict --- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the --- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox, --- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV, --- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring --- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph --- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through --- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple --- Master and CID-keyed (Type 9 / 11) fonts, writing. +-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA, from Adobe's "Adobe Type 1 Font +-- Format" (1990): eexec (r = 55665) and charstring (r = 4330) decryption, code points via codecs/font/GlyphNames. +-- Not supported: hinting, Multiple Master and CID-keyed (Type 9 / 11) fonts, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,7 +36,6 @@ function Type1.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA local function sections(r: Bytes.Reader): (string?, buffer?, string?) local b = r.buf local n = r:size() @@ -204,7 +198,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4) local ptext = buffer.tostring(priv) local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4 - -- Subrs local subrs: { buffer } = {} local function charstring(p: number, len: number): buffer? local raw = binaryAt(priv, p, len) @@ -241,7 +234,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) p = e + n end end - -- CharStrings local names: { string } = {} local charstrings: { buffer } = {} local byName: { [string]: number } = {} @@ -252,7 +244,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) break end local e = e0 :: number - -- stop at the end of the dictionary if string.find(string.sub(ptext, p, s), "%send%s") then break end @@ -281,7 +272,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1] byName[names[1]], byName[names[nd + 1]] = 0, nd end - -- the encoding local encoding: { [number]: string } = {} if string.find(clear, "/Encoding%s+StandardEncoding") then for code, gname in GlyphNames.STANDARD do @@ -306,7 +296,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) cmap[cp] = k - 1 end end - -- font matrix / bbox local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]") local scale = 0.001 if fm then diff --git a/src/Rosetta/font/woff/init.luau b/src/Rosetta/font/woff/init.luau index c992b4c..d33dfce 100644 --- a/src/Rosetta/font/woff/init.luau +++ b/src/Rosetta/font/woff/init.luau @@ -1,7 +1,6 @@ --!strict --- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding --- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended --- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): zlib-compressed sfnt tables, rebuilt and read through +-- codecs/font/TrueType; the metadata XML goes to meta.woffMetadata. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -20,7 +19,7 @@ local Woff = { } export type DecodeOptions = { - maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -29,7 +28,6 @@ function Woff.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local base = r.base diff --git a/src/Rosetta/font/woff2/Rebuild.luau b/src/Rosetta/font/woff2/Rebuild.luau index b156e55..5d2199f 100644 --- a/src/Rosetta/font/woff2/Rebuild.luau +++ b/src/Rosetta/font/woff2/Rebuild.luau @@ -1,10 +1,5 @@ --!strict --- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table --- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph, --- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx --- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor). --- --- Never throws: malformed data returns nil, message. +-- font/woff2/Rebuild: the sfnt of a WOFF2 file (W3C WOFF2, 2024 edition: section 5 glyf / loca, section 6 hmtx). local Bytes = require("@rosetta/core/Bytes") local Brotli = require("@rosetta/codecs/compress/Brotli") @@ -40,7 +35,6 @@ local function base128(r: Bytes.Reader): number? return nil end --- a cursor over a stream inside the decompressed block type Stream = { buf: buffer, p: number, e: number, bad: boolean } local function stream(b: buffer, p: number, n: number): Stream return { buf = b, p = p, e = p + n, bad = false } @@ -77,7 +71,6 @@ local function withSign(flag: number, v: number): number return if band(flag, 1) ~= 0 then v else -v end --- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?) local h = stream(b, p, n) su16(h) -- reserved @@ -132,7 +125,6 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s return nil, "empty glyph with a bounding box" end elseif nc > 0 then - -- simple glyph local ends = table.create(nc, 0) local total = 0 for c = 1, nc do @@ -363,7 +355,6 @@ local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: nu return out:finish(), nil end --- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit") function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?) if not r:match("wOF2") then return nil, "bad signature", "corrupt" @@ -433,7 +424,6 @@ function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, str if buffer.len(data) < streamTotal then return nil, "decompressed stream shorter than the tables", "corrupt" end - -- the tables, glyf / loca / hmtx rebuilt local byTag: { [string]: any } = {} for _, e in dir do byTag[e.tag] = e diff --git a/src/Rosetta/font/woff2/init.luau b/src/Rosetta/font/woff2/init.luau index b696609..c7d2018 100644 --- a/src/Rosetta/font/woff2/init.luau +++ b/src/Rosetta/font/woff2/init.luau @@ -1,7 +1,6 @@ --!strict --- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx --- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF --- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. +-- font/woff2: WOFF 2.0 (W3C Recommendation): Brotli-compressed sfnt tables with the glyf / loca and hmtx transforms, +-- rebuilt by font/woff2/Rebuild. Not supported: collections, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -20,7 +19,7 @@ local Woff2 = { } export type DecodeOptions = { - maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -30,7 +29,6 @@ function Woff2.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local at = r.base diff --git a/src/Rosetta/image/ani/init.luau b/src/Rosetta/image/ani/init.luau index 208a015..580430b 100644 --- a/src/Rosetta/image/ani/init.luau +++ b/src/Rosetta/image/ani/init.luau @@ -1,11 +1,7 @@ --!strict --- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks; --- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one, --- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files) --- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames --- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors --- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a --- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED). +-- image/ani: Windows animated cursor (RIFF "ACON": anih header, rate / seq chunks, LIST fram of ICO / CUR chunks). +-- Supports: the steps as img.frames (seq order; rate or iDispRate in 1/60 s jiffies), CUR hotspots, INFO title / +-- author; icons through opts.decodeImage / opts.encodeImage. Not supported: raw frame bitmaps (AF_ICON clear). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,11 +21,11 @@ local Ani = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one) - maxFrames: number?, -- refuse more steps (default 10000) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxFrames: number?, -- default 10000 } export type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -67,7 +63,6 @@ function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if not decodeImage then return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook") end - -- the icon chunks local icons: { Types.Image } = {} for _, c in f.chunks do if c.id == "LIST" and Riff.listType(f, c) == "fram" then @@ -98,7 +93,7 @@ function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local im = icons[idx + 1] if not im then if s >= #icons and not seq then - break -- fewer icons than steps: keep what is there + break end return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx) end diff --git a/src/Rosetta/image/blp/init.luau b/src/Rosetta/image/blp/init.luau index b693cea..344a7b2 100644 --- a/src/Rosetta/image/blp/init.luau +++ b/src/Rosetta/image/blp/init.luau @@ -1,14 +1,7 @@ --!strict --- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written --- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken. --- Decode, mip 0 (meta.source.mips counts the levels) to rgba8: --- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual --- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back); --- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque); --- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha --- type 0 / 1 / 7), uncompressed BGRA. --- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain). --- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games). +-- image/blp: Blizzard BLP textures (BLP1 Warcraft III, BLP2 World of Warcraft), from the wowdev.wiki BLP page. +-- Supports: mip 0 of BLP1 JPEG (4 components: BGRA, no colour conversion) / palette and BLP2 palette (1 / 4 / 8-bit +-- alpha, LSB first) / DXT1 / DXT3 / DXT5 / BGRA; writes BLP2 BGRA + mips. Not supported: BLP0 (.b00 mips), BLP2 JPEG. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,7 +22,7 @@ local Blp = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { maxPixels: number? } -- default 2^26 -export type EncodeOptions = { mips: boolean? } -- write the mip chain (default false) +export type EncodeOptions = { mips: boolean? } -- default false -- ------------------------------------------------------------------------------------------------ constants local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 @@ -41,13 +34,11 @@ function Blp.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha local function swap(v: number, a: number): number local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256 return r + g * 256 + b * 65536 + a * 16777216 end --- alpha of pixel i from a packed plane at p of depth bits local function alphaAt(b: buffer, p: number, depth: number, i: number): number if depth == 8 then return readu8(b, p + i) @@ -190,7 +181,6 @@ function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat) local function halve(px: buffer, w: number, h: number): (buffer, number, number) local nw, nh = math.max(1, w // 2), math.max(1, h // 2) local out = buffer.create(nw * nh * 4) diff --git a/src/Rosetta/image/bmp/init.luau b/src/Rosetta/image/bmp/init.luau index efbd897..2bb0765 100644 --- a/src/Rosetta/image/bmp/init.luau +++ b/src/Rosetta/image/bmp/init.luau @@ -1,16 +1,8 @@ --!strict --!optimize 2 --- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a --- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3 --- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or --- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap), --- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the --- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit --- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max). --- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance --- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with --- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output. --- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp. +-- image/bmp: Windows / OS/2 BMP; absorbed from bmp-luau b86aed6 (same author), new encoder. Supports: headers 12 / +-- 16..64 / 40 / 52 / 56 / 108 / 124, 1..32 bpp, BITFIELDS / ALPHABITFIELDS, RLE8 / RLE4, both row orders, Pillow's +-- leniency and mask scaling; writes 8 / 24 / 32 bpp as Pillow. Not supported: embedded JPEG / PNG, OS/2 Huffman, RLE24. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -40,11 +32,11 @@ export type Info = { } export type DecodeOptions = { - maxPixels: number?, -- refuse images with more pixels than this (default 2^26 = 64 Mpx) + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - bitDepth: (number | "auto")?, -- 8, 24, 32; default "auto": 8 when opaque with <= 256 colours, else 24 when opaque, else 32 - header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS with an alpha mask) or "info" (BI_RGB, as Pillow) + bitDepth: (number | "auto")?, -- default "auto": 8 if opaque with <= 256 colours, else 24 if opaque, else 32 + header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS) or "info" (BI_RGB, as Pillow) } -- ------------------------------------------------------------------------------------------------ constants @@ -54,7 +46,6 @@ local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "p local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz --- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer) local function whole(r: Bytes.Reader): buffer if r.base == 0 and r.limit == buffer.len(r.buf) then return r.buf @@ -70,7 +61,6 @@ function Bmp.sniff(r: Bytes.Reader): number if r:peek(2) ~= "BM" then return 0 end - -- a known header size: a strong match; "BM" alone is weak local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256 if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then return 0.9 @@ -79,7 +69,6 @@ function Bmp.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err local function parseHeader(buf: buffer): (Info?, any) local n = buffer.len(buf) if n < 18 then @@ -127,13 +116,11 @@ local function parseHeader(buf: buffer): (Info?, any) return info end --- info(r) -> Info | nil, Err: the header without decoding the pixels function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?) return parseHeader(whole(r)) end --- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate --- the top bits instead, which can differ by 1). m = 0 -> { empty }. +-- v * 255 // m, as Pillow (browsers replicate the top bits, which can differ by 1) local function scaleTable(m: number, empty: number): buffer local t = buffer.create(m + 1) if m == 0 then @@ -146,7 +133,7 @@ local function scaleTable(m: number, empty: number): buffer return t end --- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16) +-- a mask wider than 16 bits keeps its top 16 local function channel(mask: number, empty: number): (number, number, buffer) if mask == 0 then return 0, 0, scaleTable(0, empty) @@ -166,7 +153,6 @@ local function channel(mask: number, empty: number): (number, number, buffer) return sh, m, scaleTable(m, empty) end --- decode(r, opts?) -> rgba8 Image | nil, Err function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) local buf = whole(r) local info, herr = parseHeader(buf) @@ -236,7 +222,6 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end end - -- palette local entrySize = if hs == 12 then 3 else 4 local declared = if hs >= 36 then readu32(buf, 46) else 0 local palCount = 0 @@ -334,7 +319,6 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- encode(img, opts?) -> buffer | nil, Err function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image") diff --git a/src/Rosetta/image/dds/init.luau b/src/Rosetta/image/dds/init.luau index 34e22a4..0cb3fc2 100644 --- a/src/Rosetta/image/dds/init.luau +++ b/src/Rosetta/image/dds/init.luau @@ -1,17 +1,7 @@ --!strict --- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new --- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM / --- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the --- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the --- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six --- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there --- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" / --- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by --- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more. --- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32 --- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the --- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8), --- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5. +-- image/dds: DirectDraw Surface (Microsoft DDS guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10). Supports: DXGI +-- formats with a pixel layout, legacy FourCC and bit-mask formats, mips, cube maps, arrays, volumes; writes rgba8 / BC1 +-- / BC3 / BC4 / BC5 / rgba16 / rgbaf32. Not supported: planar video (NV12, P010), P8, R1_UNORM, stencil formats. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,18 +24,17 @@ local Dds = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H sources (default false: rgba8) - mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) - surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) - maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface) + native: boolean?, -- default false: rgba8 + mips: boolean?, -- default false + surfaces: boolean?, -- default true + maxPixels: number?, -- default 2^26, over every decoded surface } export type EncodeOptions = { - pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: - -- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones - mips: boolean?, -- write a full mip chain (default false) - dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays) - cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube") - alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128) + pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, + mips: boolean?, -- default false + dx10: boolean?, -- default: when the format needs it, or for arrays + cube: boolean?, -- default: when img.meta.layout == "cube" + alphaThreshold: number?, -- default 128 } -- ------------------------------------------------------------------------------------------------ constants @@ -101,10 +90,10 @@ export type Info = { height: number, depth: number, mips: number, - format: string, -- the texture format name (codecs/image/Texture) + format: string, layout: string, -- "2d" | "cube" | "array" | "volume" layers: number, - faces: { string }, -- cube faces present (in file order), else { } + faces: { string }, -- in file order srgb: boolean, dxgi: number?, fourcc: string?, @@ -118,7 +107,6 @@ local function u32(b: buffer, o: number): number return buffer.readu32(b, o) end --- info(r) -> Info | nil, Err (the headers only) function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) local b, o, n = r.buf, r.base, r.limit - r.base if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then @@ -228,7 +216,6 @@ function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) if not d then return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92) end - -- the common masks map onto named texel formats (fast paths, sane names) local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum)) local named = ({ ["32:ff:ff00:ff0000:ff000000:false"] = "rgba8", @@ -265,7 +252,6 @@ function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) return info, nil end --- the bytes of one surface of format f local function surfaceSize(info: any, w: number, h: number): number if info.format == "masked" then return (info.masked :: Texel.Desc).bytes * w * h @@ -359,7 +345,6 @@ end local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 } local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 } --- the surface bytes of one image in format f local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?) local w, h, px = img.width, img.height, img.pixels if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then @@ -448,7 +433,6 @@ function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if pf ~= needs then return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) end - -- surfaces: the frames (array / cube faces) or the image local images: { Types.Image } = { img } if img.frames and #img.frames > 1 then images = {} diff --git a/src/Rosetta/image/exr/Codec.luau b/src/Rosetta/image/exr/Codec.luau index f28c415..97d9a7b 100644 --- a/src/Rosetta/image/exr/Codec.luau +++ b/src/Rosetta/image/exr/Codec.luau @@ -1,9 +1,7 @@ --!strict --!native --!optimize 2 --- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3- --- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave), --- ZIP encode, and the per-line channel sample conversion to floats. Never throws. +-- image/exr/Codec: OpenEXR RLE / ZIP / ZIPS blocks and sample conversion (after ImfZip / ImfRle, BSD-3-Clause). local Deflate = require("@rosetta/codecs/compress/Deflate") local Half = require("@rosetta/codecs/image/Half") @@ -12,7 +10,6 @@ local Codec = {} local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 local HALF = Half.TABLE --- undoes the predictor and the interleave of t (n bytes) -> a new buffer local function reconstruct(t: buffer, n: number): buffer local prev = if n > 0 then readu8(t, 0) else 0 for i = 1, n - 1 do @@ -30,7 +27,6 @@ local function reconstruct(t: buffer, n: number): buffer return out end --- rle(src, p, n, outSize) -> the raw block | nil, message function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) local t = buffer.create(outSize) local o, stop = 0, p + n @@ -60,7 +56,6 @@ function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer? return reconstruct(t, outSize), nil end --- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS) function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) local t, err = Deflate.zlib(src, p, n, outSize) if not t then @@ -72,7 +67,6 @@ function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffe return reconstruct(t, outSize), nil end --- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib) function Codec.zip(raw: buffer, level: number): buffer local n = buffer.len(raw) local t = buffer.create(n) @@ -94,8 +88,6 @@ function Codec.zip(raw: buffer, level: number): buffer return Deflate.zlibCompress(t, { level = level }) :: buffer end --- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into --- dst (f32) at byte offset d, step bytes apart; returns the source offset after them function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number if kind == 1 then for i = 0, count - 1 do diff --git a/src/Rosetta/image/exr/Piz.luau b/src/Rosetta/image/exr/Piz.luau index 3016030..4eb4ca6 100644 --- a/src/Rosetta/image/exr/Piz.luau +++ b/src/Rosetta/image/exr/Piz.luau @@ -1,10 +1,7 @@ --!strict --!native --!optimize 2 --- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor --- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman --- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit --- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data. +-- image/exr/Piz: OpenEXR PIZ decompressor (after ImfPizCompressor / ImfHuf / ImfWav, BSD-3-Clause). local Piz = {} local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32 @@ -16,7 +13,6 @@ local DECBITS = 14 local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 -- ------------------------------------------------------------------------------------------------ Huffman --- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1) local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number? local c, lc = 0, 0 local function bits(n: number): number? @@ -69,7 +65,6 @@ local function unpackTable(src: buffer, p: number, limit: number, im: number, iM return p end --- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string? if n == 0 then return if nRaw == 0 then nil else "empty Huffman data" @@ -136,7 +131,6 @@ local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: num end end end - -- decode MSB-first from a zero-padded copy local nbytes = (nBits + 7) // 8 local data = buffer.create(nbytes + 8) buffer.copy(data, 0, src, q, nbytes) @@ -211,7 +205,6 @@ local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: num end -- ------------------------------------------------------------------------------------------------ wavelet --- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements) local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number) local w14 = mx < 16384 local n = math.min(nx, ny) @@ -280,9 +273,6 @@ end -- ------------------------------------------------------------------------------------------------ decode export type Chan = { nx: number, ny: number, size: number, ys: number } --- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message. --- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and --- ySampling. function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?) local total = 0 for _, c in chans do @@ -313,7 +303,6 @@ function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: nu buffer.copy(bitmap, minNZ, src, p, cnt) p += cnt end - -- reverse LUT local lut = buffer.create(USHORT_RANGE * 2) local k = 0 for i = 0, USHORT_RANGE - 1 do @@ -348,7 +337,6 @@ function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: nu for i = 0, total - 1 do writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2)) end - -- planes -> scanlines local o = 0 local cursor = table.clone(starts) for y = minY, maxY do diff --git a/src/Rosetta/image/exr/init.luau b/src/Rosetta/image/exr/init.luau index 342f05c..794c928 100644 --- a/src/Rosetta/image/exr/init.luau +++ b/src/Rosetta/image/exr/init.luau @@ -1,17 +1,7 @@ --!strict --- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ --- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and --- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts --- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips), --- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any --- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image --- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels. --- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear --- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) --- for colour, round(clamp(a, 0, 1) * 255) for alpha. --- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only --- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A / --- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used). +-- image/exr: OpenEXR (openexr.com file layout docs; PIZ after OpenEXR, BSD-3-Clause: licenses/openexr-LICENSE.md). +-- Supports: single / multipart, scanline / tiled (mip / rip level 0, mips), NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT +-- / UINT, subsampling, layers; writes scanlines. Not supported: deep, PXR24 / B44(A) / DWA / HTJ2K / ZSTD. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,17 +24,17 @@ local Exr = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) - part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1) - layer: string?, -- read .R / .G / .B / .A instead of R / G / B / A - mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) + part: (number | string)?, -- 1-based index or name; default 1 + layer: string?, + mips: boolean?, -- default false + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { compression: ("none" | "zips" | "zip")?, -- default "zip" pixelType: ("half" | "float")?, -- default "half" - alpha: boolean?, -- write A (default: when some alpha is not 1) - level: number?, -- zlib level 1..9 (default 6) + alpha: boolean?, -- default: when some alpha is not 1 + level: number?, -- 1..9, default 6 } -- ------------------------------------------------------------------------------------------------ constants @@ -91,7 +81,6 @@ local function f32(b: buffer, o: number): number return readf32(b, o) end --- one attribute value of a known type local function value(b: buffer, p: number, size: number, typ: string): any if typ == "chlist" then local list: { Channel } = {} @@ -146,7 +135,6 @@ local function value(b: buffer, p: number, size: number, typ: string): any return raw end --- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?) local attrs: { [string]: any } = {} local types: { [string]: string } = {} @@ -179,7 +167,6 @@ local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, end end --- level sizes of a tiled part local function levelSize(n: number, l: number, roundUp: boolean): number local d = 2 ^ l return math.max(1, if roundUp then math.ceil(n / d) else n // d) @@ -201,7 +188,6 @@ local function levelCount(w: number, h: number, mode: number, roundUp: boolean): return count(w), count(h) end --- chunk count of a part (single-part files: computed) local function chunkCount(pt: Part): number local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1 if not pt.tiled then @@ -287,7 +273,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) if multi then p += 1 end - -- offset tables for _, pt in info.parts do local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0) if n < 0 or n > 2 ^ 24 then @@ -306,20 +291,17 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?) return info, nil end --- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err function Exr.info(r: Bytes.Reader): (Info?, Err.Err?) return parse(r) end --- bytes of a sample kind local SIZE = { [0] = 4, 2, 4 } --- number of multiples of s in [a, b] local function samples(a: number, b: number, s: number): number return b // s - (a - 1) // s end -type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey) +type Target = { [number]: number } local function newPlane(pw: number, ph: number): buffer local px = buffer.create(pw * ph * 16) @@ -328,7 +310,6 @@ local function newPlane(pw: number, ph: number): buffer end return px end --- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy) local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err? local p = dp for y = y0, y1 do @@ -373,7 +354,6 @@ local function block(part: Part, target: Target, data: buffer, dp: number, y0: n return nil end --- the raw bytes of a block (uncompressed size raw) local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?) if size == raw or comp == 0 then if size < raw then @@ -443,7 +423,6 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if w * h > maxPixels then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) end - -- channel -> output component local prefix = if opts and opts.layer then opts.layer .. "." else "" local target: Target = {} local hasRgb = false @@ -466,7 +445,6 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end end local multi = info.multipart - -- offsets: single-part tables with holes are rebuilt from the chunk sequence local offsets = part.offsets local bad = false for _, o in offsets do @@ -512,7 +490,7 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end end - local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels + local planes: { [number]: buffer } = { [0] = newPlane(w, h) } local tiles = part.tiles local roundUp = tiles ~= nil and tiles[4] == 1 local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1 @@ -684,7 +662,6 @@ function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "pixelType must be half or float") end local level = opts and opts.level or 6 - -- the float values local n = w * h local fl = buffer.create(n * 16) if img.format == "rgbaf32" then @@ -710,7 +687,6 @@ function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) local sz = if kind == 1 then 2 else 4 local lpb = LINES[comp] local nblocks = (h + lpb - 1) // lpb - -- header local hw = Bytes.writer(512) hw:string(MAGIC) hw:u32le(2) diff --git a/src/Rosetta/image/gif/Decode.luau b/src/Rosetta/image/gif/Decode.luau index 98a6c7c..f258699 100644 --- a/src/Rosetta/image/gif/Decode.luau +++ b/src/Rosetta/image/gif/Decode.luau @@ -1,15 +1,12 @@ --!strict --!native --!optimize 2 --- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to --- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every --- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4. +-- image/gif/Decode: GIF frame pixels: palette indexes (plain or interlaced) to rgba8, drawn onto the canvas. local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Decode = {} --- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from --- 2, every 2nd from 1) +-- interlace passes: every 8th row from 0, every 8th from 4, every 4th from 2, every 2nd from 1 local function interlacedRow(fh: number): { number } local map = table.create(fh, 0) local r = 0 @@ -24,8 +21,6 @@ local function interlacedRow(fh: number): { number } return map end --- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the --- transparent one already alpha 0) function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) local rows = if interlaced then interlacedRow(fh) else nil for y = 0, fh - 1 do @@ -37,7 +32,6 @@ function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: bool end end --- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped) function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) @@ -53,7 +47,6 @@ function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: end end --- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background) function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) local x0, y0 = math.max(0, fx), math.max(0, fy) local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) diff --git a/src/Rosetta/image/gif/init.luau b/src/Rosetta/image/gif/init.luau index 1445572..46cf578 100644 --- a/src/Rosetta/image/gif/init.luau +++ b/src/Rosetta/image/gif/init.luau @@ -1,18 +1,7 @@ --!strict --- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image --- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames --- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / --- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames --- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize --- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with --- alpha < 128 as the transparent index. --- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" --- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over). --- --- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every --- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the --- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as --- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever). +-- image/gif: GIF87a / GIF89a, from the GIF89a spec (CompuServe 1990). Supports: every image, interlace, LZW code sizes +-- 1..8, transparency, GCE delays / disposal, NETSCAPE2.0 / ANIMEXTS1.0 loops, comments; writes quantized frames. Not +-- supported: the plain text extension, the aspect ratio, the user input flag, blend "source" frames. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,17 +23,16 @@ local Gif = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26) - maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28) - maxFrames: number?, -- stop after this many frames (default: all) + maxPixels: number?, -- default 2^26 + maxTotalPixels: number?, -- default 2^28 + maxFrames: number?, -- default: all } export type EncodeOptions = { - maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed) + maxColors: number?, -- 2..256, default 256 method: ("mediancut" | "octree")?, -- default "mediancut" - dither: boolean?, -- Floyd-Steinberg (default false) - loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops) - globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table, - -- each animation frame gets its own local table) + dither: boolean?, -- Floyd-Steinberg, default false + loops: number?, -- 0 = forever, 1..65536; default img.loops + globalPalette: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -59,7 +47,6 @@ function Gif.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } }) local t = buffer.create(1024) local list: { { number } } = table.create(n) :: { { number } } @@ -110,14 +97,12 @@ function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local comments: { string } = {} local loops: number? = nil local total = 0 - -- the pending Graphic Control Extension local delay, dispose, trans = 0, 0, -1 local truncated = false local interlacedAny = false local localTables = 0 local minCode = 8 local limit = r.limit - -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end) local function subBlocks(): (buffer?, number) local p = r.pos local n = 0 @@ -287,7 +272,6 @@ function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E break end else - -- junk between blocks: stop here, keeping what was read if #frames == 0 then return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1) end @@ -340,7 +324,6 @@ local function hasTransparency(px: buffer, n: number): boolean return false end --- palette list -> padded table bytes (power of two entries, >= 2) and its size code local function writeTable(w: Bytes.Writer, pal: { { number } }): number local bits = 1 while bit32.lshift(1, bits) < #pal do @@ -381,7 +364,6 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, Err.new(Err.ARG, "method must be mediancut or octree") end local dither = opts and opts.dither or false - -- the frames to write: { image, x, y, delay, dispose } local list: { Types.Frame } = {} if type(img.frames) == "table" and #(img.frames :: any) > 0 then for i, f in img.frames :: { Types.Frame } do @@ -402,13 +384,11 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then return nil, Err.new(Err.ARG, "loops must be 0..65536") end - -- palettes local shared = (opts and opts.globalPalette) or not animated local qopts: Quantize.PaletteOptions = { method = method, dither = dither } local globalPal: { { number } }? = nil local globalTrans = false if shared then - -- every frame's pixels together local npx = 0 for _, f in list do npx += f.image.width * f.image.height diff --git a/src/Rosetta/image/hdr/Codec.luau b/src/Rosetta/image/hdr/Codec.luau index 7f97f5e..4bde784 100644 --- a/src/Rosetta/image/hdr/Codec.luau +++ b/src/Rosetta/image/hdr/Codec.luau @@ -1,17 +1,13 @@ --!strict --!native --!optimize 2 --- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes --- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE --- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then --- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and --- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked. +-- image/hdr/Codec: Radiance RGBE scanlines (Graphics Gems II; rgbe.c): mantissa * 2^(e - 136), no +0.5, as stb_image. local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32 local frexp = math.frexp local Codec = {} --- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes) +-- old-style RLE: 1, 1, 1, n repeats the previous pixel (n << 8 for consecutive markers); new-style: 2, 2, width, planes function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?) if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then @@ -95,7 +91,6 @@ function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buf return p, nil end --- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number) for i = 0, n - 1 do local q = i * 4 @@ -115,7 +110,6 @@ function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: end end --- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe) function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) for x = 0, w - 1 do local q = (y * w + x) * 16 @@ -162,7 +156,6 @@ function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) end end --- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8 function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number writeu8(out, o, 2) writeu8(out, o + 1, 2) @@ -172,7 +165,6 @@ function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number for c = 0, 3 do local cur = 0 while cur < w do - -- find the next run of at least 4 local begRun = cur local runCount = 0 local oldRun = 0 @@ -187,14 +179,12 @@ function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number end end end - -- a short run just before the long one if oldRun > 1 and oldRun == begRun - cur then writeu8(out, o, 128 + oldRun) writeu8(out, o + 1, readu8(row, cur * 4 + c)) o += 2 cur = begRun end - -- raw bytes up to the run while cur < begRun do local n = math.min(begRun - cur, 128) writeu8(out, o, n) diff --git a/src/Rosetta/image/hdr/init.luau b/src/Rosetta/image/hdr/init.luau index 33a8e5f..7be0e4d 100644 --- a/src/Rosetta/image/hdr/init.luau +++ b/src/Rosetta/image/hdr/init.luau @@ -1,12 +1,7 @@ --!strict --- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions. --- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of --- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution --- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines. --- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion: --- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a --- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767). --- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored). +-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), from the Radiance file format notes and rgbe.c. Supports: "#?" headers, +-- 32-bit_rle_rgbe, EXPOSURE (kept, not applied), the eight orientations, flat / old / new RLE; writes -Y +X new RLE. +-- Not supported: 32-bit_rle_xyze, PRIMARIES / COLORCORR (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,12 +21,12 @@ local Hdr = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - rle: boolean?, -- new-style RLE scanlines (default true) - exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1) + rle: boolean?, -- default true + exposure: number?, -- default: meta.exposure when not 1 } -- ------------------------------------------------------------------------------------------------ constants @@ -57,7 +52,6 @@ function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local maxPixels = opts and opts.maxPixels or 2 ^ 26 local b, limit = r.buf, r.limit local p = r.base - -- header lines up to the first empty one local function line(): string? local s = p while p < limit and buffer.readu8(b, p) ~= 10 do @@ -187,7 +181,6 @@ function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local px = img.pixels if bpp == 4 then - -- rgba8 through the inverse of the decoder's display curve local lut = table.create(256, 0) for v = 0, 255 do lut[v + 1] = (v / 255) ^ 2.2 diff --git a/src/Rosetta/image/icns/init.luau b/src/Rosetta/image/icns/init.luau index dd4de85..7e09b99 100644 --- a/src/Rosetta/image/icns/init.luau +++ b/src/Rosetta/image/icns/init.luau @@ -1,13 +1,7 @@ --!strict --- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode: --- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha --- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any --- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them), --- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists --- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns --- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage --- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 / --- 48 / 128 with masks. +-- image/icns: Apple icon images (icns resource type). Supports: is32 / il32 / ih32 / it32 (icns RLE) with s8mk / l8mk / +-- h8mk / t8mk masks, ic04 / ic05 ARGB, 1-bit ics# / ICN# / ich# / icm#, PNG entries through opts.decodeImage; writes +-- PNG or RLE entries. Not supported: JPEG 2000 entries, 4 / 8-bit palette entries, nested dark-mode / TOC chunks. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,12 +22,12 @@ local Icns = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) - maxPixels: number?, -- refuse entries larger than this (default 2^22) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxPixels: number?, -- default 2^22 } export type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) - legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + legacy: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -58,7 +52,6 @@ function Icns.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4) local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean for _, ch in channels do local i = 0 @@ -228,7 +221,6 @@ function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- the icns RLE of one channel (count bytes, step 4 from ch) into w local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number) local i = 0 while i < count do diff --git a/src/Rosetta/image/ico/Dib.luau b/src/Rosetta/image/ico/Dib.luau index e8bc702..8be8878 100644 --- a/src/Rosetta/image/ico/Dib.luau +++ b/src/Rosetta/image/ico/Dib.luau @@ -1,18 +1,14 @@ --!strict --!native --!optimize 2 --- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from --- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit --- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha --- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are --- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's. +-- image/ico/Dib: ICO / CUR DIBs: XOR bitmap (1..32-bit, bottom-up, 4-byte rows) + 1-bit AND mask (1 = transparent). local Pixels = require("@rosetta/codecs/image/Pixels") local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Dib = {} --- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out +-- 32-bit entries use their alpha unless it is all zero (old icons); then the AND mask decides function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?) local stride = ((w * bpp + 31) // 32) * 4 local maskStride = ((w + 31) // 32) * 4 @@ -61,8 +57,6 @@ function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: return true, nil end --- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1). --- out needs room for w * h * 4 + maskStride * h bytes. function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number for y = h - 1, 0, -1 do for x = 0, w - 1 do diff --git a/src/Rosetta/image/ico/init.luau b/src/Rosetta/image/ico/init.luau index 2a59ffa..400fc6b 100644 --- a/src/Rosetta/image/ico/init.luau +++ b/src/Rosetta/image/ico/init.luau @@ -1,14 +1,7 @@ --!strict --- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every --- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or --- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are --- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest); --- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png --- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as --- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it --- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot. --- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS --- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes. +-- image/ico: Windows icons and cursors (ICO / CUR), from Microsoft's ICO documentation. Supports: every entry as a BMP +-- DIB (1..32-bit, AND mask) or PNG (opts.decodeImage), CUR hotspots; writes 32-bit DIB or PNG entries. Not supported: +-- resizing to icon sizes, DIB compression (BI_BITFIELDS read as 5-5-5 / BGRA), 2-colour planes. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,13 +21,13 @@ local Ico = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) - maxPixels: number?, -- refuse larger entries (default 2^26) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) - png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists) - cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + png: boolean?, -- default: only 256-pixel entries + cursor: boolean?, -- default: when the image has meta.hotspot } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/image/ilbm/init.luau b/src/Rosetta/image/ilbm/init.luau index 1d88a27..094a203 100644 --- a/src/Rosetta/image/ilbm/init.luau +++ b/src/Rosetta/image/ilbm/init.luau @@ -1,12 +1,7 @@ --!strict --- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks --- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a --- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A), --- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or --- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH --- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else --- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer --- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored). +-- image/ilbm: IFF ILBM / PBM (EA IFF 85 "ILBM", Amiga ROM Kernel Manual). Supports: 1..8 planes + CMAP, EHB (CAMG +-- 0x80), HAM6 / HAM8 (CAMG 0x800; 4-bit v -> v * 17, ilbmtoppm shifts), 24 / 32 planes, PBM, masking 1 / 2, ByteRun1, +-- NAME / ANNO / AUTH. Not supported: ANIM, RGBN / RGB8 / ACBM / DEEP, SHAM / PCHG (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,11 +23,11 @@ local Ilbm = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false) - maxPixels: number?, -- refuse larger images (default 2^26) + adjustColors: boolean?, -- default false + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - compress: boolean?, -- ByteRun1 (default true) + compress: boolean?, -- default true } local readu8, readu16 = buffer.readu8, buffer.readu16 @@ -92,7 +87,6 @@ function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8) local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham - -- palette local pal = buffer.create(1024) local ncol = 0 if cmap then @@ -125,7 +119,6 @@ function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000) end end - -- the body, decompressed local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2 local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h local raw = buffer.create(total) diff --git a/src/Rosetta/image/jpeg/init.luau b/src/Rosetta/image/jpeg/init.luau index d41175a..22c996e 100644 --- a/src/Rosetta/image/jpeg/init.luau +++ b/src/Rosetta/image/jpeg/init.luau @@ -1,20 +1,7 @@ --!strict --- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG --- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical --- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the --- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi --- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images --- (coded 4:2:0 from the planes as they are). --- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit --- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt --- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's --- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt --- scans decode as far as they go (meta.truncated = true). --- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or --- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta; --- byte-identical to cjpeg for the same settings. --- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit --- or CMYK encoding. +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81) over codecs/image/Jpeg (from jpeg-luau 1.0, same author; bit-exact with +-- djpeg, byte-identical with cjpeg; IJG parts: licenses/libjpeg-turbo-LICENSE.md). Supports: SOF0/1/2/9/10, 8 / 12-bit, +-- scaled decodes, EXIF / ICC / COM / JFIF density. Not supported: lossless (SOF3), hierarchical, DNL, 2 components. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,20 +21,20 @@ local Jpeg = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only) - orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only) - native: boolean?, -- grey files decode to gray8 (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + scale: number?, -- 1 (default), 2, 4 or 8 + orient: boolean?, -- default false + native: boolean?, -- default false + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables - subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420") + quality: number?, -- 1..100, default 90 (libjpeg scaling of the T.81 annex K tables) + subsampling: ("420" | "422" | "444")?, -- default "420" progressive: boolean?, -- default false - optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises) - gray: boolean?, -- a one-component file (default: true for gray8 images) - restart: number?, -- restart interval in MCUs (default 0 = none) - jfif: boolean?, -- write the JFIF APP0 header (default true) - meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true) + optimize: boolean?, -- default false; progressive always optimises + gray: boolean?, -- default: true for gray8 images + restart: number?, -- in MCUs, default 0 = none + jfif: boolean?, -- default true + meta: boolean?, -- default true } export type Info = Codec.Info @@ -59,7 +46,6 @@ function Jpeg.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- info(r) -> Info | nil, Err (reads the headers up to the frame header) function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?) return Codec.info(r.buf, r.base, r.limit - r.base) end @@ -69,7 +55,7 @@ function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. return nil, Err.new(Err.ARG, "options must be a table") end local o = opts or {} :: DecodeOptions - -- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF) + -- two JPEGs back to back are an image and a preview, as in MPF return Codec.decode(r.buf, r.base, r.limit - r.base, { scale = o.scale, orient = o.orient, @@ -80,7 +66,6 @@ function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- the APP1 / APP2 / COM segments and the JFIF density from img.meta local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?) local segments = {} if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then diff --git a/src/Rosetta/image/ktx/init.luau b/src/Rosetta/image/ktx/init.luau index 2ddfa33..fa97078 100644 --- a/src/Rosetta/image/ktx/init.luau +++ b/src/Rosetta/image/ktx/init.luau @@ -1,15 +1,7 @@ --!strict --- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL --- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the --- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every --- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip --- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are --- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is --- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native. --- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16 --- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain, --- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and --- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard. +-- image/ktx: Khronos KTX 1.1 / KTX 2.0. Supports: KTX1 (GL compressed and uncompressed, big-endian), KTX2 (VkFormat BCn +-- / ETC2 / EAC / uncompressed; Zstd and ZLIB supercompression), mips, cubes, arrays, 3D, KTXorientation; writes +-- uncompressed KTX2. Not supported: Basis Universal (BasisLZ / UASTC), ASTC, PVRTC. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,18 +25,18 @@ local Ktx = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8) - mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) - surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) - maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface) + native: boolean?, -- default false: rgba8 + mips: boolean?, -- default false + surfaces: boolean?, -- default true + maxPixels: number?, -- default 2^26, over every decoded surface } export type EncodeOptions = { pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) - srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb") - mips: boolean?, -- a full mip chain (box filter; default false) - cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube") - zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none) - keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written) + srgb: boolean?, -- default: meta.colorSpace == "srgb" + mips: boolean?, -- default false + cube: boolean?, -- default: meta.layout == "cube" + zlib: number?, -- 1..9, default none + keyValue: { [string]: string }?, -- KTXwriter is always written } -- ------------------------------------------------------------------------------------------------ constants @@ -118,7 +110,7 @@ export type Info = { layers: number, faces: number, levels: number, - format: string?, -- the texture format name (nil when unsupported: see unsupported) + format: string?, unsupported: string?, srgb: boolean, opaque: boolean, -- BC1 RGB @@ -289,7 +281,6 @@ local function info2(r: Bytes.Reader): (Info?, Err.Err?) return info, nil end --- info(r) -> Info | nil, Err (the headers only) function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) local id = r:peek(12) if id == ID2 then @@ -300,7 +291,6 @@ function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) end --- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image local function swapped(b: buffer, p: number, n: number, size: number): buffer local out = buffer.create(n) buffer.copy(out, 0, b, p, n) @@ -352,7 +342,6 @@ function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local w, h, d = info.width, info.height, info.depth for level = 0, info.levels - 1 do local want = level == 0 or wantMips - -- the level's data: buf, offset, the image stride and row pitch local lb, lp = b, 0 local rowPitch: number? = nil local imgSize = Texture.size(fmt, w, h) :: number @@ -492,7 +481,6 @@ function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- format -> VkFormat, bytes per texel, component bytes, kind local OUT: { [string]: { number } } = { rgba8 = { 37, 4, 1 }, rgba16 = { 91, 8, 2 }, @@ -582,7 +570,6 @@ function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then return nil, Err.new(Err.ARG, "zlib level must be 1..9") end - -- level data: the images of every layer / face per level local levelData: { buffer } = {} local raw: { number } = {} local cur = table.clone(images) @@ -602,7 +589,6 @@ function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end levelData[lv] = lb end - -- key / value data local kvw = Bytes.writer() local pairs_: { { string } } = { { "KTXwriter", "rosetta" } } if opts and opts.keyValue then diff --git a/src/Rosetta/image/pcx/init.luau b/src/Rosetta/image/pcx/init.luau index 43a558f..137b5e9 100644 --- a/src/Rosetta/image/pcx/init.luau +++ b/src/Rosetta/image/pcx/init.luau @@ -1,9 +1,7 @@ --!strict --- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit --- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the --- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross --- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as --- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE. +-- image/pcx: ZSoft PC Paintbrush (ZSoft "Technical Reference Manual" header and RLE). Supports: 1-bit, 1-bit x 2..4 +-- planes (EGA), 2 / 4-bit packed, 8-bit with the 256-colour end palette, 8-bit x 3 / 4 planes, RLE across scan lines, +-- uncompressed, DPI; writes 8-bit palette or 24 / 32-bit planes. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,10 +21,10 @@ local Pcx = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxPixels: number?, -- refuse larger images (default 2^26) + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes + palette: boolean?, -- default true; false: always 24 / 32-bit planes } local readu8, readu16 = buffer.readu8, buffer.readu16 @@ -111,7 +109,6 @@ function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E p += n truncated = n < total end - -- palettes local pal = buffer.create(1024) local function setPal(i: number, rr: number, gg: number, bb: number) buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) @@ -183,7 +180,6 @@ function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- RLE of one plane row into w local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number) local i = 0 while i < n do diff --git a/src/Rosetta/image/png/Apng.luau b/src/Rosetta/image/png/Apng.luau index 32c0551..745a4ab 100644 --- a/src/Rosetta/image/png/Apng.luau +++ b/src/Rosetta/image/png/Apng.luau @@ -1,9 +1,7 @@ --!strict --!native --!optimize 2 --- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source / --- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the --- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle. +-- image/png/Apng: APNG 1.0 dispose / blend compositing; "over" uses ffmpeg pngdec.c's integer arithmetic (byte-exact). local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill @@ -13,7 +11,6 @@ local function div255(x: number): number return (x + 128) * 257 // 65536 end --- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean) for y = 0, fh - 1 do local so = y * fw * 4 @@ -46,7 +43,6 @@ local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: nu end end --- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend }) function Apng.composite(w: number, h: number, frames: { any }): { buffer } local canvas = bcreate(w * h * 4) local saved = bcreate(w * h * 4) diff --git a/src/Rosetta/image/png/Decode.luau b/src/Rosetta/image/png/Decode.luau index ce12b8f..a5d816d 100644 --- a/src/Rosetta/image/png/Decode.luau +++ b/src/Rosetta/image/png/Decode.luau @@ -1,12 +1,7 @@ --!strict --!native --!optimize 2 --- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the --- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes. --- Absorbed from png-luau src/Png/Decode.luau (same author). --- --- The caller (init) has validated the header and checked that the data holds at least the expected number of --- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws. +-- image/png/Decode: PNG unfiltering and expansion to RGBA8 (absorbed from png-luau src/Png/Decode.luau, same author). local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local bcopy = buffer.copy @@ -28,20 +23,16 @@ Decode.PASSES = PASSES local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } Decode.CHANNELS = CHANNELS --- bytes per row (without the filter byte) for a pass width function Decode.rowBytes(pw: number, channels: number, depth: number): number return (pw * channels * depth + 7) // 8 end --- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per --- complete pixel (at least 1). Returns true, or false + the bad filter type. local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) local stride = rb + 1 for r = 0, ph - 1 do local f = readu8(raw, p) local cur = p + 1 if f == 0 then - -- none elseif f == 1 then for i = cur + bpp, cur + rb - 1 do writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) @@ -51,7 +42,6 @@ local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: num local i = cur local e4 = cur + rb - 4 while i <= e4 do - -- four bytes at once: add without carries between the byte lanes local x, y = readu32(raw, i), readu32(raw, i - stride) local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F) writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080))) @@ -112,9 +102,6 @@ local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: num return true, 0 end --- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes. --- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none), --- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth. local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number) if ct == 6 then if depth == 8 then @@ -213,8 +200,6 @@ local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: num end end --- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8). --- Returns true, or false + message. function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) local channels = CHANNELS[ct] local bpp = math.max(1, (channels * depth) // 8) diff --git a/src/Rosetta/image/png/Encode.luau b/src/Rosetta/image/png/Encode.luau index d3f261d..03dfe29 100644 --- a/src/Rosetta/image/png/Encode.luau +++ b/src/Rosetta/image/png/Encode.luau @@ -1,9 +1,7 @@ --!strict --!native --!optimize 2 --- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and --- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute --- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image. +-- image/png/Encode: PNG colour type choice and filtering (per-row minimum sum of |signed residuals|, as libpng). local readu8, writeu8 = buffer.readu8, buffer.writeu8 local bcreate, bcopy = buffer.create, buffer.copy @@ -11,7 +9,6 @@ local Encode = {} local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } --- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray" function Encode.pickColorType(px: buffer, w: number, h: number): string local opaque, gray = true, true for i = 0, w * h - 1 do @@ -33,7 +30,6 @@ function Encode.pickColorType(px: buffer, w: number, h: number): string return "rgb" end --- convert rgba8 to the colour type's packed rows (no filter bytes) local function pack(px: buffer, w: number, h: number, ct: number): buffer local ch = CHANNELS[ct] if ch == 4 then @@ -70,8 +66,6 @@ local function paeth(a: number, b: number, c: number): number return c end --- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first); --- the arithmetic is inlined: this runs for every byte local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number) local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 local p = s - rb @@ -101,7 +95,6 @@ local function costs(src: buffer, s: number, rb: number, bpp: number, first: boo return c0, c1, c2, c3, c4 end --- write the row at s filtered with f to out[o + 1 ..] (out[o] = f) local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number) writeu8(out, o, f) o += 1 @@ -130,8 +123,6 @@ local function apply(src: buffer, s: number, rb: number, bpp: number, first: boo end end --- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of --- |signed residuals| (the libpng heuristic) function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer local ch = CHANNELS[ct] local src = pack(px, w, h, ct) diff --git a/src/Rosetta/image/png/init.luau b/src/Rosetta/image/png/init.luau index 2866ba2..aa33e33 100644 --- a/src/Rosetta/image/png/init.luau +++ b/src/Rosetta/image/png/init.luau @@ -1,14 +1,7 @@ --!strict --- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder. --- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16), --- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha --- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte). --- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose / --- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not --- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode --- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked. --- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are --- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output. +-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.) and APNG 1.0; from png-luau 1.0.0 (same author). Supports: every +-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT; writes RGBA / RGB / grey(+alpha) and APNG. Not +-- supported: colour management (iCCP kept raw), palette / 16-bit / interlaced output. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -32,14 +25,13 @@ local Png = { } export type DecodeOptions = { - checkCrc: boolean?, -- verify every chunk's CRC-32 (default false) - maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer) + checkCrc: boolean?, -- default false + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - level: number?, -- deflate level 0..9 (default 6) + level: number?, -- 0..9, default 6 colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one - apng: boolean?, -- true: an APNG even without img.frames (one frame); false: a still PNG; default: APNG when - -- img.frames is a non-empty list + apng: boolean?, -- default: APNG when img.frames is a non-empty list } -- ------------------------------------------------------------------------------------------------ constants @@ -66,7 +58,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number } --- the IHDR at r's start: Header | nil, Err local function header(r: Bytes.Reader): (Header?, Err.Err?) local b, o, n = r.buf, r.base, r.limit - r.base if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then @@ -98,7 +89,6 @@ local function header(r: Bytes.Reader): (Header?, Err.Err?) return h, nil end --- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header) function Png.info(r: Bytes.Reader): (Header?, Err.Err?) return header(r) end @@ -117,8 +107,6 @@ type FrameControl = { } local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" } --- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split --- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h) local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err? -- the inflated size: every (pass) row has a filter byte local channels = Decode.CHANNELS[ct] @@ -175,7 +163,6 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) end local b, n = r.buf, r.limit - -- chunks local pal = buffer.create(1024) for i = 0, 255 do buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black @@ -375,7 +362,6 @@ local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 } local BLEND_CODES: { [string]: number } = { source = 0, over = 1 } --- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds local function delayFraction(delay: number): (number, number) for den = 1, 1000 do local num = math.floor(delay * den + 0.5) @@ -407,7 +393,6 @@ local function validImage(im: any): boolean and buffer.len(im.pixels) >= im.width * im.height * 4 end --- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?) local frames = img.frames local mode = if opts then opts.apng else nil @@ -465,7 +450,6 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) local want = opts and opts.colorType or "auto" local ctName: string = want if want == "auto" then - -- the smallest colour type that holds the image and every frame local alpha, color = false, false local function scan(im: Types.Image) local c = Encode.pickColorType(im.pixels, im.width, im.height) @@ -569,8 +553,6 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a --- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }. function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?) if not validImage(img) then return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image") diff --git a/src/Rosetta/image/pnm/Codec.luau b/src/Rosetta/image/pnm/Codec.luau index 846492e..a06a092 100644 --- a/src/Rosetta/image/pnm/Codec.luau +++ b/src/Rosetta/image/pnm/Codec.luau @@ -1,17 +1,13 @@ --!strict --!native --!optimize 2 --- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm, --- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM --- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling. --- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked. +-- image/pnm/Codec: Netpbm sample loops: P1 digits may run together; PFM either byte order. local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32 local byteswap = bit32.byteswap local Codec = {} --- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each). -- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?) if mode == 1 then @@ -33,7 +29,6 @@ function Codec.readSamples(b: buffer, p: number, limit: number, count: number, m end local i = 0 while i < count do - -- skip whitespace and comments while p < limit do local c = readu8(b, p) if c == 35 then -- '#' @@ -73,7 +68,6 @@ function Codec.readSamples(b: buffer, p: number, limit: number, count: number, m return true, nil end --- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?) local rowBytes = (w + 7) // 8 if p + rowBytes * h > limit then @@ -89,11 +83,9 @@ function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: numbe return true, nil end --- format codes for pack / extract Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 --- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for --- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval)) +-- 8-bit: round(v * 255 / maxval) function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer) local wide = fmt == 4 or fmt == 5 local top = if wide then 65535 else 255 @@ -144,7 +136,6 @@ function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: bo end end --- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?) if p + w * h * ch * 4 > limit then return false, "truncated" @@ -182,8 +173,7 @@ local function f(v: number): number return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5) end --- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for --- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide +-- grey from colour: Pillow's L = (299 R + 587 G + 114 B) / 1000 function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer local out = buffer.create(n * ch * 2) local srcWide = fmt == 4 or fmt == 5 @@ -232,7 +222,6 @@ function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boo return out end --- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian) function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number if wide then for i = 0, count - 1 do @@ -250,7 +239,6 @@ function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer return o end --- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1) function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number for y = 0, h - 1 do local acc, nb = 0, 0 @@ -271,8 +259,6 @@ function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out return o end --- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM --- rows, bottom-to-top function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number for y = h - 1, 0, -1 do for x = 0, w - 1 do diff --git a/src/Rosetta/image/pnm/init.luau b/src/Rosetta/image/pnm/init.luau index 24f8b45..32b29f7 100644 --- a/src/Rosetta/image/pnm/init.luau +++ b/src/Rosetta/image/pnm/init.luau @@ -1,12 +1,7 @@ --!strict --- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5), --- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any --- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows). --- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout --- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is --- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel --- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image. --- Not supported: multi-image streams (the first image is read), PAM depths above 4. +-- image/pnm: Netpbm, from the Netpbm format pages: PBM (P1 / P4), PGM (P2 / P5), PPM (P3 / P6), PAM (P7, depth 1..4) +-- and PFM (PF / Pf, either byte order, bottom-up rows). Supports: maxval 1..65535, PFM to rgba8 as clamp(v, 0, 1) * +-- 255; writes all seven types. Not supported: multi-image streams, PAM depths above 4. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,15 +21,14 @@ local Pnm = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- keep the source layout (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour - -- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default - ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false) - maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it - threshold: number?, -- pbm: grey below this (0..255) is black (default 128) + format: string?, -- default: grey -> pgm, opaque colour -> ppm, alpha -> pam, rgbaf32 -> pfm; "pnm" means the default + ascii: boolean?, -- default false + maxval: number?, -- 1..65535, default 255 (65535 for 16-bit / float sources) + threshold: number?, -- 0..255, default 128 } -- ------------------------------------------------------------------------------------------------ constants @@ -66,7 +60,6 @@ local function isSpace(c: number): boolean return c == 32 or (c >= 9 and c <= 13) end --- the next header token from p: token, position after it (nil at the end) local function token(b: buffer, p: number, limit: number): (string?, number) while p < limit do local c = readu8(b, p) @@ -161,7 +154,6 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E maxval = int(v) elseif key == "TUPLTYPE" then tupl = v - -- the rest of the line belongs to the value while p < limit and readu8(b, p) ~= 10 do p += 1 end @@ -184,7 +176,7 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E else return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) end - local w, h, maxval = w :: number, h :: number, maxval :: number -- each branch above returns when one is nil + local w, h, maxval = w :: number, h :: number, maxval :: number if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval)) end diff --git a/src/Rosetta/image/qoi/Codec.luau b/src/Rosetta/image/qoi/Codec.luau index 305ce81..080cf47 100644 --- a/src/Rosetta/image/qoi/Codec.luau +++ b/src/Rosetta/image/qoi/Codec.luau @@ -1,16 +1,13 @@ --!strict --!native --!optimize 2 --- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org). --- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read --- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full. +-- image/qoi/Codec: QOI op loops, from the QOI specification 1.0 (qoiformat.org). local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 local Codec = {} local index = buffer.create(256) --- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out) function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) buffer.fill(index, 0, 0, 256) local r, g, bl, a = 0, 0, 0, 255 @@ -82,7 +79,6 @@ function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: numbe return true, nil end --- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number buffer.fill(index, 0, 0, 256) local pr, pg, pb, pa = 0, 0, 0, 255 diff --git a/src/Rosetta/image/qoi/init.luau b/src/Rosetta/image/qoi/init.luau index 64f829c..450b35d 100644 --- a/src/Rosetta/image/qoi/init.luau +++ b/src/Rosetta/image/qoi/init.luau @@ -1,8 +1,6 @@ --!strict --- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec. --- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files); --- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag. --- Not supported: nothing in the spec is left out. +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). Supports: the whole spec (RGB / RGBA, +-- both colour space tags in meta.source.colorSpace). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -22,12 +20,12 @@ local Qoi = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4) - linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear") + channels: number?, -- default: 3 for rgb8 or opaque rgba8, else 4 + linear: boolean?, -- default: meta.source.colorSpace == "linear" } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/image/sgi/init.luau b/src/Rosetta/image/sgi/init.luau index 6be54bd..4f72c2d 100644 --- a/src/Rosetta/image/sgi/init.luau +++ b/src/Rosetta/image/sgi/init.luau @@ -1,10 +1,7 @@ --!strict --- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format" --- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB) --- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16 --- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is --- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen / --- colour-map files (colormap field 1..3: UNSUPPORTED). +-- image/sgi: Silicon Graphics images (Paul Haeberli's "The SGI Image File Format" 1.00). Supports: verbatim and RLE, 1 +-- / 2 bytes per channel, 1..4 channels, dimension 1..3, bottom-up rows, the image name; writes RGB(A) 8 / 16-bit. Not +-- supported: dithered / screen / colour-map files (colormap 1..3). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,12 +21,12 @@ local Sgi = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- rgba16 for 2-byte files (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - rle: boolean?, -- RLE storage (default true) - name: string?, -- the image name (up to 79 bytes; default meta.text.name) + rle: boolean?, -- default true + name: string?, -- up to 79 bytes; default meta.text.name } local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 @@ -79,7 +76,7 @@ function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E if w * h > maxPixels then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) end - -- channel planes as 16-bit samples (8-bit values scaled * 257) + -- 8-bit values scaled * 257 local plane = buffer.create(w * h * z * 2) local truncated = false local function put(c: number, row: number, x: number, v: number) diff --git a/src/Rosetta/image/sunras/init.luau b/src/Rosetta/image/sunras/init.luau index 8472e83..4e86cb8 100644 --- a/src/Rosetta/image/sunras/init.luau +++ b/src/Rosetta/image/sunras/init.luau @@ -1,10 +1,7 @@ --!strict --- image/sunras: Sun Raster (rasterfile(5), SunOS ; new code). Decode: 1-bit (0 = white without a colour --- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD, --- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in --- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the --- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED), --- raw colour maps (RMT_RAW is ignored). +-- image/sunras: Sun Raster (rasterfile(5), SunOS ). Supports: 1-bit (0 = white without a colour map), +-- 8-bit, 24 / 32-bit BGR / XBGR (RT_STANDARD, RT_OLD, RT_BYTE_ENCODED) or RGB / XRGB (RT_FORMAT_RGB), 0x80 RLE, 16-bit +-- row padding; 32-bit X is alpha unless all zero. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF, RMT_RAW. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,10 +22,10 @@ local Sunras = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxPixels: number?, -- refuse larger images (default 2^26) + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD + rle: boolean?, -- default true; false: RT_STANDARD } local MAGIC = "\89\166\106\149" diff --git a/src/Rosetta/image/tga/Codec.luau b/src/Rosetta/image/tga/Codec.luau index 1cbb0bd..666d1d6 100644 --- a/src/Rosetta/image/tga/Codec.luau +++ b/src/Rosetta/image/tga/Codec.luau @@ -1,15 +1,12 @@ --!strict --!native --!optimize 2 --- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0 --- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented --- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes. +-- image/tga/Codec: Truevision TGA 2.0 pixel loops: raw / RLE (packets may cross scanlines on read, never on write). local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 local Codec = {} --- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, --- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them) +-- kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number if kind == 0 then return readu8(b, p) * 0x10101 + 0xFF000000 @@ -33,7 +30,6 @@ local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: b end Codec.pixel = pixel --- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated? function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean) local n = w * h local i = 0 @@ -85,9 +81,6 @@ function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, return i, false end --- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1); --- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row. --- out needs room for w * h * (outBpp + 1) bytes. function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number local function get(q: number): number if srcBpp == 1 then diff --git a/src/Rosetta/image/tga/init.luau b/src/Rosetta/image/tga/init.luau index b483475..6d0e04f 100644 --- a/src/Rosetta/image/tga/init.luau +++ b/src/Rosetta/image/tga/init.luau @@ -1,13 +1,7 @@ --!strict --- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3) --- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 / --- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left, --- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit: --- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data --- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit. --- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left --- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage --- stamp, ...), which are ignored. +-- image/tga: Truevision TGA (TGA 2.0 specification). Supports: types 1 / 2 / 3 and RLE 9 / 10 / 11, 8..32-bit pixels +-- and colour maps, every origin, descriptor alpha bits (16-bit: only when 1 alpha bit is declared), the image ID, the +-- 2.0 footer. Not supported: the extension area's fields (ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,14 +21,14 @@ local Tga = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8) - maxPixels: number?, -- refuse larger images (default 2^26) + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - rle: boolean?, -- run-length encode (default false) - origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands) - alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255) - id: string?, -- the image ID field (up to 255 bytes; default meta.text.id) + rle: boolean?, -- default false + origin: ("bottom-left" | "top-left")?, -- default "bottom-left" + alpha: boolean?, -- default: 32-bit when any alpha < 255 + id: string?, -- up to 255 bytes; default meta.text.id } -- ------------------------------------------------------------------------------------------------ constants @@ -79,7 +73,6 @@ local function header(r: Bytes.Reader): Header? return h end --- plausible(h) -> nil | why not local function implausible(h: Header): string? local t = h.imageType if not TYPES[t] then @@ -141,7 +134,6 @@ function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local p = r.base + 18 local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil p += h.idLen - -- colour map local pal = buffer.create(4) local palN = 0 if h.cmapType == 1 and h.cmapLen > 0 then diff --git a/src/Rosetta/image/tiff/Pixels.luau b/src/Rosetta/image/tiff/Pixels.luau index 3bda9c6..5c2fef4 100644 --- a/src/Rosetta/image/tiff/Pixels.luau +++ b/src/Rosetta/image/tiff/Pixels.luau @@ -1,10 +1,7 @@ --!strict --!native --!optimize 2 --- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and --- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's --- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout. --- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack. +-- image/tiff/Pixels: TIFF predictors 2 / 3 (TIFF 6.0 section 14, technote 3; 3 as libtiff fpAcc / fpDiff). local Bytes = require("@rosetta/core/Bytes") local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64 @@ -15,8 +12,7 @@ local Pixels = {} local scratch = buffer.create(8) --- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an --- arbitrary payload, which its NaN-tagged values misread as a table / userdata) +-- floats read through their bits: LuaJIT's FFI can hand back a NaN with a payload its NaN-tagging misreads local function f32(bits: number): number if band(bits, 0x7F800000) == 0x7F800000 then if band(bits, 0x7FFFFF) ~= 0 then @@ -59,7 +55,6 @@ function Pixels.reverseBits(b: buffer, off: number, len: number) end -- ------------------------------------------------------------------------------------------------ predictors --- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched) function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean) for r = 0, rows - 1 do local base = off + r * rb @@ -95,7 +90,6 @@ function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, str end end --- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit) function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number) for r = 0, rows - 1 do local base = off + r * rb @@ -112,8 +106,7 @@ function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, strid end end --- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little --- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes. +-- the samples come out little endian whatever the file's byte order (libtiff fpAcc) function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) local wc = rb // bytes for r = 0, rows - 1 do @@ -130,7 +123,6 @@ function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, byt end end --- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff) function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) local wc = rb // bytes for r = 0, rows - 1 do @@ -152,7 +144,7 @@ local half = Bytes.half export type Params = { planes: { buffer }, - rb: number, -- bytes per row in each plane + rb: number, chunky: boolean, w: number, h: number, @@ -161,14 +153,13 @@ export type Params = { sfmt: number, -- 1 uint, 2 int, 3 float le: boolean, photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK - alpha: number, -- sample index of the alpha channel, -1 = none + alpha: number, assoc: boolean, -- premultiplied alpha (undone) cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block) - kind: string, -- the output pixel format + kind: string, out: buffer, } --- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them local function fast(P: Params): boolean if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then return false @@ -218,7 +209,6 @@ local function fast(P: Params): boolean return false end --- convert(P): every pixel into P.out in P.kind's layout function Pixels.convert(P: Params) if fast(P) then return @@ -229,7 +219,6 @@ function Pixels.convert(P: Params) local float = sfmt == 3 local signed = sfmt == 2 local cmapN = 2 ^ math.min(bps, 16) - -- raw sample s of pixel x in the row starting at byte ro of its plane local function raw(s: number, x: number, row: number): number local b, i if chunky then diff --git a/src/Rosetta/image/tiff/init.luau b/src/Rosetta/image/tiff/init.luau index b644082..b593bf1 100644 --- a/src/Rosetta/image/tiff/init.luau +++ b/src/Rosetta/image/tiff/init.luau @@ -1,15 +1,7 @@ --!strict --- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. --- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / --- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's --- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), --- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, --- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as --- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard --- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32). --- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none / --- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames. --- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG. +-- image/tiff: TIFF 6.0 (+ Adobe technote 3, BigTIFF). Supports: strips, tiles, planar 1 / 2, none / LZW (old-style too) +-- / Deflate (8, 32946) / PackBits / JPEG (7), predictors 2 / 3, int / float samples, CMYK (naive), fill order 2. Not +-- supported: old-style JPEG (6), CCITT (2, 3, 4), YCbCr, CIELab, JBIG. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -32,16 +24,16 @@ local Tiff = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8 - maxPixels: number?, -- per page (default 2^26) - maxPages: number?, -- pages decoded into img.frames (default 1024) - page: number?, -- decode only this page (1-based) - decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages + native: boolean?, -- default false: rgba8 + maxPixels: number?, -- per page, default 2^26 + maxPages: number?, -- default 1024 + page: number?, -- 1-based + decodeImage: ((buffer) -> (any, any))?, } export type EncodeOptions = { compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate" - predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true) - level: number?, -- deflate level 0..9 (default 6) + predictor: boolean?, -- default true + level: number?, -- 0..9, default 6 rowsPerStrip: number?, -- default: about 64 KB per strip } @@ -90,7 +82,6 @@ local function off(c: Ctx, at: number): number return if c.big then u64(c, at) else u32(c, at) end --- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many local function values(c: Ctx, e: Entry?, max: number?): { number }? if not e then return nil @@ -155,7 +146,6 @@ local function one(c: Ctx, e: Entry?, default: number): number return if v and v[1] then v[1] else default end --- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?) local esize = if c.big then 20 else 12 local hsize = if c.big then 8 else 2 @@ -203,7 +193,6 @@ local function bytesOf(c: Ctx, e: Entry?, max: number): buffer? return x end --- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?) if p < c.base or len < 0 or p + len > c.limit then -- a chunk past the end: keep what exists (truncated files) @@ -308,10 +297,10 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): if ch > h and not tiled then ch = h end - local pspp = if chunky then spp else 1 -- samples per pixel in one plane + local pspp = if chunky then spp else 1 local nplanes = if chunky then 1 else spp - local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane - local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row + local rb = math.ceil(w * pspp * bps / 8) + local crb = math.ceil(cw * pspp * bps / 8) if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then return nil, Err.new(Err.LIMIT, "decoded data over 1 GB") end @@ -382,7 +371,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp) end - -- into the plane local plane = planes[pl + 1] local x0b = math.floor(tx * cw * pspp * bps / 8) local cols = math.min(cw, w - tx * cw) @@ -402,7 +390,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): le = true -- fpAcc leaves the samples little endian end local colorType = PHOTOMETRIC[photo] - -- the output layout local kind = "rgba8" if opts and opts.native and comp ~= 7 then if photo == 3 or photo == 5 then @@ -506,7 +493,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): return img, nil end --- pages(r) -> the IFD tables of every page (and the context) | nil, Err local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < 8 then @@ -551,7 +537,6 @@ local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } return list, c, nil end --- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?) local list, c, err = pages(r, 1024) if not list or not c then @@ -617,7 +602,6 @@ function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. end -- ------------------------------------------------------------------------------------------------ encode --- layout per pixel format: samples, bits, sample format, photometric, extra samples local LAYOUT = { gray8 = { 1, 8, 1, 1 }, graya8 = { 2, 8, 1, 1 }, @@ -764,7 +748,6 @@ function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err? if not tags or not strips then return nil, err end - -- strip data first local soffs = {} for i, s in strips do if w:tell() % 2 == 1 then diff --git a/src/Rosetta/image/tim/init.luau b/src/Rosetta/image/tim/init.luau index 53a4344..7768e79 100644 --- a/src/Rosetta/image/tim/init.luau +++ b/src/Rosetta/image/tim/init.luau @@ -1,13 +1,7 @@ --!strict --- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation --- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken. --- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit --- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000 --- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when --- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }. --- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image --- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque --- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images. +-- image/tim: PlayStation TIM (magic 0x10), from Sony's PSX "File Formats" documentation. Supports: 4 / 8-bit CLUT, 15 / +-- 24-bit direct; colours are 1-5-5-5 STP-B-G-R, expanded (v << 3) | (v >> 2), 0x0000 transparent as on the hardware, +-- opaque black written as 0x8000. Not supported: mixed mode (pmode 4). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,14 +20,14 @@ local Tim = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - clut: number?, -- the CLUT row to use for indexed images (0-based, default 0) + clut: number?, -- 0-based, default 0 maxPixels: number?, -- default 2^26 } export type EncodeOptions = { bpp: number?, -- 4, 8, 16 (default) or 24 - x: number?, -- VRAM position of the image (default 0, 0) + x: number?, -- default 0, 0 y: number?, - clutX: number?, -- VRAM position of the CLUT (default 0, 480) + clutX: number?, -- default 0, 480 clutY: number?, } @@ -160,7 +154,6 @@ function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- rgba8 pixel -> PSX colour local function psx(v: number): number local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216 if a < 128 then diff --git a/src/Rosetta/image/vtf/init.luau b/src/Rosetta/image/vtf/init.luau index 8889df0..9ffd25b 100644 --- a/src/Rosetta/image/vtf/init.luau +++ b/src/Rosetta/image/vtf/init.luau @@ -1,16 +1,7 @@ --!strict --- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer --- Community "VTF (Valve Texture Format)" page; no code taken. --- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail --- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image --- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to --- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure --- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888, --- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through --- codecs/image/Texel), DXT1 (+ one-bit alpha), --- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips, --- texel, reflectivity, bumpScale }. --- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing. +-- image/vtf: Valve Texture Format 7.0 - 7.5 (Source engine), from the Valve Developer Community VTF page. Supports: the +-- high-resolution image, mips / faces / slices / frames, uncompressed texels, DXT1 / DXT3 / DXT5, ATI1N / ATI2N (35 / +-- 34 Alien Swarm, 38 / 37 Source 2013). Not supported: P8, Strata / Source 2 formats, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,17 +22,16 @@ local Vtf = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - mip: number?, -- mip level (0 = full size, default) - face: number?, -- cube map face (0-based, default 0) - slice: number?, -- volume slice (0-based, default 0) - frames: boolean?, -- decode every frame into img.frames (default true) - delay: number?, -- frame delay in seconds (default 0.1) + mip: number?, -- 0 = full size, default + face: number?, -- 0-based, default 0 + slice: number?, -- 0-based, default 0 + frames: boolean?, -- default true + delay: number?, -- seconds, default 0.1 maxPixels: number?, -- default 2^26 } -- ------------------------------------------------------------------------------------------------ constants local M = Texel.masked --- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind local FORMATS: { [number]: any } = { [0] = "rgba8", -- RGBA8888 [1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888 @@ -90,7 +80,6 @@ function Vtf.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- bytes of one w x h image in format f local function imageSize(f: any, w: number, h: number): number if type(f) == "string" and BCN[f] then return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0 @@ -162,7 +151,6 @@ function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0 dataAt = headerSize + lowSize end - -- the chain: mips smallest first; per mip: frames, faces, slices local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1) local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1) local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1) diff --git a/src/Rosetta/image/webp/Alpha.luau b/src/Rosetta/image/webp/Alpha.luau index 8fc1d98..7a08584 100644 --- a/src/Rosetta/image/webp/Alpha.luau +++ b/src/Rosetta/image/webp/Alpha.luau @@ -1,8 +1,7 @@ --!strict --!native --- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing), --- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical / --- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws. +-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2); unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt). local Vp8L = require("@rosetta/codecs/image/Vp8L") local readu8, writeu8 = buffer.readu8, buffer.writeu8 @@ -42,7 +41,6 @@ local function unfilter(a: buffer, w: number, h: number, filter: number) end end --- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any) if len <= 1 then return nil, "truncated: ALPH chunk" diff --git a/src/Rosetta/image/webp/Anim.luau b/src/Rosetta/image/webp/Anim.luau index 559202d..7a26529 100644 --- a/src/Rosetta/image/webp/Anim.luau +++ b/src/Rosetta/image/webp/Anim.luau @@ -1,10 +1,7 @@ --!strict --!native --- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c, --- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour --- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha --- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the --- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws. +-- image/webp/Anim: WebP animation compositing; coalesce() matches libwebp's WebPAnimDecoder (src/demux/anim_decode.c, +-- BSD-3-Clause, licenses/libwebp-LICENSE.txt): the background colour is ignored, as the spec recommends. local band, rshift = bit32.band, bit32.rshift local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill @@ -12,18 +9,18 @@ local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill local Anim = {} export type Frame = { - rgba: buffer, -- w * h rgba8 + rgba: buffer, x: number, y: number, w: number, h: number, - blend: boolean, -- alpha-blend over the canvas (false: overwrite) - disposeBg: boolean, -- after display, clear the rectangle to transparent - disposePrev: boolean?, -- after display, restore the canvas as it was before the frame (composite() only) + blend: boolean, + disposeBg: boolean, + disposePrev: boolean?, -- composite() only hasAlpha: boolean, } --- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult) +-- non-premultiplied 0xAABBGGRR, as libwebp BlendPixelNonPremult local function blendPixel(src: number, dst: number): number local sa = rshift(src, 24) if sa == 0 then @@ -40,7 +37,6 @@ local function blendPixel(src: number, dst: number): number end Anim.blendPixel = blendPixel --- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets) local function blendRow(cur: buffer, prev: buffer, o: number, n: number) for i = o, o + n - 1 do local s = readu32(cur, i * 4) @@ -50,7 +46,6 @@ local function blendRow(cur: buffer, prev: buffer, o: number, n: number) end end --- draw(canvas, cw, f): copy the frame rectangle into the canvas local function draw(canvas: buffer, cw: number, f: Frame) for j = 0, f.h - 1 do bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4) @@ -63,7 +58,6 @@ local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: nu end end --- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer } local size = cw * ch * 4 local out: { buffer } = {} @@ -122,9 +116,6 @@ function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer } return out end --- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or --- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle; --- previous: restore) function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer } local size = cw * ch * 4 local canvas = bcreate(size) diff --git a/src/Rosetta/image/webp/init.luau b/src/Rosetta/image/webp/init.luau index e9e84af..d69acdb 100644 --- a/src/Rosetta/image/webp/init.luau +++ b/src/Rosetta/image/webp/init.luau @@ -1,18 +1,7 @@ --!strict --- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6 --- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the --- container rules and the compositing follow libwebp's demux / WebPAnimDecoder. --- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw --- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the --- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or --- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif --- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and --- metadata). --- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does), --- alpha dithering / premultiplied output. --- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s --- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1). --- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images. +-- image/webp: WebP (RFC 9649); bitstreams ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +-- Supports: VP8 key frames (bit-exact with dwebp), VP8L, ALPH, VP8X, ANIM / ANMF, ICC / EXIF / XMP; writes VP8L. Not +-- supported: lossy encoding, VP8 scale fields (ignored, as dwebp), alpha dithering. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -36,21 +25,19 @@ local Webp = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26) - native: boolean?, -- a still lossy image without alpha decodes to its yuv420p planes (default false: rgba8) - upsampling: ("fancy" | "nearest")?, -- lossy chroma upsampling, default "fancy" (libwebp's default; "nearest" = - -- dwebp -nofancy) - coalesce: boolean?, -- animations: every frame is the full composited canvas (x = y = 0, dispose "none", - -- blend "source"), exactly what WebPAnimDecoder returns (default false: each frame's own rectangle) - frames: boolean?, -- animations: decode every frame (default true; false: only the first canvas) + maxPixels: number?, -- default 2^26 + native: boolean?, -- default false: rgba8 + upsampling: ("fancy" | "nearest")?, -- default "fancy" (libwebp's; "nearest" = dwebp -nofancy) + coalesce: boolean?, -- default false: each frame's own rectangle + frames: boolean?, -- default true } export type EncodeOptions = { - lossless: boolean?, -- must be true or nil (lossy encoding is not supported) - effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower) - exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed) - loops: number?, -- animations: play count (default img.loops; 0 = forever) - background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0) + lossless: boolean?, -- true or nil + effort: number?, -- 0..9, default 5 + exact: boolean?, -- default false + loops: number?, -- default img.loops; 0 = forever + background: { number }?, -- default meta.background or 0 } -- ------------------------------------------------------------------------------------------------ constants @@ -67,7 +54,6 @@ local function corrupt(msg: string, offset: number?): (nil, Err.Err) return nil, Err.new(Err.CORRUPT, msg, offset) end --- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT) local function fromMessage(msg: any, offset: number?): Err.Err if Err.is(msg) then return msg @@ -103,8 +89,7 @@ local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?) return out, nil end --- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size --- must fit the data (TRUNCATED) and bytes after it are ignored. +-- as libwebp: the RIFF size must fit the data and bytes after it are ignored local function readChunks(r: Bytes.Reader): ({ Chunk }?, any) local buf, base, limit = r.buf, r.base, r.limit if limit - base < 12 then @@ -131,7 +116,6 @@ local function readChunks(r: Bytes.Reader): ({ Chunk }?, any) return list, f end --- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?) local n = c.size - 12 return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) @@ -374,7 +358,6 @@ function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err. return img, nil end --- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err function Webp.info(r: Bytes.Reader): (any, Err.Err?) local chunks, cerr = readChunks(r) if not chunks then @@ -599,8 +582,6 @@ function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err? end -- ------------------------------------------------------------------------------------------------ extras --- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way --- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas) function Webp.coalesce(img: Types.Image): { buffer }? if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then return nil diff --git a/src/Rosetta/image/xbm/init.luau b/src/Rosetta/image/xbm/init.luau index 4709156..92c2fa9 100644 --- a/src/Rosetta/image/xbm/init.luau +++ b/src/Rosetta/image/xbm/init.luau @@ -1,8 +1,6 @@ --!strict --- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height --- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black, --- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below --- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image"). +-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant). Supports: _width / _height / _x_hot / _y_hot +-- defines, char / short arrays in hex, decimal or octal, LSB first, set bits black; writes X11 format. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -22,12 +20,12 @@ local Xbm = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - transparent: boolean?, -- clear bits transparent (default false: white) - maxPixels: number?, -- refuse larger images (default 2^26) + transparent: boolean?, -- default false: white + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _) - threshold: number?, -- luminance below this is black (default 128) + name: string?, -- default "image" + threshold: number?, -- default 128 } -- ------------------------------------------------------------------------------------------------ sniff @@ -120,7 +118,6 @@ function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") if name == "" or string.match(name, "^%d") then name = "_" .. name diff --git a/src/Rosetta/image/xpm/Names.luau b/src/Rosetta/image/xpm/Names.luau index 6291a2d..1d78110 100644 --- a/src/Rosetta/image/xpm/Names.luau +++ b/src/Rosetta/image/xpm/Names.luau @@ -1,7 +1,5 @@ --!strict --- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's --- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100. --- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil. +-- image/xpm/Names: CSS Color 4 named colours with X11's values where they differ, and grey0 .. grey100. local Names = {} local HEX: { [string]: number } = { @@ -37,7 +35,6 @@ local HEX: { [string]: number } = { violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32, } --- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces) function Names.lookup(name: string): number? local v = HEX[name] if v then diff --git a/src/Rosetta/image/xpm/init.luau b/src/Rosetta/image/xpm/init.luau index 4927dfa..9d193d5 100644 --- a/src/Rosetta/image/xpm/init.luau +++ b/src/Rosetta/image/xpm/init.luau @@ -1,10 +1,7 @@ --!strict --- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode: --- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 / --- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour --- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in --- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None, --- the fewest chars per pixel; opts.name (default "image"). +-- image/xpm: X PixMap (XPM 3 C source and XPM 2 plain; Arnaud Le Hors's "XPM Manual"). Supports: the values line and +-- hotspot, c / g / g4 / m / s keys (c preferred, then g, g4, m), #RGB .. #RRRRGGGGBBBB, None, colour names (unknown: +-- black); writes XPM 3 with hex colours. Not supported: the extensions section (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,10 +22,10 @@ local Xpm = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxPixels: number?, -- refuse larger images (default 2^26) + maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _) + name: string?, -- default "image" } -- the characters of pixel codes (printable ASCII without '"' and '\') @@ -44,7 +41,6 @@ function Xpm.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- colour value -> rgba8 u32, or nil for an unknown name local function colour(v: string): number? local l = string.lower(v) if l == "none" or l == "transparent" then @@ -69,7 +65,6 @@ local function colour(v: string): number? return if rgb then rgb + 0xFF000000 else nil end --- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2) local function strings(s: string): { string } local out = {} if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then @@ -214,7 +209,6 @@ function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") if name == "" or string.match(name, "^%d") then name = "_" .. name diff --git a/src/Rosetta/layered/aseprite/init.luau b/src/Rosetta/layered/aseprite/init.luau index bafac03..0a2e637 100644 --- a/src/Rosetta/layered/aseprite/init.luau +++ b/src/Rosetta/layered/aseprite/init.luau @@ -1,17 +1,7 @@ --!strict --- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA, --- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every --- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity, --- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to --- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old --- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and --- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree, --- delay }. --- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk --- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place, --- palette, tags. --- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour --- profiles (sRGB assumed). +-- layered/aseprite: Aseprite .ase / .aseprite (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA / grayscale / +-- indexed, frames, layer tree (groups, blend, opacity), raw / zlib / linked cels, palettes (0x2019, 0x0004 / 0x0011), +-- tags, user data. Not supported: tilemaps / tilesets (meta.skipped), slices, external files, colour profiles (sRGB). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,13 +20,12 @@ local Aseprite = { } export type DecodeOptions = { - maxPixels: number?, -- refuse sprites / cels larger than this (default 2^26) + maxPixels: number?, -- default 2^26 maxFrames: number?, -- default 65535 } export type EncodeOptions = { - depth: number?, -- 32 (RGBA), 16 (grayscale) or 8 (indexed, with layered.meta.palette); default meta.colorDepth if - -- the pixels fit it, else 32 - level: number?, -- zlib level for the cels (default 6) + depth: number?, -- 32, 16 or 8; default meta.colorDepth if the pixels fit, else 32 + level: number?, -- default 6 } -- ------------------------------------------------------------------------------------------------ constants @@ -67,7 +56,6 @@ local function str(r: Bytes.Reader): string return r:string(r:u16le()) end --- cel pixels (depth bytes per pixel) -> rgba8 local function toRGBA(src: buffer, so: number, n: number, depth: number, palette: buffer, transparent: number, background: boolean): buffer local out = buffer.create(n * 4) if depth == 32 then @@ -131,8 +119,8 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? local tags: { any } = {} local frames: { { cels: { [number]: any }, delay: number } } = {} local skipped = 0 - local lastUser: any = nil -- the object the next user data chunk belongs to - local tagUser = 0 -- tags waiting for their user data chunks + local lastUser: any = nil + local tagUser = 0 for fi = 1, nframes do local fstart = r.pos local fbytes = r:u32le() @@ -324,10 +312,9 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? r.pos = fstart + fbytes end local _ = ncolors - -- the layer tree of one frame local function build(fi: number): { Types.Layer } local root: { Types.Layer } = {} - local stack: { { Types.Layer } } = { root } -- stack[level + 1] = the children list at that level + local stack: { { Types.Layer } } = { root } for li, info in infos do local level = math.min(info.level, #stack - 1) local list = stack[level + 1] @@ -353,7 +340,6 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? l.opacity = 1 end table.insert(list, l) - -- deeper layers go into this group for k = #stack, level + 2, -1 do stack[k] = nil end @@ -392,9 +378,8 @@ function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered? end return root end - -- cel images (shared by linked cels) for _, f in frames do - for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration + for li, cel in pairs(f.cels) do if cel.raw then local info = infos[li] local img = Types.Image.new(cel.w, cel.h) @@ -470,7 +455,6 @@ function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer? end local meta: any = if type(layered.meta) == "table" then layered.meta else {} local level = opts and opts.level or 6 - -- frames: the layered frames, or one frame of the layers local frameList: { any } = if type(layered.frames) == "table" and #layered.frames > 0 then layered.frames else { { layers = layered.layers, delay = 0.1 } } local struct: { Node } = {} if not nodes(frameList[1].layers, 0, struct) then @@ -498,7 +482,6 @@ function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer? end perFrame[fi] = ns end - -- the colour depth: requested, or the source's when every pixel fits local depth = opts and opts.depth or meta.colorDepth or 32 local explicit = opts ~= nil and opts.depth ~= nil if depth ~= 32 and depth ~= 16 and depth ~= 8 then @@ -614,7 +597,6 @@ function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer? chunk(fw, 0x2020, c) return 1 end - -- where each (layer, frame) cel's image was first written: linked cels local firstAt: { [number]: { [any]: { frame: number, x: number, y: number, fill: number } } } = {} for fi, f in frameList do local fw = Bytes.writer(4096) diff --git a/src/Rosetta/layered/ora/init.luau b/src/Rosetta/layered/ora/init.luau index 4258578..4ec4903 100644 --- a/src/Rosetta/layered/ora/init.luau +++ b/src/Rosetta/layered/ora/init.luau @@ -1,13 +1,7 @@ --!strict --- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with --- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png. --- Decode: the stack tree (nested = groups: isolation="auto" is passThrough; name / src / x / y / --- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written), --- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it: --- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups) --- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to --- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the / / --- elements (ignored). +-- layered/ora: OpenRaster 0.0.6 (freedesktop.org; new code): a zip with a stored "mimetype" first, stack.xml, PNG +-- layers, mergedimage.png, Thumbnails/thumbnail.png. Supports: nested stacks (isolation="auto" = passThrough), layer +-- attributes, svg:* ops; PNGs via opts.decodeImage / encodeImage. Not supported: non-PNG sources, / . -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,14 +23,14 @@ local Ora = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the PNG layers (the api passes one) - composite: boolean?, -- decode mergedimage.png into meta.composite (default true) + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, + composite: boolean?, -- default true maxLayers: number?, -- default 10000 } export type EncodeOptions = { - encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the PNGs (the api passes one) - composite: Types.Image?, -- the merged image (default: the layers flattened with codecs/image/Blend) - thumbnail: boolean?, -- write Thumbnails/thumbnail.png (default true) + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, + composite: Types.Image?, -- default: the layers flattened + thumbnail: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants @@ -110,7 +104,7 @@ function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err end return img, nil end - -- a 's children, top first in the file -> bottom to top + -- stack.xml lists a 's children top first local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?) local out: { Types.Layer } = {} for _, ch in node.children do @@ -179,7 +173,6 @@ function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err end -- ------------------------------------------------------------------------------------------------ encode --- nearest-neighbour downscale to fit max x max local function thumbnail(img: Types.Image, max: number): Types.Image local w, h = img.width, img.height local s = math.min(1, max / math.max(w, h)) @@ -218,7 +211,6 @@ function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err end return data, nil end - -- layers bottom to top -> xml children top first local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?) local kids = {} for i = #layers, 1, -1 do diff --git a/src/Rosetta/layered/psd/Channels.luau b/src/Rosetta/layered/psd/Channels.luau index 035c17e..d9d6886 100644 --- a/src/Rosetta/layered/psd/Channels.luau +++ b/src/Rosetta/layered/psd/Channels.luau @@ -1,9 +1,7 @@ --!strict --!native --- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a --- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the --- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". --- Never throws: every read is range-checked first; failures return nil, "message". +-- layered/psd/Channels: PSD / PSB channel data (Photoshop File Formats Specification 2016, "Channel image data" / +-- "Image data section"): raw, PackBits RLE, ZIP, ZIP with prediction; colour modes to rgba8; PackBits rows. local Deflate = require("@rosetta/codecs/compress/Deflate") local PackBits = require("@rosetta/codecs/compress/PackBits") @@ -14,7 +12,6 @@ local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.wr local floor, min, max = math.floor, math.min, math.max local byteswap = bit32.byteswap --- rowBytes(w, depth) -> bytes per row of one channel function Channels.rowBytes(w: number, depth: number): number if depth == 1 then return (w + 7) // 8 @@ -22,7 +19,6 @@ function Channels.rowBytes(w: number, depth: number): number return w * (depth // 8) end --- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) local size = if psb then 4 else 2 if rows < 0 or p + rows * size > limit then @@ -40,7 +36,6 @@ function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, return counts, p end --- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?) for i = 0, rows - 1 do local c = counts[first + i] or 0 @@ -57,7 +52,6 @@ function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, return p, nil end --- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place local function unpredict(plane: buffer, w: number, h: number, depth: number) if depth == 8 then for y = 0, h - 1 do @@ -101,8 +95,6 @@ local function unpredict(plane: buffer, w: number, h: number, depth: number) end end --- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the --- 2-byte compression code and the data of one layer channel. function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?) local rb = Channels.rowBytes(w, depth) local plane = bcreate(rb * h) @@ -143,31 +135,29 @@ function Channels.channel(src: buffer, p: number, limit: number, w: number, h: n return plane, nil end --- sample8(plane, i, depth) -> sample i as 0..255 local function sample8(plane: buffer, i: number, depth: number): number if depth == 8 then return readu8(plane, i) elseif depth == 16 then return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5) elseif depth == 32 then - local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller + local f = readf32(plane, i * 4) if f ~= f then return 0 end return floor(max(0, min(1, f)) * 255 + 0.5) end - -- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black + -- 1-bit: 1 = black (whole-byte widths only; toRGBA reads bitmaps itself) return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255 end --- swap32(plane): big-endian f32 samples to native order, in place function Channels.swap32(plane: buffer) for i = 0, blen(plane) // 4 - 1 do writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) end end --- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white) +-- PSD Lab (0..255 each) to sRGB, the D50 white approximated by D65 local function srgb(c: number): number c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055 return floor(max(0, min(1, c)) * 255 + 0.5) @@ -188,8 +178,7 @@ local function lab(l8: number, a8: number, b8: number): (number, number, number) return srgb(r), srgb(g), srgb(bl) end --- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? } --- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab) +-- PSD colour modes: 0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer local n = w * h local out = bcreate(n * 4) @@ -197,7 +186,6 @@ function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: local alpha = planes.alpha local bitmapW = (w + 7) // 8 if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then - -- the common case, without a call per sample local g8 = if mode == 3 and c2 and blen(c2) >= n then c2 else c1 local b8 = if mode == 3 and c3 and blen(c3) >= n then c3 else c1 local a8 = if alpha and blen(alpha) >= n then alpha else nil @@ -250,7 +238,6 @@ function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: return out end --- gray8(plane, w, h, depth) -> 1 byte per pixel function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer local n = w * h local out = bcreate(n) @@ -277,7 +264,6 @@ function Channels.unmatte(rgba: buffer, n: number) end end --- matte(rgba, n) -> a copy matted with white (the writer's merged image) function Channels.matte(rgba: buffer, n: number): buffer local out = bcreate(n * 4) bcopy(out, 0, rgba, 0, n * 4) @@ -295,12 +281,10 @@ function Channels.matte(rgba: buffer, n: number): buffer end -- ------------------------------------------------------------------------------------------------ writer helpers --- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1) function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number local start = d local i = 0 while i < n do - -- a run of at least 3 equal bytes? local v = readu8(src, o + i) local run = 1 while i + run < n and run < 128 and readu8(src, o + i + run) == v do @@ -312,7 +296,6 @@ function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: num d += 2 i += run else - -- literals up to the next run of 3 local j = i while j < n and j - i < 128 do if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then @@ -330,7 +313,6 @@ function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: num return d - start end --- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each) function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer) local n = w * h local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) @@ -347,7 +329,6 @@ function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, return r, g, b, a end --- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer local cs = if psb then 4 else 2 local out = bcreate(h * cs + h * (w + w // 128 + 2)) diff --git a/src/Rosetta/layered/psd/init.luau b/src/Rosetta/layered/psd/init.luau index 919fe91..f65a879 100644 --- a/src/Rosetta/layered/psd/init.luau +++ b/src/Rosetta/layered/psd/init.luau @@ -1,15 +1,7 @@ --!strict --- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of --- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers --- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode, --- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / --- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image --- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. --- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend --- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, --- clipping, opacity / fill, hidden flags and Unicode names. --- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer --- effects, vector masks, colour management, 16 / 32-bit or non-RGB output. +-- layered/psd: Adobe Photoshop PSD / PSB (Photoshop File Formats Specification, 2016). Supports: every colour mode at +-- 1 / 8 / 16 / 32 bits, layers (RLE / ZIP channels, Lr16 / Lr32, iOpa, luni, masks, lsct groups), the merged image, +-- resources; encode: 8-bit RGB. Not supported: adjustment / type / smart-object contents, effects, vector masks. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,12 +22,12 @@ local Psd = { } export type DecodeOptions = { - layers: boolean?, -- read the layers (default true; false reads only the merged image) - maxPixels: number?, -- refuse documents / layers larger than this (default 2^26) + layers: boolean?, -- default true (false: the merged image only) + maxPixels: number?, -- default 2^26 maxLayers: number?, -- default 10000 } export type EncodeOptions = { - composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/image/Blend) + composite: Types.Image?, -- default: the layers flattened } -- ------------------------------------------------------------------------------------------------ constants @@ -101,7 +93,6 @@ local function utf16be(s: string): string return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", "")) end --- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?) local count = r:i16be() local absAlpha = count < 0 @@ -225,7 +216,7 @@ local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Er end end if ch.size < 2 then - continue -- an empty channel + continue end local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb) if not plane then @@ -251,7 +242,6 @@ local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Er return recs, absAlpha, nil end --- records (bottom to top) -> a layer tree local function tree(recs: { any }): { Types.Layer } local root: { Types.Layer } = {} local stack: { { Types.Layer } } = {} @@ -467,7 +457,7 @@ function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err planes[k] = plane end elseif comp == 2 or comp == 3 then - -- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream + -- Photoshop writes all channels in one zlib stream local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb) if not all then return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos) diff --git a/src/Rosetta/model/3ds/Build.luau b/src/Rosetta/model/3ds/Build.luau index d01a3ea..e685888 100644 --- a/src/Rosetta/model/3ds/Build.luau +++ b/src/Rosetta/model/3ds/Build.luau @@ -1,11 +1,9 @@ --!strict --- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world --- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * --- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix --- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key --- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's --- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position --- are averaged; group 0 is flat). Times are frame / fps. +-- model/3ds/Build: Read's chunk tables -> Types.Scene. +-- 3DS transforms: mesh vertices are in world space and the mesh matrix (0x4160) is the object's world transform; a +-- keyframer node is parent * T(pos) * R(rot) * S(scale) and draws its mesh at node * T(-pivot) * inverse(mesh matrix) +-- (a mirroring mesh matrix also flips x, as 3ds Max writes and assimp reads). Rotation keys are clockwise axis / angle +-- deltas from the previous key. Smoothing group 0 is flat. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Read = require("@rosetta/model/3ds/Read") @@ -20,7 +18,6 @@ local sqrt, abs = math.sqrt, math.abs export type Options = { normals: boolean?, flipV: boolean?, fps: number? } -- ------------------------------------------------------------------------------------------------ math --- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 local function meshMatrix(m: { number }?): { number } if not m then return Mat4.identity() @@ -34,7 +31,6 @@ local function det3(m: { number }): number end Build.det3 = det3 --- q(a) * q(b) local function qmul(a: { number }, b: { number }): { number } local ax, ay, az, aw = a[1], a[2], a[3], a[4] local bx, by, bz, bw = b[1], b[2], b[3], b[4] @@ -47,7 +43,7 @@ local function qmul(a: { number }, b: { number }): { number } end Build.qmul = qmul --- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +-- 3DS angles turn clockwise local function keyQuat(angle: number, x: number, y: number, z: number): { number } if x == 0 and y == 0 and z == 0 then return { 0, 0, 0, 1 } @@ -63,7 +59,7 @@ local function normalize(x: number, y: number, z: number): (number, number, numb return x / l, y / l, z / l, l end --- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +-- -Z looks from pos to target, world up +Z function Build.lookAt(p: { number }, t: { number }, roll: number): { number } local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) if l == 0 then @@ -73,7 +69,6 @@ function Build.lookAt(p: { number }, t: { number }, roll: number): { number } if abs(fz) > 0.999999 then ux, uy, uz = 0, 1, 0 end - -- right = forward x up, up = right x forward local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx local a = math.rad(roll) @@ -163,18 +158,14 @@ local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number end -- ------------------------------------------------------------------------------------------------ meshes --- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved --- by xf (world -> the node's local space) local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh local nv, nf = m.nv, m.nf local pos, faces = m.positions, m.faces - -- local positions local lp = table.create(nv * 3, 0) for v = 0, nv - 1 do local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z end - -- faces with valid corners, their materials local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) local valid = table.create(nf, false) for f = 0, nf - 1 do @@ -193,7 +184,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st end local smooth = m.smoothing local doNormals = opts.normals ~= false - -- face normals (area weighted) and the faces around each distinct position local fn = table.create(nf * 3, 0) local around: { [number]: { number } } = {} local group = table.create(nv, 0) @@ -248,7 +238,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st local nx, ny, nz = normalize(x, y, z) return nx, ny, nz end - -- primitives in the order their material first appears local order: { number } = {} local byMat: { [number]: { number } } = {} for f = 1, nf do @@ -321,7 +310,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st end -- ------------------------------------------------------------------------------------------------ tracks --- the value of a track at a frame (linear between keys, clamped at the ends) local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number } if not t or #t.frames == 0 then return default @@ -359,7 +347,6 @@ local function scaleKey(v: { number }): { number } return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] } end --- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys local function rotations(t: Read.Track): ({ number }, { { number } }) local frames, quats = {}, {} local acc: { number }? = nil @@ -396,7 +383,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene local fps = o.fps or 30 local scene = S.new() local matByName = materials(raw, scene) - -- objects by name local objByName: { [string]: Read.Object } = {} for _, obj in raw.objects do if objByName[obj.name] == nil then @@ -478,7 +464,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene local kf = raw.keyframer local kfNodes = if kf then kf.nodes else {} - -- targets of cameras / spotlights by name local targets: { [string]: Read.Node } = {} for _, n in kfNodes do if n.kind == "target" or n.kind == "lightTarget" then @@ -486,7 +471,7 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end end local placedObj: { [Read.Object]: boolean } = {} - local sceneOf: { [number]: number } = {} -- kf id -> scene node + local sceneOf: { [number]: number } = {} local channels: { Types.Channel } = {} local function channel(node: number, path: any, times: { number }, values: { number }, comps: number) for i = 1, #times do @@ -551,7 +536,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) end else - -- cameras and lights: position, target, roll local isCam = kind == "camera" local cam = if obj and isCam then obj.camera else nil local lit = if obj and not isCam then obj.light else nil @@ -581,7 +565,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end local ni = addNode(node, parent) sceneOf[id] = ni - -- every key time of the position, roll and target tracks local set: { [number]: boolean } = {} local times: { number } = {} for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do @@ -612,7 +595,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene end end end - -- objects the keyframer does not place (or files without one): at their own matrix / position for _, obj in raw.objects do if placedObj[obj] then continue diff --git a/src/Rosetta/model/3ds/Read.luau b/src/Rosetta/model/3ds/Read.luau index 648b4c5..31e53ea 100644 --- a/src/Rosetta/model/3ds/Read.luau +++ b/src/Rosetta/model/3ds/Read.luau @@ -1,10 +1,6 @@ --!strict --- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read --- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their --- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes --- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). --- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is --- clipped to the parent. Never throws on bad data: returns nil, message, offset. +-- model/3ds/Read: the 3DS chunk tree (u16 id, u32 size including the 6-byte header, little endian) -> plain tables. +-- Unknown chunks are skipped; a chunk past the end of the data is an error, one past its parent is clipped to it. local Read = {} local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 @@ -28,17 +24,14 @@ local C = { } Read.C = C --- material map chunks -> their name in Raw materials Read.MAPS = { [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", } --- keyframer node chunks -> kind local NODE_KINDS = { [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", [0xB006] = "lightTarget", [0xB007] = "spot", } --- track chunks -> (field, values per key) local TRACKS: { [number]: { any } } = { [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, @@ -59,7 +52,7 @@ export type Mesh = { nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags) faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers smoothing: buffer?, -- nf u32 - matrix: { number }?, -- 12 floats: the X, Y, Z axes and the origin (world space) + matrix: { number }?, -- 12 floats: X, Y, Z axes, origin (world space) } export type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? } export type Light = { @@ -82,13 +75,12 @@ export type Raw = { -- ------------------------------------------------------------------------------------------------ helpers type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw } --- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?) local b = ctx.b while p + 6 <= stop do local id, size = readu16(b, p), readu32(b, p + 2) if size < 6 then - return nil, nil -- padding or garbage after the last chunk + return nil, nil end local e = p + size if e > ctx.limit then @@ -103,7 +95,6 @@ local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, numb return nil, nil end --- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil local function cstring(b: buffer, p: number, stop: number): (string?, number) for q = p, stop - 1 do if readu8(b, q) == 0 then @@ -117,7 +108,7 @@ local function vec3(b: buffer, p: number): { number } return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } end --- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +-- colour chunks: the first float or byte colour (the gamma-corrected variants only when nothing else) local function color(ctx: Ctx, p: number, stop: number): { number }? local b = ctx.b local main: { number }?, lin: { number }? = nil, nil @@ -142,7 +133,6 @@ local function color(ctx: Ctx, p: number, stop: number): { number }? return main or lin end --- a percentage chunk list -> a fraction 0..1 local function percent(ctx: Ctx, p: number, stop: number): number? local b = ctx.b local v: number? = nil @@ -472,7 +462,6 @@ local function editor(ctx: Ctx, p: number, stop: number): (string?, number?) end) end --- parse(b, base, limit, opts) -> Raw | nil, message, offset function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?) if limit - base < 6 or readu16(b, base) ~= C.MAIN then return nil, "not a 3DS file (no 0x4D4D main chunk)", base @@ -483,7 +472,6 @@ function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, if size < 6 then return nil, "bad main chunk size", base end - -- a main chunk declared longer than the data: truncated if base + size > limit then return nil, "truncated: the main chunk runs past the end of the data", base end diff --git a/src/Rosetta/model/3ds/Write.luau b/src/Rosetta/model/3ds/Write.luau index 18ba0c7..38b9ee0 100644 --- a/src/Rosetta/model/3ds/Write.luau +++ b/src/Rosetta/model/3ds/Write.luau @@ -1,13 +1,6 @@ --!strict --- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world --- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's --- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 --- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with --- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and --- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in --- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key --- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. --- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +-- model/3ds/Write: Types.Scene -> 3DS. Objects split at 65535 vertices / faces; mirroring nodes written as 3ds Max does +-- (positive keyframer transform, mirror in the mesh matrix). local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Sampler = require("@rosetta/codecs/model/Sampler") @@ -108,7 +101,6 @@ local function unit(x: number, y: number, z: number): (number, number, number) return x / l, y / l, z / l end --- a quaternion -> the 3DS (clockwise angle, axis) local function axisAngle(q: { number }): (number, number, number, number) local x, y, z, w = q[1], q[2], q[3], q[4] local n = sqrt(x * x + y * y + z * z + w * w) @@ -128,7 +120,6 @@ local function conj(q: { number }): { number } return { -q[1], -q[2], -q[3], q[4] } end --- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE) local function sample(ch: Types.Channel, t: number): { number } local f = Sampler.channel(ch) if not f then @@ -191,7 +182,6 @@ local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [n if x.wire then leaf(w, C.MAT_WIRE, function() end) end - -- maps: the PBR texture refs first, then the other kinds model/3ds read local maps: { [string]: any } = {} local function fromRef(ref: Types.TextureRef?, saved: any): any if not ref or not files[ref.texture] then @@ -246,7 +236,6 @@ end -- ------------------------------------------------------------------------------------------------ meshes type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } } --- the mesh as 3DS parts (local space), or nil, message local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?) local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean return n == "TEXCOORD_0" or n == "NORMAL" @@ -260,7 +249,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, local tv, tc = if T then T.values else nil, if T then T.components else 0 local flipV = opts.flipV ~= false local corners = merged.corners - -- per face: material, smoothing group local nf = #corners // 3 local fmat, fsg = table.create(nf, 0), table.create(nf, 1) for _, part in merged.parts do @@ -272,7 +260,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, if savedOk then fsg[f] = saved[f - part.firstFace] elseif N then - -- flat when every corner normal is the face normal local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } @@ -398,7 +385,6 @@ local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: end -- ------------------------------------------------------------------------------------------------ cameras / lights --- the eye, target and roll of a node's world matrix (looking down -Z, Y up) local function aim(m: { number }, dist: number): ({ number }, { number }, number) local p = { m[13], m[14], m[15] } local fx, fy, fz = unit(-m[9], -m[10], -m[11]) @@ -406,7 +392,6 @@ local function aim(m: { number }, dist: number): ({ number }, { number }, number fx, fy, fz = 0, 0, -1 end local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } - -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis local q0 = Build.lookAt(p, t, 0) local m0 = Mat4.fromQuat(q0) local ux, uy, uz = unit(m[5], m[6], m[7]) @@ -490,11 +475,10 @@ local function writeTrack(w: W, id: number, frames: { number }, values: { number end type KfNode = { - chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1 + chunk: number, name: string, instance: string?, parent: number, -- kf index or -1 frames: { [string]: { number } }, values: { [string]: { number } }, } --- frames (rounded, strictly increasing) and the indices of the channel keys they keep local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number }) local IN = S.reader(ch.input) :: any local frames, keep = {}, {} @@ -558,7 +542,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) leaf(w, C.MESH_VERSION, function() w:u32le(3) end) - -- materials (unique names) local files = textureFiles(scene, o) local matNames: { [number]: string } = {} local used: { [string]: boolean } = {} @@ -578,7 +561,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) leaf(w, C.MASTER_SCALE, function() w:f32le(1) end) - -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) used = {} local firstNode: { [number]: number } = {} for _, i in order do @@ -608,7 +590,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) writeMesh(w, part, M, matNames) end end - -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors local KW: { [number]: { number } } = {} for _, i in order do local n = scene.nodes[i] @@ -645,7 +626,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } table.insert(kfs, kn) local idx = #kfs - -- animated root cameras / lights: position, target and roll at the key times local chs: any = if p == 0 then byNode[i] else nil local targetFrames, targetVals = { 0 }, tgt if chs and (chs.translation or chs.rotation) then @@ -707,7 +687,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end if onlyThis and idx then kfOf[i] = idx - -- the node's frame in the keyframer: the camera / light pose local kn = kfs[idx] local pos = kn.values.pos local m: { number } = W[i] @@ -724,7 +703,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) camLight(true) continue end - -- an object node (or a dummy) with the node's transform relative to its keyframer parent local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY local inv = Mat4.inverse(pkw) or Mat4.identity() local L = S.mul(inv, KW[i]) @@ -733,7 +711,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) local objName = if plist then plist[1].name else "$$$DUMMY" local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } - -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) local chs = byNode[i] if chs then local own = S.nodeMatrix(n) @@ -774,7 +751,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) camLight(false) end close(w, ed) - -- the keyframer local kf = open(w, C.KEYFRAMER) leaf(w, C.KF_HDR, function() w:u16le(5) diff --git a/src/Rosetta/model/3ds/init.luau b/src/Rosetta/model/3ds/init.luau index 8b4b9ed..115c896 100644 --- a/src/Rosetta/model/3ds/init.luau +++ b/src/Rosetta/model/3ds/init.luau @@ -1,25 +1,7 @@ --!strict --- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the --- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference --- for transforms and conventions; no code ported) and lib3ds (layouts only). --- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, --- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and --- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials --- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, --- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as --- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / --- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the --- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), --- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, --- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / --- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from --- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects --- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not --- applied), the keyframer frame range. --- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first --- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural --- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on --- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). +-- model/3ds: Autodesk 3D Studio chunked binary; layouts from the 3DS File Toolkit notes, assimp's importer (BSD-3, +-- reference only) and lib3ds. Supports: meshes, smoothing groups, Phong materials and maps, cameras, lights, keyframer. +-- Not supported: .prj / .mli, morph / hide tracks, TCB spline parameters, vertex colours / normals (3DS has none). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,16 +23,16 @@ local ThreeDs = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - normals: boolean?, -- compute NORMAL from the smoothing groups (default true; false keeps the file's vertices) - flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) - fps: number?, -- keyframer frames per second (default 30, 3ds Max's default) - maxVertices: number?, -- refuse more vertices in total (default 2^24) + normals: boolean?, -- default true + flipV: boolean?, -- default true + fps: number?, -- default 30 (3ds Max's default) + maxVertices: number?, -- default 2^24 } export type EncodeOptions = { - flipV: boolean?, -- default true (the inverse of decode) - fps: number?, -- seconds -> keyframer frames (default 30) - name: string?, -- the destination's file name (names textures that have no uri) - files: { [string]: any }?, -- receives the bytes of textures that have data but no uri + flipV: boolean?, -- default true + fps: number?, -- default 30 + name: string?, + files: { [string]: any }?, -- receives the bytes of textures with data but no uri } -- ------------------------------------------------------------------------------------------------ sniff @@ -74,7 +56,6 @@ function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, E if not raw then return nil, Err.from(msg, at) end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene = pcall(Build.scene, raw, opts :: any) if not ok then return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) diff --git a/src/Rosetta/model/3mf/Read.luau b/src/Rosetta/model/3mf/Read.luau index f9fc5b7..d8408a3 100644 --- a/src/Rosetta/model/3mf/Read.luau +++ b/src/Rosetta/model/3mf/Read.luau @@ -1,11 +1,6 @@ --!strict --- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first --- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items), --- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension --- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry, --- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit. --- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and --- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. +-- model/3mf/Read: a 3MF package -> Scene. The root model part comes from _rels/.rels (fallback: the first *.model under +-- 3D/); vertices are split where corners of one vertex carry different colours / texture coordinates. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") @@ -21,7 +16,6 @@ local MAX_DEPTH = 64 local localName = Xml.localName --- an attribute by local name (namespaced attributes such as p:path) local function attr(node: any, name: string): string? local a = node.attrs local v = a[name] @@ -44,7 +38,7 @@ local function int(s: string?): number? return nil end --- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1 +-- "#RRGGBB" / "#RRGGBBAA", sRGB local function hexColor(s: string?): { number }? if type(s) ~= "string" then return nil @@ -68,7 +62,7 @@ function Read.toLinear(c: number): number end local toLinear = Read.toLinear --- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid +-- "m00 m01 m02 m10 ... m32": 3MF's row-vector convention local function transform(s: string?): ({ number }?, boolean) if not s then return nil, true @@ -99,7 +93,6 @@ local function normPath(p: string): string return p end --- one model part parsed into its resources and build type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? } local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?) @@ -253,7 +246,6 @@ local function parseModel(text: string, path: string, opts: any): (Model?, Err.E return model, nil end --- the root model part's path local function rootPath(zip: any): string? local rels = zip:readString("_rels/.rels") if rels then @@ -313,7 +305,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) scene.meta.metadata = root.metadata scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required } - -- textures and materials (shared across model parts by part path + resource id) local texCache: { [string]: number } = {} local function texture(model: Model, id: number): number? local key = model.path .. "#" .. id @@ -359,7 +350,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) return m end - -- property of one corner -> (group key, material index?, kind, resource, index) local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number) local r = model.res[pid] if not r or p < 0 then @@ -429,7 +419,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) return "none", nil, "none", nil, 0 end - -- one Scene mesh per (part, object) with a mesh local meshCache: { [string]: number } = {} local function buildMesh(model: Model, o: any): number? local key = model.path .. "#" .. o.id @@ -532,7 +521,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) return #scene.meshes end - -- nodes: one per object instance (build items and components) local nodeCount = 0 local maxNodes = opts.maxNodes or 2 ^ 20 local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?) diff --git a/src/Rosetta/model/3mf/Write.luau b/src/Rosetta/model/3mf/Write.luau index 4f3af58..515cad1 100644 --- a/src/Rosetta/model/3mf/Write.luau +++ b/src/Rosetta/model/3mf/Write.luau @@ -1,10 +1,5 @@ --!strict --- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles, --- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the --- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours), --- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has --- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/). --- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. +-- model/3mf/Write: Scene -> a 3MF package; the node hierarchy is flattened into build items at world matrices. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") @@ -48,7 +43,6 @@ local function hex(r: number, g: number, b: number, a: number): string return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1))) end --- the triangle corner list of a primitive (0-based vertex indices) or nil local function triangles(prim: any): { number }? local pos = prim.attributes and prim.attributes.POSITION if type(pos) ~= "table" then @@ -128,10 +122,9 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) nextId += 1 return nextId end - local res: { string } = {} -- resource XML chunks, in definition order + local res: { string } = {} local files: { { name: string, data: buffer, mime: string } } = {} - -- unit local unitName: string, scale: number = "millimeter", 1 local mu: any = scene.meta and scene.meta.unit if type(o.unit) == "string" and UNITS[o.unit] then @@ -152,16 +145,14 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) end end - -- base materials: one group with every Scene material local baseId: number? = nil local nmat = #scene.materials - local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed + local defaultBase = nmat local needDefault = false if nmat > 0 then baseId = id() end - -- textures used as base colour textures local texRes: { [number]: number } = {} local function textureId(ti: number): number? if texRes[ti] ~= nil then @@ -186,7 +177,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) return rid end - -- objects local objectOf: { [number]: number } = {} local objChunks: { string } = {} for mi, mesh in scene.meshes do @@ -195,7 +185,7 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) local base = 0 local objPid: number?, objP: number? = nil, nil local anyNone = false - local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 } + local triList: { { number } } = {} for _, prim in mesh.primitives do local corners = triangles(prim) if not corners or #corners == 0 then @@ -210,7 +200,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) for v = 0, n - 1 do table.insert(verts, fmt('\t\t\t\t\t\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0))) end - -- properties: texture group, colour group, base material, none local pid, kind = -1, "none" local mat = prim.material and scene.materials[prim.material] local uv = prim.attributes.TEXCOORD_0 @@ -296,7 +285,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) table.insert(res, objChunks[#objChunks]) end - -- the base material group goes first (its id was taken first) if baseId then local parts = { fmt('\t\t\n', baseId) } for _, m in scene.materials do @@ -310,7 +298,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) table.insert(res, 1, table.concat(parts)) end - -- build items: every node with a mesh, at its world matrix local items: { string } = {} local seen: { [number]: boolean } = {} for _, pl in Types.Scene.flatten(scene) do @@ -342,7 +329,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) end end - -- metadata local meta: { string } = {} local md = scene.meta and scene.meta.metadata if type(md) == "table" then diff --git a/src/Rosetta/model/3mf/init.luau b/src/Rosetta/model/3mf/init.luau index 888670e..18cdfe2 100644 --- a/src/Rosetta/model/3mf/init.luau +++ b/src/Rosetta/model/3mf/init.luau @@ -1,21 +1,7 @@ --!strict --- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, --- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts --- (codecs/text/Xml). --- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from --- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices --- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata --- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours --- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to --- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it --- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first --- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices --- are split where a vertex's corners carry different colours / texture coordinates. --- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a --- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups, --- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit). --- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are --- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none). +-- model/3mf: 3D Manufacturing Format (core 1.3, materials extension 1.2, production extension 1.1 p:path). +-- Supports: meshes, components, build items, base materials, colour / texture / composite / multi groups. +-- Not supported: beam lattice, slices, displacement, volumetric and secure content, thumbnails, normals. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -37,13 +23,13 @@ local ThreeMf = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25) - maxNodes: number?, -- refuse more object instances (default 2^20) + maxVertices: number?, -- default 2^25 + maxNodes: number?, -- default 2^20 } export type EncodeOptions = { unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else - -- millimeter); positions are scaled through the build transforms when meta.unit differs - level: number?, -- deflate level for the XML parts (default 6; 0 stores them) + -- millimeter) + level: number?, -- default 6; 0 stores } -- ------------------------------------------------------------------------------------------------ sniff @@ -51,7 +37,6 @@ function ThreeMf.sniff(r: Bytes.Reader): number if r:peek(4) ~= "PK\3\4" then return 0 end - -- the central directory sits at the end: look for the model part's name there, then at the start local n = r:size() local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536)) if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then diff --git a/src/Rosetta/model/b3d/Read.luau b/src/Rosetta/model/b3d/Read.luau index 80b0534..2db075a 100644 --- a/src/Rosetta/model/b3d/Read.luau +++ b/src/Rosetta/model/b3d/Read.luau @@ -1,8 +1,5 @@ --!strict --- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are --- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes --- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/b3d/Read: the BB3D chunk tree (4-byte id, u32 little-endian size, no padding) -> Types.Scene. local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Chunks = require("@rosetta/containers/Chunks") @@ -26,8 +23,8 @@ type MeshRec = { mesh: number, node: number, count: number, joints: { { number } type Bone = { node: number, target: MeshRec?, list: { number } } type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } } --- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated --- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored +-- Blitz3D is left-handed Y up: z mirrored; quaternions are w x y z, conjugated (Blitz3D stores the inverse +-- rotation, as assimp reads them) then mirrored local function vec(r: Bytes.Reader): { number } local x, y, z = r:f32le(), r:f32le(), r:f32le() return { x, y, -z } @@ -54,7 +51,6 @@ local function fetcher(opts: Options?): (string) -> buffer? end end --- scene(r, opts) -> Scene | nil, message, kind function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?) local buf = src.buf local maxVertices = opts and opts.maxVertices or 2 ^ 24 @@ -77,7 +73,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, local scene = Types.Scene.new() local texs: { TexInfo } = {} local brushes: { Brush } = {} - local materialOf: { [number]: number } = {} -- brush index (0-based) -> material + local materialOf: { [number]: number } = {} local meshes: { MeshRec } = {} local bones: { Bone } = {} local nodeKeys: { [number]: Keys } = {} @@ -141,7 +137,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end - -- the material of brush id (0-based) | nil for -1 / out of range local function material(id: number): number? if id < 0 or id >= #brushes then return nil @@ -290,7 +285,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, fail(string.format("triangle %d: vertex index out of range", i)) return nil end - -- mirrored z: reverse the winding to keep the faces front-facing writeu32(idx, i * 12, a) writeu32(idx, i * 12 + 4, cc) writeu32(idx, i * 12 + 8, b) @@ -302,7 +296,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end if not attrs then - return nil -- a mesh without vertices: the node stays a pivot + return nil end if #mesh.primitives == 0 then table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" }) @@ -472,7 +466,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, end end end - local self: number? = nil -- the mesh node as a joint, for vertices no bone moves + local self: number? = nil local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) for v = 0, nv - 1 do local e = inf[v + 1] @@ -484,7 +478,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, buffer.writeu16(jb, v * 8, self :: number) buffer.writef32(wb, v * 16, 1) else - -- the 4 strongest, normalised local order = {} for k = 1, #e, 2 do table.insert(order, k) @@ -568,7 +561,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, brushes = #brushes, frames = if anim then anim.frames else nil, fps = if anim then anim.fps else nil, - handedness = "left", -- converted: z mirrored, winding reversed + handedness = "left", } return scene, nil, nil end diff --git a/src/Rosetta/model/b3d/init.luau b/src/Rosetta/model/b3d/init.luau index e208d12..308453d 100644 --- a/src/Rosetta/model/b3d/init.luau +++ b/src/Rosetta/model/b3d/init.luau @@ -1,21 +1,7 @@ --!strict --- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description --- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer. --- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler, --- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes -> --- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is --- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree --- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) / --- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the --- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights --- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the --- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps, --- default 60) -> one animation of LINEAR channels at frame / fps seconds. --- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding --- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their --- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }. --- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the --- extras; texture coordinate sets of 3 / 4 components keep their first two. +-- model/b3d: Blitz3D .b3d (BB3D chunks, version 1; blitzbasic.com "b3dfile_specs.txt", checked against assimp). +-- Supports: TEXS, BRUS, NODE / MESH / VRTS / TRIS, BONE skins, KEYS + ANIM; left-handed, so z is mirrored. +-- Not supported: writing; several VRTS chunks in one MESH (the first is used); 3 / 4 component texture coordinates. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -35,10 +21,10 @@ local B3d = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths) - files: { [string]: any }?, -- or: the files by name + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, maxVertices: number?, -- default 2^24 - maxDepth: number?, -- node nesting (default 256) + maxDepth: number?, -- default 256 } -- ------------------------------------------------------------------------------------------------ sniff @@ -54,7 +40,6 @@ function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if r:peek(4) ~= "BB3D" then return nil, Err.new(Err.CORRUPT, "no BB3D chunk") end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, r, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) diff --git a/src/Rosetta/model/bsp/Brush.luau b/src/Rosetta/model/bsp/Brush.luau index 83fa807..f745199 100644 --- a/src/Rosetta/model/bsp/Brush.luau +++ b/src/Rosetta/model/bsp/Brush.luau @@ -1,13 +1,7 @@ --!strict --- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex --- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture --- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the --- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake / --- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the --- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from --- opts.resolve("textures/.wal") when available, else texture coordinates stay in texels: extras.bsp.texels). --- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken. --- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls. +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the +-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture +-- size. local Types = require("@rosetta/Types") local Pixels = require("@rosetta/codecs/image/Pixels") @@ -20,7 +14,7 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32 export type Lump = { at: number, size: number } export type Options = { palette: buffer?, - wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size) + wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size) maxPixels: number?, maxVertices: number?, } @@ -32,7 +26,6 @@ local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- miptex lump (Quake / Half-Life) -> textures local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?) local out: { Tex } = {} if l.size < 4 then @@ -80,9 +73,6 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer return out, nil end --- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message --- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes, --- models, miptex (q1 / hl) function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) local q2 = variant == "q2" local maxPixels = opts and opts.maxPixels or 2 ^ 24 @@ -95,9 +85,8 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian if nF > (opts and opts.maxVertices or 2 ^ 24) then return nil, "limit: too many faces" end - -- textures local texs: { Tex } = {} - local texOf: { number } = {} -- texinfo -> texture index (1-based) + local texOf: { number } = {} if q2 then local byName: { [string]: number } = {} for i = 0, nTI - 1 do @@ -126,7 +115,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0 end end - -- faces of each model local scene = Scene.new() scene.meta.up = "z" local faceModel: { number } = {} @@ -160,7 +148,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian skipped += 1 continue end - -- the polygon local poly: { number } = {} local ok = true for k = 0, numEdges - 1 do @@ -189,7 +176,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian if side ~= 0 then nx, ny, nz = -nx, -ny, -nz end - -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored) + -- Newell's normal of the polygon as stored local n = #poly // 3 local ax, ay, az = 0, 0, 0 for k = 0, n - 1 do @@ -239,7 +226,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian end end end - -- textures, materials for i, t in texs do local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } table.insert(scene.textures, tex) @@ -250,7 +236,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any table.insert(scene.materials, mat) end - -- meshes and nodes local root: Types.Node = { name = "bsp", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 diff --git a/src/Rosetta/model/bsp/Quake3.luau b/src/Rosetta/model/bsp/Quake3.luau index 3284055..de8c1a4 100644 --- a/src/Rosetta/model/bsp/Quake3.luau +++ b/src/Rosetta/model/bsp/Quake3.luau @@ -1,11 +1,6 @@ --!strict --- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a --- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches --- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap --- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1 --- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as --- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped. --- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken. +-- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. local Types = require("@rosetta/Types") local Quake3 = {} @@ -17,19 +12,18 @@ local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.wri export type Lump = { at: number, size: number } export type Options = { patchLevel: number?, maxVertices: number? } -type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices) +type Batch = { shader: number, lightmap: number, verts: { number } } -- indices into the vertex lump, or -1 - k for patch vertices local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- decode(b, base, lumps, opts) -> Scene | nil, message function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?) local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152 local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) local maxV = opts and opts.maxVertices or 2 ^ 24 - -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids + -- patch vertices: 12 floats + 4 colour bytes each local extra: { number } = {} local function vertex(i: number): { number } local o = base + VX.at + i * 44 @@ -92,7 +86,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: local L = level for py = 0, (h - 1) // 2 - 1 do for px = 0, (w - 1) // 2 - 1 do - -- the 3x3 control points of this sub-patch local ctrl: { { number } } = {} for j = 0, 2 do for i = 0, 2 do @@ -127,7 +120,7 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: for gx = 0, L - 1 do local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] - -- counter-clockwise for Quake's clockwise-front control grids + -- Quake's control grids are clockwise-front for _, v in { a, d, c2, c2, d, e } do table.insert(tris, v) end @@ -166,7 +159,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: end local scene = Scene.new() scene.meta.up = "z" - -- shaders, lightmaps for i = 0, nT - 1 do local name = cstr(b, base + T.at + i * 72, 64) table.insert(scene.textures, { name = name, uri = name }) diff --git a/src/Rosetta/model/bsp/init.luau b/src/Rosetta/model/bsp/init.luau index ff2dcda..02ae8d9 100644 --- a/src/Rosetta/model/bsp/init.luau +++ b/src/Rosetta/model/bsp/init.luau @@ -1,11 +1,6 @@ --!strict --- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38) --- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a --- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III --- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as --- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not --- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey. --- Quake II .wal sizes come from opts.resolve("textures/.wal") / opts.files. Units are map units, z up. +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW +-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. -- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. -- ------------------------------------------------------------------------------------------------ requires @@ -28,10 +23,10 @@ local Bsp = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - palette: (buffer | string)?, -- Quake 1: the 768-byte palette + palette: (buffer | string)?, -- Quake 1: 768 bytes resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - patchLevel: number?, -- Quake III patch subdivisions (default 4) + patchLevel: number?, -- default 4 maxPixels: number?, -- default 2^24 maxVertices: number?, -- default 2^24 } @@ -55,7 +50,6 @@ function Bsp.sniff(r: Bytes.Reader): number return if v == 38 or v == 46 or v == 47 then 1 else 0.3 end if v == 29 or v == 30 then - -- no magic: check that the lump directory fits the file local size = r:remaining() for i = 0, 14 do local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) @@ -69,7 +63,6 @@ function Bsp.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the entities text -> { { key = value } } local function entities(text: string): { { [string]: string } } local out: { { [string]: string } } = {} for block in string.gmatch(text, "%b{}") do diff --git a/src/Rosetta/model/dae/Math.luau b/src/Rosetta/model/dae/Math.luau index cabfc97..4da24c2 100644 --- a/src/Rosetta/model/dae/Math.luau +++ b/src/Rosetta/model/dae/Math.luau @@ -1,6 +1,5 @@ --!strict --- model/dae/Math: the Collada-specific transform elements (, ); everything else (matrices, --- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +-- model/dae/Math: the Collada transform elements and ; matrices are flat column-major arrays of 16. local Mat4 = require("@rosetta/codecs/model/Mat4") local DaeMath = {} @@ -18,7 +17,7 @@ local function norm(a: { number }): { number } return { a[1] / l, a[2] / l, a[3] / l } end --- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest +-- : an object at eye whose -Z looks at interest function DaeMath.lookat(v: { number }): { number } local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) }) @@ -27,14 +26,14 @@ function DaeMath.lookat(v: { number }): { number } return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 } end --- skew(angle, rotation axis, translation axis) (RenderMan's skew) +-- (RenderMan's skew) function DaeMath.skew(v: { number }): { number } local a = rad(v[1] or 0) local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) local s = math.tan(a) local m = Mat4.identity() - -- M = I + s * t * r^T (column-major: m[col*4 + row]) + -- M = I + s * t * r^T for row = 0, 2 do for col = 0, 2 do m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1] diff --git a/src/Rosetta/model/dae/Read.luau b/src/Rosetta/model/dae/Read.luau index 8cf63f9..b7e5eae 100644 --- a/src/Rosetta/model/dae/Read.luau +++ b/src/Rosetta/model/dae/Read.luau @@ -1,13 +1,5 @@ --!strict --- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / --- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile --- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, --- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix / --- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin --- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as --- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform --- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS --- channels; one animation per animation clip, else one for the file). +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") @@ -100,8 +92,8 @@ type Ctx = { meshes: { [string]: number }, skins: { [string]: number }, posIndex: { [any]: { number } }, - nodeOf: { [string]: { number } }, -- collada node id -> scene nodes - info: { [number]: any }, -- scene node -> { el, xf, sid, cid } + nodeOf: { [string]: { number } }, + info: { [number]: any }, pendingSkins: { any }, skipped: { [string]: number }, err: string?, @@ -113,7 +105,6 @@ local function skip(C: Ctx, what: string) end -- ------------------------------------------------------------------------------------------------ sources --- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params) local function readSource(C: Ctx, el: any): any local cached = C.sources[el] if cached ~= nil then @@ -279,7 +270,6 @@ local function image(C: Ctx, id: string): any return img end --- the effect's newparams by sid (this level and the profile's) local function newparams(effect: any, profile: any, technique: any): { [string]: any } local out = {} for _, scope in { effect, profile, technique } do @@ -295,7 +285,6 @@ local function newparams(effect: any, profile: any, technique: any): { [string]: return out end --- texture(effect params, sampler sid) -> scene texture index local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number? local np = params[samplerSid] local imageId: string? = nil @@ -364,7 +353,6 @@ local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): n return idx end --- one colour-or-texture parameter of a common technique local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any) if not el then return nil, nil @@ -474,7 +462,7 @@ local function material(C: Ctx, id: string, uvsets: { [string]: number }): numbe if type(shininess) == "number" then mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) end - -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance) + -- Collada 1.4.1 section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then local mode = attr(transparentEl, "opaque") or "A_ONE" local tv = if type(transparency) == "number" then transparency else 1 @@ -531,7 +519,6 @@ end -- ------------------------------------------------------------------------------------------------ geometry type Input = { semantic: string, source: any, offset: number, set: number } --- the inputs of a primitive element (VERTEX expanded into the inputs) local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) local out: { Input } = {} local stride = 0 @@ -563,7 +550,6 @@ local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) return out, math.max(stride, 1) end --- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string) local p: { number } = {} local faces: { number } = {} @@ -670,7 +656,6 @@ local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } } --- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs) local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built? local ins, stride = inputs(C, prim, verticesEl) local p, faces, starts, mode = corners(C, prim, kind, stride) @@ -688,7 +673,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil skip(C, "primitives without positions") return nil end - -- attribute names local named: { { input: Input, name: string, comps: number } } = {} local texSets: { number } = {} local texInputs: { Input } = {} @@ -725,10 +709,9 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) }) end end - -- de-index local np = #p local keyOf: { [any]: number } = {} - local tuples: { number } = {} -- the first p index of each output vertex's tuple + local tuples: { number } = {} local corner = table.create(#starts) :: { number } local count = 0 for ci, s in starts do @@ -803,7 +786,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil if allTri then mode = "triangles" elseif C.triangulate then - -- fan triangulation local tri: { number } = {} local at = 0 for _, f in faces do @@ -832,7 +814,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } end --- geometry(el) -> the built primitives (cached per geometry element) local function geometry(C: Ctx, el: any): { Built }? local cached = C.posIndex[el] if cached then @@ -863,7 +844,6 @@ local function geometry(C: Ctx, el: any): { Built }? return out end --- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } }) local syms: { [string]: string } = {} local sets: { [string]: { [string]: number } } = {} @@ -894,7 +874,6 @@ local function copyAccessor(a: Types.Accessor): Types.Accessor return Scene.accessor(b, a.type, a.components, a.count) end --- mesh(geometry element, instance element, skin?) -> scene mesh index local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?) local syms, sets = bindings(inst) local parts = { key } @@ -915,7 +894,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { for _, b in built do local prim = b.prim if bindShape then - -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared) local attrs = table.clone(prim.attributes) local pos = copyAccessor(attrs.POSITION) for v = 0, pos.count - 1 do @@ -961,7 +939,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { end end if target then - -- texcoord semantic -> TEXCOORD_n index among this primitive's sets local uv: { [string]: number } = {} for sem, set in (sym and sets[sym]) or {} do uv[sem] = (table.find(b.texSets, set) or 1) - 1 @@ -976,7 +953,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { return idx, built end --- morph controller -> mesh with targets (deltas) local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number? local base = C.ids[urlId(attr(morph, "source")) or ""] if not base or lname(base) ~= "geometry" then @@ -1082,7 +1058,6 @@ local function camera(C: Ctx, el: any): number? return #C.scene.cameras end --- light(el) -> light index, or nil and the ambient colour local function light(C: Ctx, el: any): (number?, { number }?) local tc = child(el, "technique_common") if not tc then @@ -1124,7 +1099,6 @@ end -- ------------------------------------------------------------------------------------------------ nodes local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } --- the matrix of one transform element's values local function xfMatrix(kind: string, v: { number }): { number } if kind == "matrix" then return Mat4.fromRows(v) @@ -1182,7 +1156,7 @@ local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number return idx end --- the instances of a node: the first of each kind on the node itself, the rest on child nodes +-- extra instances of a node go on child nodes local function instances(C: Ctx, el: any, node: Types.Node, idx: number) local function slot(kind: string, name: string?): (Types.Node, number) local n: any = node @@ -1322,7 +1296,7 @@ visitNode = function(C: Ctx, el: any): number? end -- ------------------------------------------------------------------------------------------------ skins --- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere +-- joints: by sid below the skeleton roots, else by sid / id / name anywhere local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number? local nodes = C.scene.nodes local function search(i: number, depth: number): number? @@ -1410,7 +1384,7 @@ local function resolveSkins(C: Ctx) local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } if ps.bind then local sk: any = skin - sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals + sk.extras = { dae = { bindShapeMatrix = ps.bind } } end if ibm and ibm.comps == 16 and ibm.count >= #names then local b = buffer.create(#names * 64) @@ -1432,7 +1406,6 @@ local function resolveSkins(C: Ctx) cache[key] = si end C.scene.nodes[ps.node].skin = si - -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh) local mesh = C.scene.meshes[ps.mesh] if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then continue @@ -1457,7 +1430,7 @@ local function resolveSkins(C: Ctx) local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} local wdata = wSrc and wSrc.data or {} - local per: { { number } } = {} -- position index -> { j1, w1, j2, w2, ... } strongest 4 + local per: { { number } } = {} local at = 0 for pi, c in vcount do local list = {} @@ -1555,9 +1528,9 @@ local function sample(c: Curve, t: number): { number } return a end --- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element +-- "id/sid/sid.member" or "id/sid(i)(j)" local function target(C: Ctx, s: string): ({ number }?, any, number?) - -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" + -- ids may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" local id, sids = match(s, "^([^/]*)/(.*)$") if not id then return nil, nil, nil @@ -1607,7 +1580,6 @@ local function target(C: Ctx, s: string): ({ number }?, any, number?) return nodes, xf, member end --- the channels of one (recursively) -> curves grouped by node local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number) if depth > 64 then return @@ -1697,7 +1669,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) local prev: { number }? = nil for i, t in times do - -- this time's values of each animated element local xf = {} for k, x in info.xf do xf[k] = { kind = x.kind, values = table.clone(x.values) } @@ -1738,7 +1709,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } :: Types.Channel) table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) - -- the node is now TRS-driven local node = C.scene.nodes[ni] if node.matrix then setTransform(node, node.matrix) @@ -1821,12 +1791,11 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err? } for _, el in Xml.descendants(root) do local id = el.attrs.id - -- duplicate ids: the first one, unless it is empty (some exporters write before the real one) + -- duplicate ids: the first, unless empty (some exporters write before the real one) if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then C.ids[id] = el end end - -- asset: up axis, unit local asset = child(root, "asset") local up = asset and child(asset, "up_axis") local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP" @@ -1834,7 +1803,6 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err? local unit = asset and child(asset, "unit") local meter = unit and attr(unit, "meter") scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1 - -- the instanced visual scene (else the first one) local vsId: string? = nil local sceneEl = child(root, "scene") local ivs = sceneEl and child(sceneEl, "instance_visual_scene") diff --git a/src/Rosetta/model/dae/Write.luau b/src/Rosetta/model/dae/Write.luau index c317f42..b777d96 100644 --- a/src/Rosetta/model/dae/Write.luau +++ b/src/Rosetta/model/dae/Write.luau @@ -1,9 +1,6 @@ --!strict --- model/dae/Write: Scene -> Collada 1.4.1 text. One per mesh primitive (triangles, lines or polylist; strips --- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n --- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its --- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major ; cameras; --- lights. Not written: skins, morph targets, animations. +-- model/dae/Write: Scene -> Collada 1.4.1 text; strips and fans unrolled, points skipped, nodes as row-major . +-- Not written: skins, morph targets, animations. local Types = require("@rosetta/Types") local Xml = require("@rosetta/codecs/text/Xml") local Base64 = require("@rosetta/core/Base64") @@ -38,7 +35,6 @@ local function nameAttr(s: string?): string return if s then ' name="' .. esc(s) .. '"' else "" end --- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?) local n = prim.attributes.POSITION.count local idx: { number } = {} @@ -160,7 +156,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? local meta: { [string]: any } = scene.meta or {} local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP" w(format('rosetta1970-01-01T00:00:00Z1970-01-01T00:00:00Z%s\n', f(meta.unit or 1), up)) - -- images local imageId: { [number]: string } = {} if #scene.textures > 0 then w("\n") @@ -184,12 +179,11 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- effects + materials if #scene.materials > 0 then w("\n") for i, mat in scene.materials do local ph: any = mat.extras and mat.extras.phong or {} - local params: { [any]: any } = {} -- the newparam strings, and their sids as seen-keys + local params: { [any]: any } = {} local function texParam(ref: Types.TextureRef?): (string?, number?) if not ref or not imageId[ref.texture] then return nil, nil @@ -236,7 +230,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- geometries: one per primitive local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {} w("\n") for mi, mesh in scene.meshes do @@ -289,7 +282,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end end w("\n") - -- cameras / lights if #scene.cameras > 0 then w("\n") for i, cam in scene.cameras do @@ -316,7 +308,6 @@ function Write.build(scene: Types.Scene, opts: any?): string? end w("\n") end - -- the node tree w('\n') local seen: { [number]: boolean } = {} local function node(i: number, depth: number) diff --git a/src/Rosetta/model/dae/init.luau b/src/Rosetta/model/dae/init.luau index a3fb3de..289bfa8 100644 --- a/src/Rosetta/model/dae/init.luau +++ b/src/Rosetta/model/dae/init.luau @@ -1,26 +1,8 @@ --!strict --- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its --- manifest.xml and the images). New code. --- Reads: geometry ( triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input --- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"), --- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess / --- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump -> --- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5), --- kept encoded (opts.resolve / opts.files, embedded hex , data: URIs), the instanced visual scene (matrix / --- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances --- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under --- or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph --- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect; --- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as --- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE --- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided, --- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z" --- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left --- origin (opts.flipV = false keeps Collada's). --- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae. --- Not supported: / geometry, polygon holes (: the outer loop only), Bezier / Hermite curves --- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than --- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations. +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry, +-- common-profile materials, images, the visual scene, skin / morph controllers, cameras, lights, transform animations. +-- Not supported: / , polygon holes (), Bezier / Hermite curves (sampled linearly), non-transform +-- animation targets, physics / kinematics / non-COMMON FX profiles; writing skins, morphs and animations. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -43,17 +25,17 @@ local Dae = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths - files: { [string]: any }?, -- or: the files by uri / base name - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention) - maxVertices: number?, -- refuse more output vertices / array values (default 2^25) + resolve: ((uri: string) -> any)?, -- image files (buffer or string) + files: { [string]: any }?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + maxVertices: number?, -- default 2^25 } export type EncodeOptions = { - files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri) - name: string?, -- the destination's file name (names the image files) - flipV: boolean?, -- default true (the inverse of decode) - format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension + files: { [string]: any }?, -- receives the texture images (else data: URIs or their uri) + name: string?, + flipV: boolean?, -- default true + format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images) } -- ------------------------------------------------------------------------------------------------ sniff @@ -107,7 +89,7 @@ local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch end end --- the main .dae of a .zae: manifest.xml's , else the first .dae entry +-- a .zae's main .dae: manifest.xml's , else the first .dae entry local function zae(r: Bytes.Reader): (any, string?, Err.Err?) local zip, err = Zip.open(r) if not zip then @@ -174,7 +156,6 @@ function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err return nil, Err.new(Err.ARG, "needs a Scene") end if opts and opts.format == "zae" then - -- a zip: manifest.xml, the .dae and its images local files = {} local o = table.clone(opts) o.files = files diff --git a/src/Rosetta/model/fbx/Ascii.luau b/src/Rosetta/model/fbx/Ascii.luau index 9975cc8..7f6f62f 100644 --- a/src/Rosetta/model/fbx/Ascii.luau +++ b/src/Rosetta/model/fbx/Ascii.luau @@ -1,7 +1,6 @@ --!strict --- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';' --- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary --- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws. +-- model/fbx/Ascii: the ASCII FBX 7.x node tree ("Name: value, ... { children }", ';' comments, "*N { a: ... }" arrays, +-- " in strings); integers longer than 15 digits stay strings so ids are exact. local Base64 = require("@rosetta/core/Base64") local Ascii = {} @@ -15,7 +14,6 @@ local function isNameStart(c: number): boolean return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 end --- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?) local maxBytes = opts and opts.maxBytes or 2 ^ 30 local n = #text @@ -36,7 +34,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n end end - -- at i: a name followed by ':'? -> name, the index after ':' local function nameAt(): (string?, number) local c = sbyte(text, i) if not c or not isNameStart(c) then @@ -61,7 +58,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n return nil, i end - -- the values of one node (after the ':'), up to a new name, '{' or '}' local function values(): ({ any }?, string?) local props: { any } = {} while true do @@ -163,7 +159,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n return e end end - -- "*N { a: v, v, ... }" -> an Array local p1 = props[1] if #props == 1 and type(p1) == "table" and p1.star then local a = node.children[1] @@ -213,7 +208,6 @@ local function fmt(v: number): string return string.format("%.17g", v) end --- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes) function Ascii.write(root: any, version: number?): string local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) } local function node(nd: any, indent: string) @@ -236,7 +230,7 @@ function Ascii.write(root: any, version: number?): string elseif tv == "table" and v.array then arr = v elseif tv == "buffer" then - -- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them + -- raw bytes (Video Content): base64 split into lines as the FBX SDK writes them local b64 = Base64.encode(v) local chunks = {} for k = 1, #b64, 2048 do diff --git a/src/Rosetta/model/fbx/Binary.luau b/src/Rosetta/model/fbx/Binary.luau index 34bb2c5..90a2cb4 100644 --- a/src/Rosetta/model/fbx/Binary.luau +++ b/src/Rosetta/model/fbx/Binary.luau @@ -1,10 +1,7 @@ --!strict --!native --- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit --- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's --- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array --- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become --- the string "L" so ids stay exact. Never throws: errors are returned (nil, message, offset). +-- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by +-- Blender's io_scene_fbx and assimp's FBXBinaryTokenizer. Scalar L values past 2^53 become "L" so ids stay exact. local Deflate = require("@rosetta/codecs/compress/Deflate") local Binary = {} @@ -21,7 +18,7 @@ local MAX_DEPTH = 128 local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16 local writef64 = buffer.writef64 --- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>" +-- signed 64-bit: a number when |v| < 2^53, else "L<16 hex digits>" local function i64(b: buffer, p: number, asString: boolean): any local lo, hi = readu32(b, p), readu32(b, p + 4) if hi >= 0x80000000 then @@ -40,7 +37,6 @@ Binary.i64 = i64 local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } --- the elements of a raw array (n elements of type t at p) as f64s local function toF64(t: string, src: buffer, p: number, n: number): buffer local out = buffer.create(n * 8) if t == "d" then @@ -66,7 +62,6 @@ local function toF64(t: string, src: buffer, p: number, n: number): buffer return out end --- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?) local maxBytes = opts and opts.maxBytes or 2 ^ 30 if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then @@ -158,7 +153,6 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: return out, p end - -- one node record at p: node | false (the null record), next offset | nil, message, offset local function node(p: number, stop: number, depth: number): (any, any, number?) if p + head > stop then return nil, "truncated node record", p @@ -230,10 +224,8 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: end -- ------------------------------------------------------------------------------------------------ writer --- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit --- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint --- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their --- type (compressed with zlib when longer than 32 elements, unless compress = false). +-- default version 7400 (32-bit records; 7500+ writes 64-bit); node.types = "ILDS..." gives one type character per +-- property; arrays over 32 elements are zlib-compressed export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } local function sizeHint(n: WNode): number diff --git a/src/Rosetta/model/fbx/Read.luau b/src/Rosetta/model/fbx/Read.luau index b18510d..110b110 100644 --- a/src/Rosetta/model/fbx/Read.luau +++ b/src/Rosetta/model/fbx/Read.luau @@ -1,15 +1,6 @@ --!strict --- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections -> --- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric --- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in --- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one --- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the --- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file --- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind --- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's --- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or --- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node --- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults. +-- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice, +-- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") @@ -50,7 +41,7 @@ local function isArray(v: any): boolean return type(v) == "table" and v.array == true end --- the array under n. (or inline numbers: old ASCII files) +-- old ASCII files have inline numbers local function array(n: Node?, name: string): Array? local c = child(n, name) if not c then @@ -87,7 +78,7 @@ local function at(a: Array, i: number): number return buffer.readf64(a.data, i * 8) end --- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) local function objectName(s: any): string if type(s) ~= "string" then return "" @@ -104,7 +95,7 @@ local function objectName(s: any): string end Read.objectName = objectName --- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } } +-- Properties70: P: name, type, label, flags, values... local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } } local out = into or {} local p70 = child(n, "Properties70") @@ -155,7 +146,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local maxVertices = opts and opts.maxVertices or 2 ^ 25 local scene = Types.Scene.new() - -- property templates (Definitions/ObjectType/PropertyTemplate) by object class + -- Definitions/ObjectType/PropertyTemplate local templates: { [string]: { [string]: { any } } } = {} local defs = child(root, "Definitions") if defs then @@ -169,7 +160,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end - -- objects local objects: { [any]: Obj } = {} local order: { Obj } = {} local objs = child(root, "Objects") @@ -187,7 +177,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end - -- connections: children (sources) of each parent, parents of each child, in file order local kids: { [any]: { Conn } } = {} local parents: { [any]: { Conn } } = {} local conns = child(root, "Connections") @@ -236,7 +225,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ return out end - -- global settings local gs = properties(child(root, "GlobalSettings")) local upAxis = pnum(gs, "UpAxis", 1) local unitScale = pnum(gs, "UnitScaleFactor", 1) @@ -280,7 +268,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ return p end end - -- ASCII: base64 strings (possibly split into several) + -- ASCII: base64, possibly split into several strings local parts = {} for _, p in c.props do if type(p) == "string" then @@ -384,7 +372,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ if opacity < 1 then m.alphaMode = "blend" end - -- 3ds Max Physical / PBR materials local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] if pbr then local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|" @@ -504,7 +491,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ nd.scale = s end nd.extras = { fbx = { type = o.sub, id = o.id } } - -- parent local parentModel: Obj? = nil for _, t2 in targets(o.id, "Model") do parentModel = t2.obj @@ -517,7 +503,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.insert(scene.roots, ni) end end - -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed + -- break parent cycles: cut children already placed do local placed: { [number]: boolean } = {} local function visit(i: number) @@ -537,13 +523,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end for i in scene.nodes do if not placed[i] then - -- part of a parent cycle: make it a root table.insert(scene.roots, i) visit(i) end end end - -- world matrices (rest pose) local worldM: { [number]: Mat4.M4 } = {} local function world(i: number, parent: Mat4.M4) worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) @@ -559,7 +543,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ -- ------------------------------------------------------------------------------------------ meshes local corners = 0 - -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?) local skin = sources(geo.id, "Deformer", "Skin")[1] if not skin then @@ -645,7 +628,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end local meshCache: { [string]: number } = {} - local shapeChannels: { [number]: { Obj } } = {} -- mesh index -> blend shape channel objects (for weights curves) + local shapeChannels: { [number]: { Obj } } = {} local nodeSkin: { [number]: number } = {} local skinCache: { [any]: number } = {} @@ -662,7 +645,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ if corners > maxVertices or ncp > maxVertices then return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") end - -- polygons: corner -> control point, polygon of each corner, polygon starts local cp = table.create(nc, 0) local polyOf = table.create(nc, 0) local starts: { number } = { 0 } @@ -688,7 +670,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ np += 1 starts[np + 1] = nc end - -- layer elements type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number } local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem } local out: { Elem } = {} @@ -711,7 +692,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end) return out end - -- the data element of a corner (c 0-based), or -1 local function lookup(e: Elem, c: number): number local m = e.mapping local i @@ -742,7 +722,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] - -- the normals index name varies ("NormalsIndex" / "NormalIndex") + -- "NormalsIndex" / "NormalIndex" for _, e in normals do if not e.index then local c = nil @@ -758,7 +738,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- polygons by material slot local groups: { [number]: { number } } = {} local slots: { number } = {} for p = 0, np - 1 do @@ -785,7 +764,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.sort(slots) local perCp, skin = skinOf(geo) local shapes = shapesOf(geo) - local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G) + local N3: Mat4.M4? = nil -- inverse transpose of G if G then local inv = Mat4.inverse(G) if inv then @@ -1004,12 +983,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ for _, o in models do local ni = nodeOf[o.id] local nd = scene.nodes[ni] - -- materials of the model, in connection order local mats: { number } = {} for _, m in sources(o.id, "Material") do table.insert(mats, material(m)) end - -- geometric transform (not inherited: baked into the mesh) + -- geometric transform: not inherited, baked into the mesh local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) @@ -1047,7 +1025,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis + -- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis for _, a in sources(o.id, "NodeAttribute") do local p = a.props if a.sub == "Camera" then @@ -1120,7 +1098,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ times[k + 1] = at(kt, k) / TICKS values[k + 1] = at(kv, k) end - -- per-key attribute flags (expanded through KeyAttrRefCount) + -- expanded through KeyAttrRefCount local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") local flags = table.create(n, 4) local slopes: { { number } } = {} @@ -1223,11 +1201,10 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ for _, stack in order do if stack.class == "AnimationStack" then local anim: Types.Animation = { name = stack.name, channels = {} } - -- model id -> { T/R/S -> { axis -> curve } , defaults } type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } } local tracks: { [any]: Track } = {} local trackOrder: { any } = {} - local morph: { [any]: Curve } = {} -- blend shape channel id -> DeformPercent curve + local morph: { [any]: Curve } = {} local layers = sources(stack.id, "AnimationLayer") for _, layer in layers do for _, cn in sources(layer.id, "AnimationCurveNode") do @@ -1328,7 +1305,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end end - -- morph target weights: every node whose mesh has an animated blend shape channel if next(morph) then for ni, nd in scene.nodes do local chans = nd.mesh and shapeChannels[nd.mesh] diff --git a/src/Rosetta/model/fbx/Write.luau b/src/Rosetta/model/fbx/Write.luau index e48613a..7311530 100644 --- a/src/Rosetta/model/fbx/Write.luau +++ b/src/Rosetta/model/fbx/Write.luau @@ -1,11 +1,6 @@ --!strict --- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types --- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f). --- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one --- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals --- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material; --- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets -> --- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. +-- model/fbx/Write: Scene -> an FBX 7.4 node tree. Property types follow what Blender's and the FBX SDK's readers check +-- (ids L, ints I, doubles D, KTime L, arrays d / i / l / f); rotations as Euler XYZ degrees. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") @@ -28,7 +23,7 @@ local function arr(t: string, list: { number }): any end return { array = true, type = t, count = n, data = d } end --- P: name, type, label, flags, values (vt: one type character per value) +-- P: name, type, label, flags, values local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } end @@ -64,7 +59,6 @@ local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> return Types.Scene.reader(acc) end --- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based) local function faces(prim: Types.Primitive): { { number } }? local pos = prim.attributes.POSITION if not pos then @@ -235,7 +229,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) link(m.baseColorTexture, "DiffuseColor") link(m.normalTexture, "NormalMap") link(m.emissiveTexture, "EmissiveColor") - -- the other textures the FBX material had (specular, metalness, ... maps), under their property names local linked = { [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, [m.normalTexture and m.normalTexture.texture or -1] = true, @@ -260,7 +253,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) -- ------------------------------------------------------------------------------------------ models local modelIds: { [number]: number } = {} local skip: { [number]: boolean } = {} - local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there) + local attrHost: { [number]: number } = {} local parentOf: { [number]: number } = {} for i, nd in nodes do for _, c in nd.children or {} do @@ -283,7 +276,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) attrHost[i] = p end end - -- world matrices (rest pose) for clusters and the bind pose local worldM: { [number]: Mat4.M4 } = {} local visiting: { [number]: boolean } = {} local function world(i: number): Mat4.M4 @@ -390,7 +382,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local euler = Mat4.eulerXYZ(r) local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null" - -- an orientation child folded into this node gives it its attribute local folded: number? = nil for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) if host == i then @@ -430,9 +421,9 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) -- ------------------------------------------------------------------------------------------ geometry local geoIds: { [number]: number } = {} - local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot + local geoSlots: { [number]: { number } } = {} local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {} - local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation) + local geoChannels: any = {} local geoCount: { [number]: number } = {} local function geometry(mi: number): number? if geoIds[mi] then @@ -625,7 +616,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) geoSlots[mi] = if anyMat then slots else {} geoVerts[mi] = layout geoCount[mi] = offset - -- morph targets local prims = mesh.primitives local ntargets = 0 for _, l in layout do @@ -717,7 +707,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) OO(pm, mid) end end - -- skin: one Skin per (geometry, skin) local skin = nd.skin and scene.skins[nd.skin] local key = tostring(gid) .. ":" .. tostring(nd.skin) if skin and not skinned[key] then @@ -728,7 +717,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local meshWorld = world(i) pose(mid, meshWorld) local ibm = accessorReader(skin.inverseBindMatrices) - -- per joint: control points and weights local perJoint: { { idx: { number }, w: { number } } } = {} for j in skin.joints do perJoint[j] = { idx = {}, w = {} } @@ -878,7 +866,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) end table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) else - -- weights: one DeformPercent curve per blend shape channel of the node's mesh local nd = nodes[ch.node] local gc: any = geoChannels local chans = nd.mesh and gc[nd.mesh] diff --git a/src/Rosetta/model/fbx/Xform.luau b/src/Rosetta/model/fbx/Xform.luau index abe251b..b7376ff 100644 --- a/src/Rosetta/model/fbx/Xform.luau +++ b/src/Rosetta/model/fbx/Xform.luau @@ -1,7 +1,6 @@ --!strict --- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model --- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The --- matrix / quaternion arithmetic is codecs/model/Mat4. +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): +-- local = T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1 local Mat4 = require("@rosetta/codecs/model/Mat4") local Xform = {} @@ -12,7 +11,6 @@ function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4 return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") end --- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers export type Props = { T: { number }, R: { number }, S: { number }, Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number }, @@ -28,7 +26,6 @@ function Xform.localMatrix(p: Props): Mat4.M4 end m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) if not isZero(p.Rpost) then - -- the inverse of a rotation is its transpose m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) end m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) diff --git a/src/Rosetta/model/fbx/init.luau b/src/Rosetta/model/fbx/init.luau index db1f96d..b266afd 100644 --- a/src/Rosetta/model/fbx/init.luau +++ b/src/Rosetta/model/fbx/init.luau @@ -1,24 +1,7 @@ --!strict --- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays --- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and --- assimp's FBX importer, and the FBX SDK's documentation of the transform model. --- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl --- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms --- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals, --- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference --- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR --- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins --- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets --- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and --- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for --- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated). --- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives --- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields), --- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster + --- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler --- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK). --- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered --- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear). +-- model/fbx: Autodesk FBX 7.x binary and ASCII, from Blender's io_scene_fbx, assimp and the FBX SDK transform docs. +-- Supports: Model transforms, meshes, Phong / Physical materials, textures, skins, blend shapes, animation, cameras. +-- Not supported: FBX 6.x and older, NURBS / patches / lines, constraints, animation layer blending. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,21 +24,21 @@ local Fbx = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention) - sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only) - resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths) - files: { [string]: any }?, -- or: the files by name - maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30) - maxVertices: number?, -- refuse more polygon corners (default 2^25) + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + sampleRate: number?, -- samples per second (default: the keys only) + resolve: ((uri: string) -> any)?, -- external texture files + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of arrays + maxVertices: number?, -- default 2^25 polygon corners } export type EncodeOptions = { - ascii: boolean?, -- write ASCII FBX (default binary) + ascii: boolean?, -- default binary version: number?, -- 7400 (default) or 7500 (64-bit records) - flipV: boolean?, -- default true (the inverse of decode) - embedTextures: boolean?, -- embed texture.data as Video content (default true) - compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger) - name: string?, -- the destination's file name (names textures without a uri) + flipV: boolean?, -- default true + embedTextures: boolean?, -- default true + compress: boolean?, -- arrays over 32 elements (default true) + name: string?, creator: string?, } @@ -100,8 +83,6 @@ end local toErr = Err.from --- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. --- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?) if r:peek(21) == MAGIC then local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts) @@ -129,7 +110,6 @@ function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if not root then return nil, version end - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene)) diff --git a/src/Rosetta/model/gltf/Pack.luau b/src/Rosetta/model/gltf/Pack.luau index 470d384..998eb9b 100644 --- a/src/Rosetta/model/gltf/Pack.luau +++ b/src/Rosetta/model/gltf/Pack.luau @@ -1,15 +1,11 @@ --!strict --!native --- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene --- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range --- first (offsets, strides and counts against the buffer lengths); nothing here throws. +-- model/gltf/Pack: the byte loops of glTF accessors (gather strided elements, scatter, sparse substitution); callers +-- check every range first. glTF pads matrix columns to 4 bytes. local Pack = {} local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 --- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is --- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem = --- cols * colBytes bytes each) function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then @@ -30,7 +26,6 @@ function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: end end --- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled) function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) if cols == 1 or colBytes == colStride then if stride == elem then @@ -51,8 +46,6 @@ function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: end end --- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element --- idx[k] of dst becomes value k (values packed, elem bytes each) function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean for k = 0, n - 1 do local i diff --git a/src/Rosetta/model/gltf/Read.luau b/src/Rosetta/model/gltf/Read.luau index 7159685..f3d1176 100644 --- a/src/Rosetta/model/gltf/Read.luau +++ b/src/Rosetta/model/gltf/Read.luau @@ -1,10 +1,6 @@ --!strict --- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type --- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution, --- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the --- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the --- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets, --- scenes. glTF extras and unhandled extensions are kept in .extras.gltf = { extras, extensions }. +-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. glTF extras and unhandled extensions are +-- kept in .extras.gltf = { extras, extensions }. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") @@ -27,7 +23,7 @@ local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } local WRAP: { [number]: "clamp" | "mirror" | "repeat" } = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } --- the extensions this reader understands (everything else that is required -> UNSUPPORTED) +-- the extensions this reader understands (any other required one -> UNSUPPORTED) local KNOWN = { KHR_lights_punctual = true, KHR_mesh_quantization = true, @@ -83,7 +79,6 @@ local function numbers(v: any, n: number): { number }? return table.move(v, 1, n, 1, {} :: { number }) end --- extras.gltf: the JSON extras and the extensions not turned into Scene fields local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }? local extras = obj.extras local ext: { [string]: any }? = nil @@ -102,8 +97,7 @@ local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any return { gltf = { extras = extras, extensions = ext } } end --- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value --- by value: normalized integers <-> floats, ints widened or narrowed) +-- a Draco attribute as its glTF accessor's type: bytes as they are when the layouts agree, else value by value local DRACO_HANDLED = { KHR_draco_mesh_compression = true } local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } local DRACO_SAME: { [string]: string } = { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } @@ -171,7 +165,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end end local scene = Types.Scene.new() - -- buffers local buffers: { buffer } = {} local total = 0 for i, b in arr(doc.buffers) do @@ -228,7 +221,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end views[i] = { buf = b, offset = off, length = len, stride = stride } end - -- accessors local accessors: { Types.Accessor } = {} for i, a in arr(doc.accessors) do local label = "accessor " .. (i - 1) @@ -295,7 +287,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc if io + n * isz > iv.length or vo + n * elem > vv.length then return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") end - -- sparse values are tightly packed (matrices: padded columns, rare enough to repack first) + -- sparse values are tightly packed (matrices: padded columns) local vals, valOff = vv.buf, vv.offset + vo if cols > 1 and colBytes ~= colStride then vals = buffer.create(n * elem) @@ -317,7 +309,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc local k = int(v) return if k then accessors[k + 1] else nil end - -- images (kept encoded), samplers, textures local images: { Img } = {} for i, im in arr(doc.images) do if type(im) ~= "table" then @@ -403,7 +394,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.textures, tex) end - -- materials local function texRef(info: any): Types.TextureRef? if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then return nil @@ -415,7 +405,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end return r end - -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + -- a textureInfo: a table with an index, under a key ending in Texture local function convertExt(v: any): any if type(v) ~= "table" then return v @@ -465,7 +455,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc mat.extras = kept table.insert(scene.materials, mat) end - -- meshes for i, m in arr(doc.meshes) do if type(m) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) @@ -534,7 +523,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then return nil, Err.new(Err.CORRUPT, "bad indices accessor") end - -- indices must reference existing vertices local get = Types.Scene.reader(ind :: Types.Accessor) :: any for q = 0, ind.count - 1 do if get(q, 0) >= count then @@ -563,7 +551,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.meshes, mesh) end - -- cameras, lights for _, c in arr(doc.cameras) do if type(c) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad camera") @@ -591,7 +578,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc }) end end - -- nodes local nodes = arr(doc.nodes) for i, n in nodes do if type(n) ~= "table" then @@ -647,7 +633,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc p = parent[p] end end - -- skins for _, s in arr(doc.skins) do if type(s) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad skin") @@ -661,7 +646,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil }) end - -- animations for _, a in arr(doc.animations) do if type(a) ~= "table" then return nil, Err.new(Err.CORRUPT, "bad animation") @@ -698,7 +682,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end table.insert(scene.animations, anim) end - -- scenes local scenes = arr(doc.scenes) local list = {} for _, s in scenes do @@ -720,7 +703,6 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end end end - -- root extensions other than the lights, asset info local rootExt = nil if type(doc.extensions) == "table" then for k, v in doc.extensions do diff --git a/src/Rosetta/model/gltf/Write.luau b/src/Rosetta/model/gltf/Write.luau index dc91e3d..9ff38ff 100644 --- a/src/Rosetta/model/gltf/Write.luau +++ b/src/Rosetta/model/gltf/Write.luau @@ -1,11 +1,6 @@ --!strict --- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex --- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires), --- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither), --- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats, --- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their --- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first --- for concave faces). +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. Vertex attributes 4-byte aligned per +-- element, matrix columns padded, f64 / i32 data converted (glTF has neither), POSITION and animation input min / max. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -89,7 +84,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return #views - 1 end - -- accessor(acc, usage, attribute?) -> the glTF index (0-based) local function accessor(acc: Types.Accessor, usage: string, attribute: string?): number local known = accIndex[acc] if known then @@ -148,7 +142,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return 0 end if attribute == "POSITION" or usage == "input" then - -- min / max of the raw component values local raw = Types.Scene.accessor(a.data, if a.type == "unorm8" then "u8" elseif a.type == "unorm16" then "u16" elseif a.type == "snorm8" then "i8" elseif a.type == "snorm16" then "i16" else a.type, comps, a.count) local get = Types.Scene.reader(raw) :: (number, number) -> number local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) @@ -173,7 +166,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) return index end - -- extras.gltf -> extras / extensions fields of a glTF object local function restore(g: any, extras: any) local saved = type(extras) == "table" and extras.gltf if type(saved) ~= "table" then @@ -193,7 +185,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end end - -- images, samplers, textures local images: { any } = {} local imageOut: { { data: buffer, mime: string?, name: string } } = {} local imageIndex: { [any]: number } = {} @@ -212,7 +203,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) im.bufferView = view(data, buffer.len(data), nil, nil) im.mimeType = mime or "image/png" elseif embedImages then - im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI / a file name by the caller im.mimeType = mime table.insert(imageOut, { data = data, mime = mime, name = im.uri }) else @@ -316,7 +307,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end return out end - -- materials local materials: { any } = {} for i, m in scene.materials or {} do if type(m) ~= "table" then @@ -370,7 +360,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, m.extras) table.insert(materials, g) end - -- meshes local meshes: { any } = {} for i, mesh in scene.meshes or {} do if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then @@ -396,7 +385,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) local mode = p.mode or "triangles" local indices = p.indices if mode == "polygons" then - -- fan-triangulate local faces = p.faces local getf = faces and Types.Scene.reader(faces) local n = if indices then indices.count else p.attributes.POSITION.count @@ -459,7 +447,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, mesh.extras) table.insert(meshes, g) end - -- cameras, lights local cameras: { any } = {} for _, c in scene.cameras or {} do local g = object() @@ -498,7 +485,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end table.insert(lights, g) end - -- nodes local nodes: { any } = {} local nodeCount = #(scene.nodes or {}) for i, n in scene.nodes or {} do @@ -549,7 +535,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, n.extras) table.insert(nodes, g) end - -- skins local skins: { any } = {} for _, s in scene.skins or {} do local g = object() @@ -570,7 +555,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) end table.insert(skins, g) end - -- animations local animations: { any } = {} for _, a in scene.animations or {} do local g = object() @@ -602,7 +586,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) if failure then return nil, failure end - -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + -- scenes: the original list (meta.gltf.scenes), else the roots local meta: { [string]: any } = if type(scene.meta) == "table" then scene.meta else {} local mg = type(meta.gltf) == "table" and meta.gltf or {} local scenes = {} @@ -619,7 +603,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) restore(g, s.extras) table.insert(scenes, g) end - -- the current roots replace the default scene's list local which = mg.scene or 1 if scenes[which] then scenes[which].nodes = {} @@ -646,7 +629,6 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) asset.extras = mg.asset.extras end doc.asset = asset - -- root extensions kept from the source (variants, ...), the lights if type(mg.extensions) == "table" then doc.extensions = object() for k, v in mg.extensions do diff --git a/src/Rosetta/model/gltf/init.luau b/src/Rosetta/model/gltf/init.luau index 9d094ed..3a592da 100644 --- a/src/Rosetta/model/gltf/init.luau +++ b/src/Rosetta/model/gltf/init.luau @@ -1,22 +1,7 @@ --!strict --- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and --- binary (.glb). New code. --- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every --- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR --- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior, --- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept, --- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime, --- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins, --- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a --- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer. --- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths). --- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes .bin and the --- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension). --- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the --- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back --- uncompressed (the extension is dropped). --- Not supported: meshopt (EXT_meshopt_compression) compressed primitives (UNSUPPORTED), KHR_animation_pointer channels --- (skipped and counted in the animation's extras). +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), .gltf JSON and .glb. Supports: the core spec, KHR_materials_*, +-- KHR_texture_transform, KHR_lights_punctual, KHR_mesh_quantization, KHR_draco_mesh_compression (written uncompressed). +-- Not supported: EXT_meshopt_compression (UNSUPPORTED), KHR_animation_pointer channels (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -40,16 +25,16 @@ local Gltf = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string); the api sets it for paths - files: { [string]: any }?, -- or: the files by uri - maxBytes: number?, -- refuse buffers / accessors over this many bytes in total (default 2^30) + resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string) + files: { [string]: any }?, + maxBytes: number?, -- default 2^30 bytes of buffers / accessors } export type EncodeOptions = { - binary: boolean?, -- write GLB (default: when opts.format is "glb") - format: string?, -- "glb" -> binary (set by the api from the destination's extension) - external: boolean?, -- .gltf: write the buffer and images as files into opts.files (default false: data: URIs) + binary: boolean?, -- default: when opts.format is "glb" + format: string?, + external: boolean?, -- default false: data: URIs files: { [string]: any }?, -- receives .bin and images with external = true - name: string?, -- the destination's file name (names the external files) + name: string?, embedImages: boolean?, -- default true (false with external = true) } @@ -98,7 +83,6 @@ local function fetcher(opts: DecodeOptions?): Read.Fetch end end --- the JSON text and BIN chunk of a GLB local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?) local magic, version, length = r:u32le(), r:u32le(), r:u32le() if r.err then @@ -178,7 +162,6 @@ function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Er local doc = out.doc local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" local files = opts and opts.files - -- images: data: URIs, or files if doc.images then local n = 0 for _, im in doc.images do diff --git a/src/Rosetta/model/iqm/Read.luau b/src/Rosetta/model/iqm/Read.luau index df004ac..0ce4fe9 100644 --- a/src/Rosetta/model/iqm/Read.luau +++ b/src/Rosetta/model/iqm/Read.luau @@ -1,7 +1,5 @@ --!strict --- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and --- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). --- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. Every header range is checked before it is read. local Types = require("@rosetta/Types") local Rig = require("@rosetta/codecs/model/Rig") @@ -32,7 +30,7 @@ local function half(h: number): number return s * (1 + m / 1024) * 2 ^ (e - 15) end --- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +-- normalized: integer formats scaled to 0..1 / -1..1 local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } local out = table.create(n) :: { number } local size = Read.SIZES[format] @@ -77,7 +75,6 @@ end local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } --- scene(b, base, limit, opts) -> Scene | nil, message function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) local size = limit - base local H: { [string]: number } = {} @@ -128,7 +125,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: if H.num_comment > 0 then source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") end - -- vertex arrays (the whole model's vertices; meshes are ranges of them) local nv = H.num_vertexes type Array = { kind: string, name: string, format: number, comps: number, offset: number } local arrays: { Array } = {} @@ -147,7 +143,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) end - -- joints -> nodes + a skin local jointNodes: { number } = {} local skin: number? = nil if H.num_joints > 0 then @@ -166,7 +161,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: end jointNodes, skin = Rig.skeleton(scene, joints, "local") end - -- materials: one per distinct material string (IQM names its texture there) + -- materials: one per distinct material string (IQM tools name the texture there) local matOf: { [string]: number } = {} local function material(name: string): number? if name == "" then @@ -185,7 +180,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: matOf[name] = #scene.materials return #scene.materials end - -- meshes for m = 0, H.num_meshes - 1 do local p = base + H.ofs_meshes + m * 24 local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) @@ -242,7 +236,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: if not attributes.POSITION then return nil, "no position array" end - -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + -- IQM's front faces are clockwise: corners 2 and 3 swap local ib = buffer.create(ct * 12) for k = 0, ct - 1 do local q = base + H.ofs_triangles + (ft + k) * 12 @@ -263,7 +257,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end - -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + -- frames hold the masked pose channels (offset + value * scale), in pose order if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then local np = H.num_poses local poses: { { mask: number, offset: { number }, scale: { number } } } = {} diff --git a/src/Rosetta/model/iqm/Write.luau b/src/Rosetta/model/iqm/Write.luau index a1dbe7a..63e03c8 100644 --- a/src/Rosetta/model/iqm/Write.luau +++ b/src/Rosetta/model/iqm/Write.luau @@ -1,14 +1,6 @@ --!strict --- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines --- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights --- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins --- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse --- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world --- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are --- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), --- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. --- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). --- Plain code (the caller wraps it in pcall). +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). Blend weights are u8 summing to 255; the skeleton +-- is the union of the scene's skins, parents first; animations quantized per pose channel to 16 bits. local Types = require("@rosetta/Types") local Bytes = require("@rosetta/core/Bytes") local Mat4 = require("@rosetta/codecs/model/Mat4") @@ -21,7 +13,6 @@ local Scene = Types.Scene type M4 = { number } -- ------------------------------------------------------------------------------------------------ scene walk --- world matrices (rest pose, or with a pose's overrides) and the parent of every node local function parents(scene: Types.Scene): { [number]: number } local parent: { [number]: number } = {} for i, n in scene.nodes do @@ -70,7 +61,6 @@ local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sa end -- ------------------------------------------------------------------------------------------------ geometry --- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points local function triangles(prim: Types.Primitive): { number }? local mode = prim.mode or "triangles" local nv = prim.attributes.POSITION.count @@ -143,7 +133,7 @@ local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: return out end --- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +-- the 4 strongest, u8 weights summing to 255 local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } local pairs_: { { number } } = {} for c = 1, 4 do @@ -179,7 +169,6 @@ local function influences(skin: Types.Skin, jointIndex: { [number]: number }, jo return list end --- appends a flat influence list to the blend index / weight arrays (4 slots) local function push4(bi: { number }, bw: { number }, list: { number }) local n = #bi for c = 1, 4 do @@ -194,7 +183,6 @@ type MeshOut = { name: string, material: string, first: number, count: number, t function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) local parent = parents(scene) local rest = worlds(scene, parent, nil) - -- the skeleton: every skin joint, parents first local isJoint: { [number]: boolean } = {} local ibmOf: { [number]: M4 } = {} for _, skin in scene.skins do @@ -212,9 +200,9 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end end end - -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + -- IQM wants parents first local jointList: { number } = {} - local jointIndex: { [number]: number } = {} -- node -> 0-based joint + local jointIndex: { [number]: number } = {} local function add(n: number, depth: number) if jointIndex[n] or depth > #scene.nodes then return @@ -271,7 +259,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end return Mat4.decompose(m) end - -- the meshes local nodeOfMesh: { [number]: number } = {} local placed: { { node: number, mesh: number } } = {} local seen: { [number]: boolean } = {} @@ -311,7 +298,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri local hasTC, hasN, hasTG, hasC = false, false, false, false local tris: { number } = {} local meshes: { MeshOut } = {} - -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds local skinOf: { { number } } = {} local nvTotal = 0 for _, pl in placed do @@ -392,7 +378,7 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri else table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) end - -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + -- the 4 strongest, u8 weights summing to 255 local list: { number } if joints and weights and skinned then list = influences(skinned, jointIndex, joints, weights, v) @@ -404,7 +390,7 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri push4(BI, BW, list) skinOf[#skinOf + 1] = list end - -- triangles back to IQM's clockwise order + -- IQM's clockwise order local tfirst = #tris // 3 for k = 1, #tri, 3 do table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) @@ -428,7 +414,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri if #meshes == 0 then return nil, "nothing to write: no triangle primitives" end - -- animation frames local frames: { { { number } } } = {} -- frames[f][joint] = 10 values local anims: { { name: string, first: number, count: number, rate: number } } = {} local frameWorld: { { [number]: M4 } } = {} @@ -438,7 +423,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri if #keys > 0 then local rate = opts and opts.framerate if not rate then - -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second local dt = if #keys > 1 then keys[2] - keys[1] else 0 local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 for k = 2, #keys do @@ -475,7 +459,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end end end - -- quantization per pose channel local masks, offsets, scales = {}, {}, {} local numChannels = 0 for j = 1, #jointList do @@ -500,7 +483,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri end masks[j], offsets[j], scales[j] = mask, off, sc end - -- text local text = { "\0" } local textLen = 1 local textAt: { [string]: number } = { [""] = 0 } @@ -527,7 +509,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri str(a.name) end local comment = opts and opts.comment - -- layout local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) local H: { [string]: number } = {} local function at(): number @@ -549,7 +530,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri w:u32le(v) end end - -- vertex arrays: headers, then data type Arr = { typ: number, format: number, comps: number, data: { number } } local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } if hasTC then @@ -648,7 +628,6 @@ function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: stri while at() % 4 ~= 0 do w:u8(0) end - -- bounds of the skinned vertices per frame H.ofs_bounds = at() local skinM = table.create(#jointList) :: { M4 } for f, world in frameWorld do diff --git a/src/Rosetta/model/iqm/init.luau b/src/Rosetta/model/iqm/init.luau index 016b70e..53f5e17 100644 --- a/src/Rosetta/model/iqm/init.luau +++ b/src/Rosetta/model/iqm/init.luau @@ -1,15 +1,7 @@ --!strict --- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / --- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). --- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as --- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as --- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _), joints --- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels --- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in --- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's --- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). --- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and --- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). +-- model/iqm: Inter-Quake Model (IQM version 2; iqm.txt / iqm.h of Lee Salzman's IQM SDK, public domain; checked against +-- assimp). Supports: meshes, every vertex array format, joints / skin, poses + anims, bounds. IQM is z-up, clockwise. +-- Not supported: IQM version 1, adjacency and extensions. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,11 +22,11 @@ local Iqm = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxVertices: number?, -- refuse more vertices or triangles (default 2^25) + maxVertices: number?, -- default 2^25 } export type EncodeOptions = { - framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second) - comment: string?, -- stored in the comment block + framerate: number?, -- default: the key spacing when uniform, else 30 per second + comment: string?, } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/model/ldraw/Colors.luau b/src/Rosetta/model/ldraw/Colors.luau index d114066..7d3d36f 100644 --- a/src/Rosetta/model/ldraw/Colors.luau +++ b/src/Rosetta/model/ldraw/Colors.luau @@ -1,7 +1,6 @@ --!strict --- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from --- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see --- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut +-- model/ldraw/Colors: the LDraw colour table, parsed from !COLOUR lines. The built-in table is LDraw.org's LDConfig.ldr +-- (UPDATE 2025-05-20; CC BY 2.0, see licenses/LDRAW_COLOURS.txt), without the "0 !COLOUR " prefix and with MATERIAL cut -- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. local Colors = {} @@ -10,7 +9,7 @@ export type Table = { [number]: Colour } local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } --- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +-- "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." function Colors.entry(rest: string): (number?, Colour?) local words: { string } = {} for w in string.gmatch(rest, "%S+") do @@ -51,7 +50,6 @@ function Colors.entry(rest: string): (number?, Colour?) return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } end --- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added function Colors.parse(text: string, into: Table?): Table local t: Table = into or {} for line in string.gmatch(text, "[^\n]+") do @@ -297,7 +295,6 @@ Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 ]] local cache: Table? = nil --- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it) function Colors.builtin(): Table if not cache then local t: Table = {} diff --git a/src/Rosetta/model/ldraw/Read.luau b/src/Rosetta/model/ldraw/Read.luau index 8b5b060..bcc201a 100644 --- a/src/Rosetta/model/ldraw/Read.luau +++ b/src/Rosetta/model/ldraw/Read.luau @@ -1,8 +1,7 @@ --!strict --- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command --- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into --- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes. --- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +-- model/ldraw/Read: LDraw text -> Types.Scene. Sub-files are tried as written (backslashes as slashes), then lower +-- case, under "", "parts/", "p/", "parts/s/" and "models/"; faces are written counter-clockwise after the matrices' +-- mirroring. local Types = require("@rosetta/Types") local Colors = require("@rosetta/model/ldraw/Colors") @@ -22,7 +21,7 @@ export type Options = { maxNodes: number?, } --- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5 +-- k = 0 (a BFC state change), 1 (a reference: v = x y z a b c d e f g h i), 2..5 type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? } type File = { name: string, @@ -52,7 +51,6 @@ local function srgbToLinear(v: number): number return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4 end --- parse(text, name) -> File (colour definitions go into colours as they are met) local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } local cmds = f.cmds @@ -96,7 +94,6 @@ local function parse(text: string, name: string, colours: Colors.Table, stats: { elseif w1 == "Author:" then f.author = rest elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then - -- (headers) elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) end @@ -152,7 +149,6 @@ local function parse(text: string, name: string, colours: Colors.Table, stats: { return f end --- scene(text, opts) -> Scene | nil, message, kind function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?) local o: Options = opts or {} local colours = Colors.builtin() @@ -329,7 +325,7 @@ function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, strin end end - -- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct) + -- m is a 3x4 row-major matrix local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean) if failure then return @@ -439,7 +435,6 @@ function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, strin return Types.Scene.accessor(b, "f32", 3, count) end - -- the mesh of a file baked at the identity (nil when it has no geometry) local meshOf: { [string]: number | false } = {} local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number? local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "") diff --git a/src/Rosetta/model/ldraw/init.luau b/src/Rosetta/model/ldraw/init.luau index 01aab94..245a395 100644 --- a/src/Rosetta/model/ldraw/init.luau +++ b/src/Rosetta/model/ldraw/init.luau @@ -1,33 +1,7 @@ --!strict --- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and --- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked --- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models. --- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour + --- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines --- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at --- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried --- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing --- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles). --- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without --- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main --- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw = --- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one --- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines --- = false drops them); no normals, no indices (each triangle has its own three vertices). --- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise --- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or --- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place. --- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge --- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig --- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered --- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER -> --- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }). --- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node --- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright = --- false leaves it out (meta.up = nil, meta.source.up = "-y"). --- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }. --- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta --- commands (ignored); BFC in model files' references (models place parts as certified). +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read; File Format spec 1.0.2 with the MPD, BFC and !COLOUR extensions +-- (ldraw.org). Supports: line types 0-5, sub-files, BFC, LDConfig colours. -Y up, 1 LDU = 0.4 mm (a root node turns +-- it). Not supported: writing; !TEXMAP and !DATA; LDCad / MLCad / LPub meta commands; BFC in model files' references. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -49,15 +23,15 @@ local Ldraw = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths) - files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...) + resolve: ((uri: string) -> any)?, -- sub-files by library path + files: { [string]: any }?, -- or by library path ("parts/3001.dat", "p/stud.dat", ...) ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours - color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour") - upright: boolean?, -- add the root node turning -Y up into Y up (default true) - flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false) - lines: boolean?, -- type 2 edge lines as "lines" primitives (default true) - optionalLines: boolean?, -- type 5 optional lines too (default false) - maxDepth: number?, -- sub-file nesting (default 64) + color: number?, -- default 16 ("Main_Colour") + upright: boolean?, -- default true + flatten: boolean?, -- default false + lines: boolean?, -- default true + optionalLines: boolean?, -- default false + maxDepth: number?, -- default 64 maxTriangles: number?, -- default 2^24 maxNodes: number?, -- default 2^20 } @@ -80,7 +54,6 @@ end -- ------------------------------------------------------------------------------------------------ decode function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, kind = pcall(Read.scene, text, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) @@ -92,8 +65,6 @@ function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err end -- ------------------------------------------------------------------------------------------------ extras --- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance, --- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added function Ldraw.colors(ldconfig: string?): { [number]: any } local t = Colors.builtin() if ldconfig then diff --git a/src/Rosetta/model/lwo/Build.luau b/src/Rosetta/model/lwo/Build.luau index c8cfc02..4bbd6d2 100644 --- a/src/Rosetta/model/lwo/Build.luau +++ b/src/Rosetta/model/lwo/Build.luau @@ -1,11 +1,6 @@ --!strict --- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z --- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's --- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its --- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), --- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, --- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. --- Plain code (the caller wraps it in pcall). +-- model/lwo/Build: a parsed LightWave object -> Types.Scene. LightWave is left-handed (y up, clockwise front faces): z +-- is negated and the winding reversed, as assimp does. Vertices are split where a VMAD gives a corner its own value. local Types = require("@rosetta/Types") local Parse = require("@rosetta/model/lwo/Parse") @@ -14,7 +9,7 @@ local Build = {} local Scene = Types.Scene local writef32, writeu32 = buffer.writef32, buffer.writeu32 -type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point" +type Group = { material: number, class: string, polys: { number } } -- "poly" / "patch" / "line" / "point" local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } @@ -118,7 +113,6 @@ local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { return groups end --- the corners of a face in output order (winding reversed for the handedness change, first corner kept) local function ordered(corners: { number }): { number } local n = #corners local out = table.create(n) :: { number } @@ -134,8 +128,8 @@ type Attr = { map: Parse.Map, name: string, comps: number } local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive local pts, pivot = layer.pts, layer.pivot local vertOf: { [number]: number } = {} - local srcPoint: { number } = {} -- vertex (1-based) -> point - local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local srcPoint: { number } = {} + local srcPoly: { number } = {} -- -1: none local indices: { number } = {} local faces: { number } = {} local madMaps: { Parse.Map } = {} @@ -204,7 +198,6 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) end local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) } - -- the value of map m for vertex v (1-based), or nil local function value(m: Parse.Map, v: number): ({ number }?, number?) local f = srcPoly[v] if f >= 0 then @@ -306,7 +299,7 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S local scene = Scene.new() scene.meta.up = "y" scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } - -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + -- every TXUV map name, in order of first appearance, gets one TEXCOORD_n index local uvSets: { [string]: number } = {} local nuv = 0 for _, layer in m.layers do @@ -317,7 +310,6 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end end end - -- materials: one per surface, then one per tag without a surface, then a default one local texCache: { [string]: number } = {} local bySurfName: { [string]: number } = {} for i, surf in m.surfaces do @@ -359,7 +351,6 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end return default :: number end - -- nodes and meshes local nodeOf: { [number]: number } = {} local layerOfNode: { Parse.Layer } = {} for _, layer in m.layers do @@ -434,7 +425,7 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S end end end - -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + -- a parent link that would close a cycle is dropped local parentOf: { [number]: number } = {} for ni, layer in layerOfNode do local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil diff --git a/src/Rosetta/model/lwo/Parse.luau b/src/Rosetta/model/lwo/Parse.luau index d977762..110f66e 100644 --- a/src/Rosetta/model/lwo/Parse.luau +++ b/src/Rosetta/model/lwo/Parse.luau @@ -1,15 +1,7 @@ --!strict --- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build --- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave --- 5.x), checked against what assimp's LWO importer reads (no code taken). --- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are --- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS --- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo --- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural --- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). --- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, --- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. --- Plain code (the caller wraps it in pcall); bad data returns nil, message. +-- model/lwo/Parse: LightWave object chunks -> plain tables. From the LWO2 specification (LightWave 6 "Object Files", +-- Ernie Wright) and the LWOB one (LightWave 5.x), checked against assimp (no code taken). Several PNTS per layer: later +-- POLS / VMAP indices are relative to the latest. Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. local Bytes = require("@rosetta/core/Bytes") local Chunks = require("@rosetta/containers/Chunks") @@ -19,17 +11,17 @@ export type Map = { kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot" name: string, dims: number, - vals: { number }, -- per point: vals[point * dims + c + 1] + vals: { number }, -- vals[point * dims + c + 1] has: { [number]: boolean }, mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values } -export type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices +export type Poly = { kind: string, surf: number?, corners: { number } } -- 0-based point indices export type Layer = { index: number, name: string?, parent: number?, pivot: { number }, - pts: { number }, -- x, y, z flat + pts: { number }, polys: { Poly }, maps: { Map }, implicit: boolean?, -- the layer before any LAYR @@ -50,7 +42,7 @@ export type Block = { } export type Surface = { name: string, - values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND + values: { [string]: number }, color: { number }, side: number, vcol: { name: string, kind: string, intensity: number }?, @@ -62,7 +54,7 @@ export type Model = { tags: { string }, layers: { Layer }, surfaces: { Surface }, - clips: { [number]: string }, -- clip index -> path + clips: { [number]: string }, skipped: { [string]: number }, corners: number, } @@ -79,7 +71,7 @@ local MAP_KINDS: { [string]: string } = { } -- ------------------------------------------------------------------------------------------------ primitives --- S0: a NUL-terminated string padded to an even length +-- S0: NUL-terminated, padded to an even length local function s0(r: Bytes.Reader): string local start = r.pos local s = r:cstring() @@ -89,7 +81,7 @@ local function s0(r: Bytes.Reader): string return s end --- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +-- VX: 2 bytes, or 4 bytes after an 0xFF byte local function vx(r: Bytes.Reader): number if r:peekU8() == 0xFF then return r:u32be() - 0xFF000000 @@ -102,7 +94,7 @@ local function id4(r: Bytes.Reader): string return (string.gsub(s, " +$", "")) end --- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +-- LWO2 sub-chunks: 4-byte id, 2-byte size, padded to even local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ()) while p + 6 <= e do local id = buffer.readstring(buf, p, 4) @@ -133,7 +125,6 @@ local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string? return nil end --- POLS (LWO2): returns nil or an error local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string? local polys = layer.polys local npts = #layer.pts // 3 @@ -281,7 +272,7 @@ end local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } local function readBlock(r: Bytes.Reader, surf: Surface) - -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + -- IMAP / PROC / GRAD / SHDR header: ordinal string, header sub-chunks if r:remaining() < 6 then return end @@ -464,7 +455,6 @@ local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [n end -- ------------------------------------------------------------------------------------------------ the file --- parse(buf, from, limit, opts) -> Model | nil, message function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?) local version = buffer.readstring(buf, from + 8, 4) local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) @@ -516,7 +506,7 @@ function Parse.model(buf: buffer, from: number, limit: number, maxCorners: numbe if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then err = readPolys(r, layer, kind, ptBase, budget) else - -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + -- PTAG / VMAD refer to the polygon numbering: keep it, skip the geometry local before = #layer.polys err = readPolys(r, layer, kind, ptBase, budget) model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before diff --git a/src/Rosetta/model/lwo/init.luau b/src/Rosetta/model/lwo/init.luau index 810ba5b..d6a2e29 100644 --- a/src/Rosetta/model/lwo/init.luau +++ b/src/Rosetta/model/lwo/init.luau @@ -1,19 +1,7 @@ --!strict --- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from --- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. --- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / --- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and --- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: --- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the --- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has --- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces --- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> --- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, --- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: --- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding --- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. --- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / --- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). +-- model/lwo: LightWave objects LWO2 (6+), LWOB (5.x) and Modo's LXOB, read; from the LWO2 / LWOB specs, checked against +-- assimp. Supports: layers, polygons, VMAP / VMAD, surfaces, clips. Left-handed: z negated, winding reversed. Not +-- supported: LWO3, envelopes, procedural / gradient textures, planar / cylindrical / spherical projections, smoothing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,8 +22,8 @@ local Lwo = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - maxVertices: number?, -- refuse more points / polygon corners (default 2^25) + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^25 } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/model/mca/Chunk.luau b/src/Rosetta/model/mca/Chunk.luau index 49f5a00..fd5d992 100644 --- a/src/Rosetta/model/mca/Chunk.luau +++ b/src/Rosetta/model/mca/Chunk.luau @@ -1,9 +1,7 @@ --!strict --- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three --- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least --- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 = --- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through --- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y). +-- model/mca/Chunk: an Anvil chunk's blocks (Minecraft wiki "Chunk format"): 1.18+ sections[] block_states +-- (non-spanning, >= 4 bits); 1.13 - 1.17 Level.Sections[] Palette + BlockStates (spanning before DataVersion 2529 = +-- 20w17a); pre-1.13 Blocks / Add / Data nibble arrays. A section is 16 x 16 x 16 cells, x then z then y. local Types = require("@rosetta/Types") local Nbt = require("@rosetta/codecs/text/Nbt") local Mc = require("@rosetta/codecs/model/Minecraft") @@ -12,14 +10,14 @@ local Chunk = {} local Packed = Mc.Packed -export type Section = { y: number, states: { string }, cells: buffer } -- cells: u16 per cell, 4096, x-z-y order +export type Section = { y: number, states: { string }, cells: buffer } -- u16 per cell, 4096, x-z-y order export type Blocks = { - x: number, -- chunk coordinates (xPos / zPos) + x: number, -- xPos / zPos z: number, dataVersion: number?, sections: { Section }, - blockEntities: { any }, -- the chunk's records as they are (absolute x, y, z) - entities: { any }, -- entities stored in the chunk (before 1.17) + blockEntities: { any }, -- absolute x, y, z + entities: { any }, -- before 1.17 } local function int(v: any): number? @@ -31,7 +29,6 @@ local function list(v: any): { any } return if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then v else {} end --- a palette section (1.13+): states from the palette compounds, cells from the packed array local function paletted(y: number, palette: { any }, data: any, minBits: number, spanning: boolean): (Section?, string?) local states = table.create(#palette) :: { string } for i, c in palette do @@ -58,7 +55,6 @@ local function paletted(y: number, palette: { any }, data: any, minBits: number, return { y = y, states = states, cells = cells }, nil end --- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk function Chunk.blocks(root: any): (Blocks?, string?) if type(root) ~= "table" or not Types.isObject(root) then return nil, "chunk NBT is not a compound" diff --git a/src/Rosetta/model/mca/Lz4Block.luau b/src/Rosetta/model/mca/Lz4Block.luau index 37d10ab..9b45515 100644 --- a/src/Rosetta/model/mca/Lz4Block.luau +++ b/src/Rosetta/model/mca/Lz4Block.luau @@ -1,15 +1,13 @@ --!strict --- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4 --- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 | --- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the --- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4. +-- model/mca/Lz4Block: lz4-java LZ4BlockOutputStream framing (Minecraft 24w04a+, compression type 4): "LZ4Block", token +-- (0x10 raw / 0x20 LZ4 | level), compressed and decompressed lengths, XXH32 (LE i32s; not verified), then the block; +-- blocks are independent and an empty block ends the stream. local Lz4 = require("@rosetta/codecs/compress/Lz4") local Lz4Block = {} local MAGIC = "LZ4Block" --- decode(buf, offset, length, maxBytes) -> buffer | nil, message function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?) local p, e = offset, offset + length local parts, total = {}, 0 diff --git a/src/Rosetta/model/mca/init.luau b/src/Rosetta/model/mca/init.luau index fdbbf14..abdabc1 100644 --- a/src/Rosetta/model/mca/init.luau +++ b/src/Rosetta/model/mca/init.luau @@ -1,17 +1,7 @@ --!strict --- model/mca: Minecraft Anvil region files (r...mca: 32 x 32 chunks), read-only. New code, from the Minecraft --- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads --- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over --- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, --- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). --- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks --- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with --- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its --- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, --- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header --- and one chunk's NBT without building voxels. --- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the --- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). +-- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, +-- LZ4 (lz4-java blocks, 24w04a+) and stored chunks, external .mcc chunks, every chunk layout back to pre-1.13. +-- Not supported: writing; custom (127) compression; LZ4 checksums; the separate 1.17+ entities/ region files. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -35,19 +25,19 @@ local Mca = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - chunks: { { number } }?, -- only these chunks: { { x, z } } local coordinates 0 .. 31 (default all) - area: { number }?, -- only blocks inside { minX, minY, minZ, maxX, maxY, maxZ } (world coordinates, inclusive) - maxCells: number?, -- refuse grids with more cells (default 2^25: pick chunks or an area for big regions) - maxBytes: number?, -- refuse a chunk that inflates past this (default 2^26) - keepNbt: boolean?, -- keep each chunk's NBT in meta.source.chunks[i].nbt (default true) - region: { number }?, -- the region's coordinates { x, z } (default: from opts.name "r...mca"), for .mcc files - name: string?, -- the file name (the api fills it in) - resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c...mcc + chunks: { { number } }?, -- local coordinates 0 .. 31 (default all) + area: { number }?, -- world coordinates, inclusive + maxCells: number?, -- default 2^25 + maxBytes: number?, -- default 2^26 + keepNbt: boolean?, -- default true + region: { number }?, -- default: from opts.name "r...mca" + name: string?, + resolve: ((string) -> buffer?)?, -- external chunks c...mcc } export type Entry = { - x: number, -- local chunk coordinates 0 .. 31 + x: number, -- 0 .. 31 z: number, - sector: number, -- 4 KiB sector of the chunk + sector: number, -- 4 KiB sectors sectors: number, timestamp: number, -- seconds since 1970 } @@ -87,7 +77,6 @@ function Mca.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?) local n = r.limit - r.base if n < 8192 then @@ -122,7 +111,6 @@ local function regionCoords(o: DecodeOptions): (number?, number?) return nil, nil end --- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any) local p = r.base + e.sector * 4096 if p + 5 > r.limit then @@ -175,7 +163,6 @@ local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, a return out, comp end --- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any) local o: DecodeOptions = opts or {} if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then @@ -243,7 +230,6 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end end - -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for _, c in chunks do lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) @@ -273,7 +259,7 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end if lo[2] == math.huge then - lo[2], hi[2] = 0, -1 -- no blocks at all + lo[2], hi[2] = 0, -1 end if #chunks == 0 then lo, hi = { 0, 0, 0 }, { -1, -1, -1 } @@ -283,7 +269,6 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if n > (o.maxCells or 2 ^ 25) then return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) end - -- one palette for the grid (air first), each section copied in through a remap table local states = { "minecraft:air" } local index: { [string]: number } = { ["minecraft:air"] = 0 } local grid = buffer.create(n * 2) diff --git a/src/Rosetta/model/md2/init.luau b/src/Rosetta/model/md2/init.luau index cd767d1..d9d256b 100644 --- a/src/Rosetta/model/md2/init.luau +++ b/src/Rosetta/model/md2/init.luau @@ -1,15 +1,7 @@ --!strict --- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the --- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken. --- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise, --- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1), --- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored --- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not --- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one --- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture --- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up. --- meta.source = { format, frames, frameNames, skinWidth, skinHeight }. --- Not supported: the GL command list (the triangles carry the same geometry), writing. +-- model/md2: Quake II MD2 ("IDP2" v8), from qfiles.h dmdl_t and David Henry's "MD2 file format"; no code taken. +-- Supports: clockwise faces reversed, frames as morph targets, animations per frame-name group (10 fps), skin URIs. +-- Not supported: the GL command list, writing; Quake's normal table (not redistributable: normals are computed). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,10 +22,10 @@ local Md2 = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - frame: number?, -- the frame used as the base POSITION (1-based, default 1) - morph: boolean?, -- every frame as a morph target + the animations (default true) - fps: number?, -- animation frame rate (default 10) - maxVertices: number?, -- frames x vertices (default 2^24) + frame: number?, -- 1-based, default 1 + morph: boolean?, -- default true + fps: number?, -- default 10 + maxVertices: number?, -- default 2^24 } -- ------------------------------------------------------------------------------------------------ constants @@ -49,7 +41,6 @@ function Md2.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- group frame names by their name without trailing digits, in file order local function groups(names: { string }, fps: number): { Rig.Range } local out: { Rig.Range } = {} for i, n in names do @@ -99,13 +90,11 @@ function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E return nil, Err.new(Err.CORRUPT, "frame size too small", 16) end local b, base = r.buf, r.base - -- skins local skins: { string } = {} for i = 0, nSkins - 1 do local s = buffer.readstring(b, base + oSkins + i * 64, 64) table.insert(skins, (string.match(s, "^[^%z]*")) :: string) end - -- weld (xyz, st) pairs local key: { [number]: number } = {} local vx: { number }, vst: { number } = {}, {} local indices: { number } = {} @@ -140,7 +129,6 @@ function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) end end - -- frames local frames: { buffer } = {} local normals: { buffer } = {} local names: { string } = {} diff --git a/src/Rosetta/model/md3/init.luau b/src/Rosetta/model/md3/init.luau index 46277c8..3c4a395 100644 --- a/src/Rosetta/model/md3/init.luau +++ b/src/Rosetta/model/md3/init.luau @@ -1,14 +1,7 @@ --!strict --- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format --- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format" --- notes (PhaethonH); no code taken. --- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame --- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left --- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all --- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes --- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation). --- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }. --- Not supported: writing. +-- model/md3: Quake III MD3 ("IDP3" v15), from qfiles.h md3Header_t / md3Surface_t and PhaethonH's "MD3 file format"; +-- no code taken. Supports: surfaces as primitives, positions in 1/64 units, lat / long normals, frames as morph +-- targets, tags as child nodes with channels. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,10 +23,10 @@ local Md3 = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - frame: number?, -- the frame used as the base POSITION / NORMAL (1-based, default 1) - morph: boolean?, -- every frame as a morph target + the animation (default true) - fps: number?, -- animation frame rate (default 15) - maxVertices: number?, -- frames x vertices over all surfaces (default 2^24) + frame: number?, -- 1-based, default 1 + morph: boolean?, -- default true + fps: number?, -- default 15 + maxVertices: number?, -- default 2^24 } -- ------------------------------------------------------------------------------------------------ constants @@ -175,7 +168,6 @@ function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E table.insert(mesh.primitives, prim) so += oEnd end - -- frames and tags local frameNames: { string } = {} for f = 0, nFrames - 1 do frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16) diff --git a/src/Rosetta/model/md5/Read.luau b/src/Rosetta/model/md5/Read.luau index fb1d75b..16cab7d 100644 --- a/src/Rosetta/model/md5/Read.luau +++ b/src/Rosetta/model/md5/Read.luau @@ -1,11 +1,6 @@ --!strict --- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose: --- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive --- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed --- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim: --- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at --- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding --- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken. +-- model/md5/Read: MD5Version 10 text, from modwiki "MD5 (file format)" and David Henry's "The MD5 Mesh and Animation +-- Formats"; no code taken. The bind pose is model space, the baseframe parent-relative. local Types = require("@rosetta/Types") local Rig = require("@rosetta/codecs/model/Rig") @@ -93,7 +88,7 @@ local function vec(L: Lexer, n: number): { number } return v end --- the unit quaternion from its x, y, z (w <= 0, as id's tools store it) +-- w = -sqrt(1 - x² - y² - z²) (w <= 0, as id's tools store it) local function quat(x: number, y: number, z: number): { number } local t = 1 - x * x - y * y - z * z return { x, y, z, if t < 0 then 0 else -math.sqrt(t) } @@ -109,7 +104,6 @@ end -- ------------------------------------------------------------------------------------------------ md5mesh type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } } --- mesh(text, opts) -> Scene, joint node indices by name | nil, message function Read.mesh(text: string, opts: Options?): (Types.Scene?, any) local L: Lexer = { text = text, pos = 1, err = nil } local joints: { MeshJoint } = {} @@ -277,7 +271,6 @@ export type Anim = { tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame } --- anim(text) -> Anim | nil, message function Read.anim(text: string): (Anim?, string?) local L: Lexer = { text = text, pos = 1, err = nil } local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} } @@ -396,7 +389,6 @@ function Read.anim(text: string): (Anim?, string?) return a, nil end --- addAnim(scene, nodes by joint name, anim, name) -> channels added function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number local nodes: { number } = {} local tracks: { [number]: Rig.Track } = {} @@ -416,7 +408,6 @@ function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, return #scene.animations[ai].channels end --- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation function Read.animScene(a: Anim, name: string): Types.Scene local scene = Scene.new() scene.meta.up = "z" diff --git a/src/Rosetta/model/md5/init.luau b/src/Rosetta/model/md5/init.luau index 20164b7..39411a6 100644 --- a/src/Rosetta/model/md5/init.luau +++ b/src/Rosetta/model/md5/init.luau @@ -1,10 +1,6 @@ --!strict --- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim --- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from --- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by --- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless --- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom --- units, z up. Not supported: writing, .md5camera. +-- model/md5: Doom 3 / Quake 4 MD5 (MD5Version 10 text): .md5mesh and .md5anim (model/md5/Read); a mesh loads +-- opts.anims, joints matched by name. Not supported: writing, .md5camera. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,11 +22,11 @@ local Md5 = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - anims: { string }?, -- .md5anim files to load with a .md5mesh + anims: { string }?, resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - skipMissing: boolean?, -- ignore animations that cannot be found (default false: UNSUPPORTED) - name: string?, -- the file name (names a standalone animation) + skipMissing: boolean?, -- default false: UNSUPPORTED + name: string?, maxVertices: number?, -- default 2^24 } diff --git a/src/Rosetta/model/mdl/HalfLife.luau b/src/Rosetta/model/mdl/HalfLife.luau index bafc628..30cc80e 100644 --- a/src/Rosetta/model/mdl/HalfLife.luau +++ b/src/Rosetta/model/mdl/HalfLife.luau @@ -1,14 +1,7 @@ --!strict --- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h --- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken. --- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts -> --- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans --- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 = --- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family -> --- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only). --- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone --- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "t.mdl" (pass it --- as opts.textures = that file's bytes). +-- model/mdl/HalfLife: GoldSrc studio models ("IDST" v10), from the Half-Life SDK studio.h and HLMV / Crowbar notes; no +-- code taken. Not supported: sequence groups in other files, bone controllers, hitboxes / attachments / events, blends +-- past the first. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Pixels = require("@rosetta/codecs/image/Pixels") @@ -27,7 +20,6 @@ local function str(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end --- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string) local n, at = readi32(b, base + 180), readi32(b, base + 184) if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then @@ -52,7 +44,7 @@ local function textures(b: buffer, base: number, size: number, maxPixels: number return out, names end --- one animation value: bone default + stored value * scale (frame f, 0-based) +-- bone default + stored value * scale local function animValue(b: buffer, at: number, limit: number, f: number): number? local p = at local k = f @@ -77,7 +69,6 @@ local function animValue(b: buffer, at: number, limit: number, f: number): numbe return nil end --- decode(b, base, size, opts) -> Scene | nil, message function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?) if size < 244 then return nil, "truncated header" @@ -106,7 +97,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): local maxPixels = opts and opts.maxPixels or 2 ^ 24 local scene = Scene.new() scene.meta.up = "z" - -- bones local bones: { Bone } = {} local joints: { Rig.Joint } = {} for i = 0, nBones - 1 do @@ -124,7 +114,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): table.insert(scene.nodes, root) scene.roots[1] = 1 local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) - -- textures and skins local texSrc, texBase, texSize = b, base, size if nTex == 0 and opts and opts.textures then texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) @@ -151,7 +140,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 end end - -- body parts local totalVerts = 0 for part = 0, nParts - 1 do local po = base + oParts + part * 76 @@ -173,7 +161,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): local tex = skinMap[skinref + 1] or (skinref + 1) local img = images[tex] local tw, th = if img then img.width else 1, if img then img.height else 1 - -- triangle commands local weld: { [string]: number } = {} local corners: { { number } } = {} local indices: { number } = {} @@ -285,7 +272,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): table.insert(root.children, #scene.nodes) end end - -- sequences local seqs: { any } = {} for s = 0, nSeq - 1 do local so = base + oSeq + s * 176 diff --git a/src/Rosetta/model/mdl/Quake.luau b/src/Rosetta/model/mdl/Quake.luau index d1068f9..9657bb5 100644 --- a/src/Rosetta/model/mdl/Quake.luau +++ b/src/Rosetta/model/mdl/Quake.luau @@ -1,9 +1,6 @@ --!strict --- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et --- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken. --- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette; --- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per --- side); simple and grouped frames become morph targets with one animation per frame-name group. +-- model/mdl/Quake: Quake 1 MDL ("IDPO" v6), from "Quake Specs 3.4" section 5 and modelgen.h; no code taken. Seam +-- texture coordinates of back-facing triangles move half a skin width; a skin group shows its first picture. local Types = require("@rosetta/Types") local Pixels = require("@rosetta/codecs/image/Pixels") local Rig = require("@rosetta/codecs/model/Rig") @@ -19,7 +16,6 @@ local function name16(b: buffer, at: number): string return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string end --- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base) function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?) if size < 84 then return nil, "truncated header" @@ -41,7 +37,6 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o local function need(n: number): boolean return n >= 0 and p + n <= size end - -- skins local pal = if palette then Pixels.palette(palette, 0, 256) else nil local skins: { Types.Image } = {} local px = sw * sh @@ -79,7 +74,6 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o table.insert(skins, img) p += count * px end - -- texture coordinates and triangles if not need(nVerts * 12 + nTris * 16) then return nil, "truncated vertices / triangles" end @@ -117,7 +111,7 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o table.insert(indices, c[1]) end p += nTris * 16 - -- frames: simple (type 0) or groups of simple frames + -- frames: simple (type 0) or groups local frameAt: { number } = {} local names: { string } = {} local fsize = 24 + nVerts * 4 diff --git a/src/Rosetta/model/mdl/init.luau b/src/Rosetta/model/mdl/init.luau index be1b702..e9de164 100644 --- a/src/Rosetta/model/mdl/init.luau +++ b/src/Rosetta/model/mdl/init.luau @@ -1,10 +1,6 @@ --!strict --- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10: --- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the --- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string), --- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette = --- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx --- files) is UNSUPPORTED. +-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins +-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,14 +22,14 @@ local Mdl = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - palette: (buffer | string)?, -- Quake: the 768-byte palette (default: resolved gfx/palette.lmp, else grey) + palette: (buffer | string)?, -- default: resolved gfx/palette.lmp, else grey resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, - frame: number?, -- Quake: the frame used as the base POSITION (default 1) - morph: boolean?, -- Quake: frames as morph targets + animations (default true) - fps: number?, -- Quake: animation frame rate (default 10) - bodies: { number }?, -- Half-Life: the model picked for each body part (1-based, default 1) - textures: (buffer | string)?, -- Half-Life: the "t.mdl" texture file of a model without textures + frame: number?, -- Quake; default 1 + morph: boolean?, -- Quake; default true + fps: number?, -- Quake; default 10 + bodies: { number }?, -- Half-Life; 1-based, default 1 + textures: (buffer | string)?, maxPixels: number?, -- default 2^24 maxVertices: number?, -- default 2^24 } diff --git a/src/Rosetta/model/ms3d/Read.luau b/src/Rosetta/model/ms3d/Read.luau index 05c6b32..904cdb3 100644 --- a/src/Rosetta/model/ms3d/Read.luau +++ b/src/Rosetta/model/ms3d/Read.luau @@ -1,15 +1,7 @@ --!strict --- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h --- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a --- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess --- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and --- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds --- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model), --- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3), --- joint extras (colours) and model extras (joint size, transparency mode, alpha reference). --- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices --- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest + --- key positions). Never throws on bad data: returns nil, message, offset. +-- model/ms3d/Read: the ms3dspec.h layout: vertices, triangles, groups, materials (shininess 0..128), the animation +-- header, joints (local Euler XYZ radians, keys in seconds relative to the rest pose), then the sub-versioned comments, +-- vertex extras (weights in percent, subversion 1-3), joint extras (colours) and model extras. Never throws. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") @@ -62,7 +54,6 @@ type Joint = { rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?, } --- scene(b, base, limit, opts) -> Scene | nil, message, offset function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?) local p = base local function need(n: number): boolean @@ -77,7 +68,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty end p += 14 local maxV = opts and opts.maxVertices or 2 ^ 20 - -- vertices if not need(2) then return nil, "truncated vertex count", p end @@ -92,7 +82,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } end p += nv * 15 - -- triangles if not need(2) then return nil, "truncated triangle count", p end @@ -106,7 +95,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty end local triAt = p p += nt * 70 - -- groups if not need(2) then return nil, "truncated group count", p end @@ -135,7 +123,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty p += 1 table.insert(groups, g) end - -- materials if not need(2) then return nil, "truncated material count", p end @@ -154,7 +141,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty }) end p += nm * 361 - -- animation header and joints (version 3 files may end here) + -- version 3 files may end here local fps, current, frames = 24, 0, 0 local joints: { Joint } = {} if need(12) then @@ -189,7 +176,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty table.insert(joints, j) end end - -- sub-versioned blocks local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } local function comments(list: { any }): string? if not need(4) then @@ -283,7 +269,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } local scene = S.new() scene.meta.up = "y" scene.meta.source = source :: any - -- materials, textures for _, m in mats do local mat = S.material(m.name) local d = m.diffuse @@ -305,7 +290,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } } table.insert(scene.materials, mat) end - -- joints: nodes, rest pose, skin local nj = #joints local jointNode: { [number]: number } = {} local byName: { [string]: number } = {} @@ -355,7 +339,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } end scene.skins[1] = { joints = list, inverseBindMatrices = ibm } end - -- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner local nv = #verts for gi, g in groups do local remap: { [string]: number } = {} @@ -365,7 +348,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } local count = 0 for _, ti in g.tris do local q = triAt + ti * 70 - -- a triangle with an out-of-range vertex is dropped if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then continue end @@ -382,7 +364,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } table.move(v.pos, 1, 3, o * 3 + 1, P) N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) - -- influences: the valid bones, weights normalized local sum = 0 for c = 1, 4 do if v.bones[c] >= 0 then @@ -429,7 +410,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any } table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end - -- the animation: rest * key rotations, rest + key positions local channels: { Types.Channel } = {} for i, j in joints do if #j.rotKeys > 0 then diff --git a/src/Rosetta/model/ms3d/Write.luau b/src/Rosetta/model/ms3d/Write.luau index 3e9d0dd..a9cefbc 100644 --- a/src/Rosetta/model/ms3d/Write.luau +++ b/src/Rosetta/model/ms3d/Write.luau @@ -1,13 +1,6 @@ --!strict --- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped, --- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first --- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2); --- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each --- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's --- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials: --- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and --- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment), --- joint colours and model extras are written in their sub-versioned blocks. +-- model/ms3d/Write: Scene -> MilkShape 3D v4: a group per placed primitive, the first skin's joints (rest pose from +-- the inverse bind matrices, keys relative to it), vertex extras subversion 2 (weights in percent). local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") @@ -57,14 +50,11 @@ end -- ------------------------------------------------------------------------------------------------ joints type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } } --- the rigid part (rotation and translation) of a matrix local function rigid(m: { number }): { number } local t, r = Mat4.decompose(m) return Mat4.compose(t, r, nil) end --- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order; --- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number }) local skin = scene.skins[1] local anim = scene.animations[1] @@ -85,7 +75,6 @@ local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: num table.insert(chans[ch.node], ch) end end - -- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix local B = S.IDENTITY local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil if skin and IBM and tr.world[skin.joints[1]] then @@ -104,8 +93,7 @@ local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: num while p ~= 0 and byNode[p] == nil do p = tr.parent[p] end - -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the - -- joint and its joint parent (C) carry over to the keys + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity() local gp = tr.parent[ni] local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY) @@ -158,7 +146,6 @@ type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { n type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number } type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? } --- every placed primitive as a group: vertices, triangles; or nil, message local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?) local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {} for _, pl in S.flatten(scene) do @@ -175,7 +162,6 @@ local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number continue end local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil - -- a rigid mesh follows its nearest joint local rigid = -1 if not skinned then local p = pl.node @@ -257,7 +243,6 @@ local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number b, c = c, b end local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi } - -- the face normal for primitives without normals local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z @@ -343,7 +328,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end w:i8(g.material % 256) end - -- materials w:u16le(#scene.materials) local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" for i, m in scene.materials do @@ -375,7 +359,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) fixedString(w, file, 128) fixedString(w, msg(x.alphamap), 128) end - -- the animation header and joints local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24) local last = 0 for _, j in js do @@ -412,7 +395,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end end end - -- comments w:u32le(1) local function comments(list: { any }, get: (any) -> string?) local found = {} @@ -465,7 +447,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end w:u32le(0) end - -- joint colours, model extras w:u32le(1) for _, j in js do local x: any = scene.nodes[j.node].extras diff --git a/src/Rosetta/model/ms3d/init.luau b/src/Rosetta/model/ms3d/init.luau index 62020fd..79171bb 100644 --- a/src/Rosetta/model/ms3d/init.luau +++ b/src/Rosetta/model/ms3d/init.luau @@ -1,18 +1,7 @@ --!strict --- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of --- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested --- against (no code ported). --- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and --- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in --- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive; --- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use --- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse --- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes --- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d, --- the model comment / fps / frames / joint size in meta.source. meta.up = "y". --- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex), --- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127 --- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written). +-- model/ms3d: MilkShape 3D 1.8 (.ms3d v3 / v4), from ms3dspec.h, tested against assimp's MS3D importer (no code +-- ported). Supports: groups, materials, joints, a skin, keyframes, comments and the extra blocks, read + write. Not +-- supported: scale keys (MilkShape has none), a second skin; writes at most 65535 vertices, 255 groups, 127 joints. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,12 +22,12 @@ local Ms3d = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxVertices: number?, -- refuse more triangle corners (default 2^20) + maxVertices: number?, -- default 2^20 } export type EncodeOptions = { - fps: number?, -- the animation's frames per second (default: the source's, else 24) - name: string?, -- the destination's file name (names textures that have no uri) - files: { [string]: any }?, -- receives the bytes of textures that have data but no uri + fps: number?, -- default: the source's, else 24 + name: string?, + files: { [string]: any }?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -53,7 +42,6 @@ end -- ------------------------------------------------------------------------------------------------ decode function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) - -- the scene builder is plain (not native) code: a bug there must not escape as an error local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) if not ok then return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) diff --git a/src/Rosetta/model/obj/Mtl.luau b/src/Rosetta/model/obj/Mtl.luau index daefd17..715af0d 100644 --- a/src/Rosetta/model/obj/Mtl.luau +++ b/src/Rosetta/model/obj/Mtl.luau @@ -1,8 +1,6 @@ --!strict --- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc, --- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping --- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the --- reverse (from extras.obj when present, else from the PBR fields). +-- model/obj/Mtl: Wavefront .mtl (Paul Bourke's MTL spec + the PBR extension: Pr, Pm, Ps, Pc, Pcr, aniso, anisor, Ke, +-- map_Pr, map_Pm, map_Ke, norm); Phong values are kept in extras.obj. local Types = require("@rosetta/Types") local Mtl = {} @@ -35,7 +33,6 @@ local function parseMap(args: { string }): Map end end else - -- -o / -s / -t: up to three numbers while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do table.insert(vals, args[i]) i += 1 @@ -48,7 +45,6 @@ local function parseMap(args: { string }): Map return { file = file, options = opts } end --- parse(text) -> { Entry } in file order function Mtl.parse(text: string): { Entry } local out: { Entry } = {} local cur: Entry? = nil @@ -96,7 +92,6 @@ function Mtl.mime(file: string): string? return if ext then MIME[string.lower(ext)] else nil end --- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material local m = Types.Scene.material(e.name) local v = e.values @@ -144,7 +139,6 @@ function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material if m.emissiveTexture and not ke then m.emissive = { 1, 1, 1 } end - -- everything else as it was, for the writer and for Phong renderers local extra: { [string]: any } = {} for k, vals in v do extra[k] = vals @@ -171,7 +165,6 @@ local function num(v: number): string end Mtl.num = num --- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to. function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string local out = { "# written by rosetta" } for i, m in materials do @@ -190,7 +183,6 @@ function Mtl.write(materials: { Types.Material }, names: { string }, textureFile end order = table.clone(saved.order or {}) end - -- the PBR fields win over the saved Phong values they map to local bc = m.baseColor or { 1, 1, 1, 1 } values.Kd = { bc[1], bc[2], bc[3] } if (bc[4] or 1) < 1 or values.d then @@ -235,7 +227,6 @@ function Mtl.write(materials: { Types.Material }, names: { string }, textureFile setMap("norm", m.normalTexture) end setMap("map_ORM", m.metallicRoughnessTexture) - -- the saved order first, then the rest sorted local keys = {} local seen = {} for _, k in order do diff --git a/src/Rosetta/model/obj/init.luau b/src/Rosetta/model/obj/init.luau index 493a0dd..917f451 100644 --- a/src/Rosetta/model/obj/init.luau +++ b/src/Rosetta/model/obj/init.luau @@ -1,17 +1,7 @@ --!strict --- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp --- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form --- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR --- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line --- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons", --- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false --- keeps OBJ's). --- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group. --- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination. --- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups --- (s: kept per node in extras.obj.smoothing, not used to compute normals). --- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to --- opts.files[.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too. +-- model/obj: Wavefront OBJ + MTL (Paul Bourke's specs, as Blender / Maya / assimp write them). Supports: v (with +-- "v x y z r g b"), vt, vn, f in every index form, l, p, o / g, usemtl / mtllib, continuations; TEXCOORD_0 flipped to +-- top-left. Not supported: free-form geometry (curv, surf: skipped), smoothing groups (kept in extras.obj.smoothing). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,21 +21,21 @@ local Obj = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) - mtl: (string | buffer)?, -- the material library text, when not found through resolve / files - resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths) - files: { [string]: any }?, -- or: the other files by name + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + mtl: (string | buffer)?, + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25) } export type EncodeOptions = { - name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl") - mtlName: string?, -- the .mtl file name (overrides name) - files: { [string]: any }?, -- receives the .mtl and embedded textures + name: string?, -- default "model.mtl" + mtlName: string?, + files: { [string]: any }?, flipV: boolean?, -- default true (the inverse of decode) - normals: boolean?, -- write vn (default true when the primitives have NORMAL) - texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0) - colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists) + normals: boolean?, -- default true when the primitives have NORMAL + texcoords: boolean?, -- default true when the primitives have TEXCOORD_0 + colors: boolean?, -- default true when COLOR_0 exists } -- ------------------------------------------------------------------------------------------------ sniff @@ -146,7 +136,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end return p end - -- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil local function corner(tok: string): (number?, number, number) local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") local vi = tonumber(a) @@ -180,7 +169,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E local line = string.sub(text, pos, e - 1) pos = e + 1 lineNo += 1 - -- continuation lines while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do line = string.gsub(line, "\\\r?$", " ") local e2 = string.find(text, "\n", pos, true) or (len + 1) @@ -192,7 +180,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if key == nil or string.sub(key, 1, 1) == "#" then continue end - local rest: string = rest :: string -- both captures match together + local rest: string = rest :: string local hash = string.find(rest, "#", 1, true) if hash then rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") @@ -266,7 +254,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end if mode == "triangles" and k > 3 then - -- fan: rewrite the k corners as (k - 2) triangles local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) local o = base for a = 2, k - 1 do @@ -276,7 +263,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end elseif mode == "lines" then - -- a polyline -> segments local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) local o = base for a = 1, k - 1 do @@ -309,7 +295,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E skipped += 1 end end - -- materials local scene = Types.Scene.new() local matIndex: { [string]: number } = {} local texIndex: { [string]: number } = {} @@ -354,7 +339,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end end - -- materials named by usemtl but not defined anywhere: a default one with the name + -- usemtl of an undefined material: a default one with that name for _, s in sections do for _, p in s.prims do if p.material and not matIndex[p.material] then @@ -364,7 +349,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end end end - -- vertices: one per distinct (v, vt, vn) in each primitive local f32 = buffer.writef32 local KT, KN = nt + 1, nn + 1 local numericKeys = np * KT * KN < 2 ^ 52 @@ -434,7 +418,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end return out end - -- nodes: objects at the root, their groups as children; without objects every group is a root local objectNode: { [string]: number } = {} for _, s in sections do if #s.prims > 0 then @@ -463,7 +446,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E objectNode[s.object] = #scene.nodes table.insert(scene.roots, #scene.nodes) elseif hasObjects and s.object and objectNode[s.object] then - -- the object's own faces after its groups: a child too table.insert(scene.nodes, node) table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes) else @@ -488,7 +470,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- the shortest decimal that reads back as the same f32 local probe = buffer.create(4) local function f32str(v: number): string if v ~= v or v == math.huge or v == -math.huge then @@ -527,7 +508,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err local placed = Types.Scene.flatten(scene) local out = { "# written by rosetta" } local mats = scene.materials or {} - -- material names (unique), texture file names local names: { string } = {} local used: { [string]: boolean } = {} for i, m in mats do @@ -595,7 +575,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") end end - -- the normal matrix (inverse transpose) for baked normals local nm: { number }? = nil if Nr and not ident then local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] @@ -647,7 +626,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end return s end - -- the corner list local ind = prim.indices local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil local count = if ind then ind.count else n @@ -743,7 +721,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end -- ------------------------------------------------------------------------------------------------ extras --- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files) function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) if type(scene) ~= "table" or type(scene.materials) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") diff --git a/src/Rosetta/model/off/init.luau b/src/Rosetta/model/off/init.luau index 8f80995..7a7a025 100644 --- a/src/Rosetta/model/off/init.luau +++ b/src/Rosetta/model/off/init.luau @@ -1,21 +1,7 @@ --!strict --- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description --- (geomview.org/docs/html/OFF.html). --- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the --- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`; --- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8 --- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given). --- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces; --- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are --- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or --- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single --- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points". --- meta.source = { format, keyword, vertices, faces, edges }. --- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes --- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons --- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are --- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF --- (UNSUPPORTED). +-- model/off: Geomview OFF text (geomview.org/docs/html/OFF.html), read + write. Supports: [ST][C][N]OFF, face colours +-- (prim.extras.faceColors), n-gons (fan-triangulated or "polygons"), point clouds; floats as %.9g (f32-exact). +-- Not supported: 4OFF / nOFF, binary OFF; colormap-index face colours are ignored. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -35,15 +21,15 @@ local Off = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + triangulate: boolean?, -- default true maxVertices: number?, -- default 2^24 maxFaces: number?, -- default 2^25 } export type EncodeOptions = { - colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true) - normals: boolean?, -- write NORMAL (NOFF) when present (default true) - texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true) - comment: string?, -- a "# ..." line after the header keyword + colors: boolean?, -- default true + normals: boolean?, -- default true + texcoords: boolean?, -- default true + comment: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -52,7 +38,7 @@ local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writ -- ------------------------------------------------------------------------------------------------ sniff function Off.sniff(r: Bytes.Reader): number local head = r:peek(512) - for _ = 1, 16 do -- leading comment lines + for _ = 1, 16 do local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") if not rest then break @@ -67,14 +53,13 @@ function Off.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32 +-- unorm8 when every value is an integer and some value is above 1, else f32 type ColorSet = { values: { number }, float: boolean, max: number } local function colorType(c: ColorSet): string return if not c.float and c.max > 1 then "unorm8" else "f32" end --- the colour accessor for count entries of 4 values (nan = absent: opaque white) local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?) local t = colorType(c) local buf = buffer.create(count * (if t == "unorm8" then 4 else 16)) @@ -109,7 +94,7 @@ local function addColor(c: ColorSet, toks: { string }, from: number, n: number) c.max = v end else - table.insert(vals, 0 / 0) -- absent: full (opaque white) + table.insert(vals, 0 / 0) end end end @@ -122,7 +107,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E local maxVertices = opts and opts.maxVertices or 2 ^ 24 local maxFaces = opts and opts.maxFaces or 2 ^ 25 local text = buffer.readstring(r.buf, r.base, r.limit - r.base) - -- the next non-empty line's tokens (comments stripped) local at = 1 local lineNo = 0 local function line(): { string }? @@ -188,7 +172,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if nf > maxFaces then return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) end - -- every vertex / face line takes at least 6 / 2 bytes if nv * 6 + nf * 2 > #text - at + 2 then return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") end @@ -273,7 +256,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E addColor(fcol, t, 1, 0) end end - -- the primitive local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } if nrm then attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) @@ -367,7 +349,6 @@ local function fnum(v: number): string? return string.format("%.9g", v) end --- a colour attribute's 4 components of entry i (0-based) as text local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string local out = table.create(4) for c = 1, 4 do @@ -429,7 +410,6 @@ function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end table.insert(out, s) end - -- face colours of a single primitive (per file face, or through faceOfTriangle) local fc: Flatten.Attr? = nil local fcMap: { number }? = nil if wantC and #m.parts == 1 and nf > 0 then diff --git a/src/Rosetta/model/ply/Binary.luau b/src/Rosetta/model/ply/Binary.luau index 5bfdf92..58f8383 100644 --- a/src/Rosetta/model/ply/Binary.luau +++ b/src/Rosetta/model/ply/Binary.luau @@ -1,11 +1,8 @@ --!strict --!native --!optimize 2 --- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, --- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of --- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the --- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list --- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws. +-- model/ply/Binary: PLY element data loops; type codes 1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, 7 f32, 8 f64, either +-- byte order. Never throws: the caller bounds every row first. local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 local readf32, readf64 = buffer.readf32, buffer.readf64 local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 @@ -22,7 +19,6 @@ local function swap16(v: number): number return rshift(v, 8) + band(v, 255) * 256 end --- rd(b, q, code, be) -> the value at q local function rd(b: buffer, q: number, code: number, be: boolean): number if not be then if code == 7 then @@ -63,7 +59,6 @@ local function rd(b: buffer, q: number, code: number, be: boolean): number end Binary.rd = rd --- wr(d, o, code, v): v as code, little endian local function wr(d: buffer, o: number, code: number, v: number) if code == 7 then writef32(d, o, v) @@ -85,7 +80,6 @@ local function wr(d: buffer, o: number, code: number, v: number) end Binary.wr = wr --- put(d, o, code, v, be): v as code in either byte order (the writer) function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) if not be or code <= 2 then wr(d, o, code, v) @@ -102,7 +96,6 @@ function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) end end --- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) for k = 1, np do local sc, dc, d = code[k], dCode[k], dst[k] @@ -135,8 +128,6 @@ function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: numb end end --- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property, --- or -1, message (truncated rows, a negative / fractional count) function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) local totals = table.create(np, 0) local q = p @@ -168,10 +159,6 @@ function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, return q, totals end --- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message. --- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their --- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows --- must have passed scan() with the same arguments. function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) local at = table.create(np, 0) local q = p diff --git a/src/Rosetta/model/ply/init.luau b/src/Rosetta/model/ply/init.luau index f58e82c..56d509b 100644 --- a/src/Rosetta/model/ply/init.luau +++ b/src/Rosetta/model/ply/init.luau @@ -1,24 +1,7 @@ --!strict --- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, --- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). --- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> --- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u --- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> --- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's --- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are --- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are --- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", --- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face --- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after --- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, --- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments --- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and --- types. meta.source = { format, encoding, vertices, faces }. --- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, --- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces --- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when --- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. --- Not supported: list properties in the vertex element (UNSUPPORTED). +-- model/ply: Stanford PLY (Greg Turk 1994; paulbourke.net/dataformats/ply, rply / plyfile behaviour), ascii and +-- binary either endian, read + write. Supports: every property type, faces (fan-triangulated or "polygons"), point +-- clouds; other elements, comments, obj_info and property order round-trip. Not supported: vertex list properties. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -39,13 +22,13 @@ local Ply = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + triangulate: boolean?, -- default true maxVertices: number?, -- default 2^24 maxFaces: number?, -- faces, and rows of any other element (default 2^25) } export type EncodeOptions = { format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" - comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments) + comments: { string }?, } type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } @@ -115,7 +98,6 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) if first then first = false -- "ply" elseif kw == nil then - -- blank line elseif kw == "end_header" then h.dataStart = base + at - 1 break @@ -175,7 +157,6 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) return h, nil end --- the reading plan of one element: per property, where its values go type Plan = { code: { number }, isList: { boolean }, @@ -213,7 +194,6 @@ local function newPlan(e: Elem): Plan return pl end --- unset scalar destinations get their own native buffer local function ownBuffers(e: Elem, pl: Plan) for k, p in e.props do if not p.list and pl.dst[k] == nil then @@ -222,7 +202,6 @@ local function ownBuffers(e: Elem, pl: Plan) end end --- read one element's rows (binary) into the plan; returns the next offset or nil, Err local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) local b, limit, n, np = r.buf, r.limit, e.count, #e.props local hasList, rowSize = false, 0 @@ -267,7 +246,6 @@ local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boo return q, nil end --- a token as a value of type code, or nil local function value(tok: string?, code: number): number? if tok == nil then return nil @@ -283,7 +261,6 @@ local function value(tok: string?, code: number): number? return v end --- read one element's rows (ascii) from the token stream local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? ownBuffers(e, pl) local n = e.count @@ -352,7 +329,6 @@ local function propIndex(e: Elem, name: string): number? return nil end --- vertex element -> attributes: sets the plan's destinations, returns the attribute table local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) local nv = e.count local attrs: { [string]: Types.Accessor } = {} @@ -362,7 +338,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") end end - -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) local ks: { [number]: number } = {} local codes = {} @@ -408,7 +383,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er end group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) - -- colours: one type class for all channels do local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") if rk and gk and bk then @@ -447,7 +421,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er return attrs, nil end --- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) local nt = 0 for f = 0, nf - 1 do @@ -513,7 +486,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end if ascii then local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) - -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating local need = 0 for _, e in h.elems do need += e.count * #e.props @@ -527,7 +499,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E local attrs: { [string]: Types.Accessor } = {} local p = h.dataStart if not ascii then - -- every row takes at least its scalar sizes and list counts: bound the counts before allocating local need = 0 for _, e in h.elems do local row = 0 @@ -566,7 +537,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E p = q end end - -- the primitive local prim: Types.Primitive = { attributes = attrs, mode = "points" } local nf = 0 local extras: { [string]: any } = {} @@ -630,7 +600,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if next(extras) then prim.extras = extras end - -- raw elements, element order, property order local elements: { any } = {} local order: { string } = {} for i, e in h.elems do @@ -662,7 +631,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E end -- ------------------------------------------------------------------------------------------------ encode --- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } @@ -670,7 +638,6 @@ local function keep(name: string): boolean return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" end --- the spelling `want` from the source file when it means the same type as code, else the classic name local function spell(want: string?, code: number): string if want and CODES[want] == code then return want @@ -689,7 +656,6 @@ local function toInt(v: number, code: number): number return v end --- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } local function rowsAscii(out: { string }, n: number, cols: { Row }) @@ -762,7 +728,6 @@ local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean w.pos = o end --- numbers of a raw element column (buffer of a ply type) local function bufNumbers(b: any, code: number, count: number): { number }? if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then return nil @@ -774,7 +739,6 @@ local function bufNumbers(b: any, code: number, count: number): { number }? return out end --- the list count type for a maximum count local function countCodeFor(maxCount: number): number return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 end @@ -791,7 +755,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} local nv = m.count - -- source property spellings / order local srcType: { [string]: string } = {} local srcOrder: { [string]: number } = {} if type(meta.vertexProperties) == "table" then @@ -822,7 +785,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err if C then local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 if C.raw and code == 7 then - -- another normalized type: as floats local vals = table.create(#C.values) local scale = if C.type == "snorm8" then 127 else 32767 for i, v in C.values do @@ -888,7 +850,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end end end - -- the source order first (stable for the rest) local rank: { [Column]: number } = {} for i, c in cols do rank[c] = (srcOrder[c.name] or (1000000 + i)) @@ -896,7 +857,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err table.sort(cols, function(a: Column, b: Column): boolean return rank[a] < rank[b] end) - -- faces local faceRows: { Row }? = nil local nf = 0 if m.sizes then @@ -929,7 +889,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err local rows: { Row } = { { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, } - -- per-face data of a single primitive if #m.parts == 1 then local ex = m.parts[1].prim.extras local fot: { number }? = nil @@ -984,7 +943,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end end end - -- the source order, then the rest by name local placed: { [string]: boolean } = { [idxName] = true } local ordered: { Row } = {} for _, fp in fprops do @@ -1014,7 +972,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end faceRows = rows end - -- raw elements type Raw = { name: string, count: number, rows: { Row } } local raws: { [string]: Raw } = {} local rawOrder: { string } = {} @@ -1057,7 +1014,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end end end - -- element order: the source's, then vertex, face, the rest local order: { string } = {} local seen: { [string]: boolean } = {} local function want(name: string) @@ -1081,7 +1037,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err for _, name in rawOrder do want(name) end - -- header local vrows: { Row } = {} for _, c in cols do table.insert(vrows, { kind = "s" :: "s", col = c }) diff --git a/src/Rosetta/model/pmx/Build.luau b/src/Rosetta/model/pmx/Build.luau index 569398d..15aedfd 100644 --- a/src/Rosetta/model/pmx/Build.luau +++ b/src/Rosetta/model/pmx/Build.luau @@ -1,11 +1,6 @@ --!strict --- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, --- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed --- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with --- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as --- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex --- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative --- translation each) and one skin with translation-only inverse bind matrices. +-- model/pmx/Build: the PMX / PMD model table to a Scene. MMD is left-handed (y up, x right, z forward): z is negated +-- and every winding reversed; UVs are already top-left. local Types = require("@rosetta/Types") local Build = {} @@ -17,7 +12,6 @@ local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } --- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve local function fetcher(opts: any): (string) -> buffer? return function(uri: string): buffer? if not opts then @@ -40,7 +34,6 @@ local function lh(v: { number }?): { number }? return if v then { v[1], v[2], -v[3] } else nil end --- the scene index of a file texture index (0-based, -1 = none) local function texIndex(m: any, i: number?): number? return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil end @@ -73,7 +66,6 @@ local function material(m: any, mat: any): Types.Material return out end --- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root local function parents(bones: { any }): { number } local nb = #bones local par = table.create(nb, 0) @@ -98,7 +90,6 @@ local function parents(bones: { any }): { number } return par end --- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive local map: { [number]: number } = {} local verts: { number } = {} @@ -150,7 +141,6 @@ local function primitive(m: any, first: number, n: number, morphs: { any }, sdef for a, acc in uvas do buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) end - -- weights: invalid bones get weight 0, the rest is normalized local sum = 0 local js, ws = table.create(4, 0), table.create(4, 0) for c = 0, 3 do @@ -217,7 +207,6 @@ function Build.scene(m: any, opts: any): (any, ...any) scene.materials[i] = material(m, mat) end - -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) local vmorphs, names, others = {}, {}, {} local wantMorphs = not (opts and opts.morphs == false) for _, mo in m.morphs do @@ -253,7 +242,6 @@ function Build.scene(m: any, opts: any): (any, ...any) first += n end if first < m.indexCount then - -- faces no material covers table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) end mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil } @@ -262,7 +250,6 @@ function Build.scene(m: any, opts: any): (any, ...any) end scene.meshes[1] = mesh - -- nodes: 1 = the model, 2 = the mesh, then one per bone scene.nodes[1] = { name = m.name, children = { 2 } } scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } scene.roots[1] = 1 diff --git a/src/Rosetta/model/pmx/Pmd.luau b/src/Rosetta/model/pmx/Pmd.luau index 692f369..bcca778 100644 --- a/src/Rosetta/model/pmx/Pmd.luau +++ b/src/Rosetta/model/pmx/Pmd.luau @@ -1,11 +1,6 @@ --!strict --- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as --- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community --- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, --- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to --- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in --- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in --- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +-- model/pmx/Pmd: PMD 1.0, from the MMD community layout notes (MMDAgent / mmd_tools); no third-party code. Names are +-- Shift-JIS: kept when ASCII, else the English name, else the raw bytes (`nameSjis`). Never throws. local Bytes = require("@rosetta/core/Bytes") local Pmd = {} @@ -96,7 +91,7 @@ function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...a r.pos += ni * 2 m.indexCount, m.indices = ni, ind - -- materials: 70 bytes each; texture names collected into the texture list + -- materials: 70 bytes each local nm = r:u32le() ok, e = counted(r, nm, 70, "materials") if r.err or not ok then @@ -159,7 +154,6 @@ function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...a m.bones[i] = b end - -- IK chains local nik = r:u16le() for _ = 1, nik do local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() diff --git a/src/Rosetta/model/pmx/Read.luau b/src/Rosetta/model/pmx/Read.luau index 005b6b5..1dc2a8b 100644 --- a/src/Rosetta/model/pmx/Read.luau +++ b/src/Rosetta/model/pmx/Read.luau @@ -1,11 +1,6 @@ --!strict --- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that --- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. --- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices --- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, --- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, --- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). --- Never throws: returns nil, message[, kind]. +-- model/pmx/Read: PMX 2.0 / 2.1, from the specification notes that ship with PmxEditor; values as in the file +-- (left-handed, 0-based indices); 2.1 soft bodies are counted, not parsed. Never throws. local Bytes = require("@rosetta/core/Bytes") local Text = require("@rosetta/codecs/text/Text") @@ -33,7 +28,7 @@ local function vec(r: Bytes.Reader, n: number): { number } return v end --- a count field: i32 >= 0 and at most remaining / minSize records +-- a count field: i32 >= 0 local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any) local n = r:i32le() if r.err then @@ -206,7 +201,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... r.pos = p + ni * vsize m.indexCount, m.indices = ni, ind - -- textures local nt nt, e, k = count(r, 4, "textures") if not nt then @@ -217,7 +211,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... m.textures[i] = text() end - -- materials local nm nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") if not nm then @@ -242,7 +235,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... m.materials[i] = mat end - -- bones local nb nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") if not nb then @@ -290,7 +282,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... m.bones[i] = b end - -- morphs local nmo nmo, e, k = count(r, 8 + 2 + 4, "morphs") if not nmo then @@ -311,7 +302,7 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ... return nil, e, k end if t == 1 then - -- vertex morphs: packed (index list + deltas), they become morph targets + -- vertex morphs: packed (index list + deltas) local vi, d = table.create(no), buffer.create(no * 12) for o = 1, no do local x = vidx() diff --git a/src/Rosetta/model/pmx/init.luau b/src/Rosetta/model/pmx/init.luau index c398b6e..5321593 100644 --- a/src/Rosetta/model/pmx/init.luau +++ b/src/Rosetta/model/pmx/init.luau @@ -1,17 +1,7 @@ --!strict --- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD --- format, as documented by the MMD community). New code, no third-party code. --- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / --- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / --- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one --- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, --- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon --- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; --- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), --- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras --- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the --- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). --- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. +-- model/pmx: MikuMikuDance PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (MMD community notes); no +-- third-party code. Supports: every deform type, materials, bones and IK, vertex morphs as morph targets, the other +-- morphs, frames, rigid bodies and joints as extras. Not supported: writing, 2.1 soft bodies, VMD / VPD. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,11 +23,11 @@ local Pmx = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name) - resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths) - morphs: boolean?, -- vertex morphs as morph targets (default true) + files: { [string]: any }?, -- "/" or "\" separators, or the base name + resolve: ((uri: string) -> any)?, + morphs: boolean?, -- default true maxVertices: number?, -- default 2^24 - maxBytes: number?, -- morph target bytes (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/model/qb/init.luau b/src/Rosetta/model/qb/init.luau index 8a1dfbd..f2bf092 100644 --- a/src/Rosetta/model/qb/init.luau +++ b/src/Rosetta/model/qb/init.luau @@ -1,15 +1,7 @@ --!strict --- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the --- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA --- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 --- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. --- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as --- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view --- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and --- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). --- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; --- options default to the source file's settings. --- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. +-- model/qb: Qubicle Binary (.qb 1.1.0.0, minddesk.com "Qubicle Binary"), read + write. Supports: RGBA / BGRA, left- or +-- right-handed z, plain or RLE matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 per z slice), the alpha visibility mask, named +-- matrices with a position. Not supported: Qubicle Exchange (.qbt / .qbcl). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,13 +20,13 @@ local Qb = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27) + maxCells: number?, -- default 2^27 } export type EncodeOptions = { - compressed: boolean?, -- run-length compress the matrices (default: the source's, else true) + compressed: boolean?, -- default: the source's, else true colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba" - rightHanded: boolean?, -- the z axis orientation (default: the source's, else true) - visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false) + rightHanded: boolean?, -- default: the source's, else true + visibilityMask: boolean?, -- default: the source's, else false } -- ------------------------------------------------------------------------------------------------ constants @@ -56,7 +48,6 @@ function Qb.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them local function indexed(v: Types.Voxels, colors: buffer, n: number) local count: { [number]: number } = {} for i = 0, n - 1 do @@ -337,7 +328,6 @@ function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 end - -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked local function value(x: number, y: number, z: number): number local zz = if right then z else sz - 1 - z local c = cellColor(v, x + sx * (y + sy * zz)) diff --git a/src/Rosetta/model/rbxm/init.luau b/src/Rosetta/model/rbxm/init.luau index d8a57a7..5cbaab4 100644 --- a/src/Rosetta/model/rbxm/init.luau +++ b/src/Rosetta/model/rbxm/init.luau @@ -1,15 +1,7 @@ --!strict --- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, " "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks +-- an INST chunk that marks services makes a place function Rbxm.variant(r: Bytes.Reader): string? local b, p, e = r.buf, r.base + 32, r.limit if r:peek(14) ~= MAGIC then @@ -83,7 +75,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Class = { id: number, name: string, refs: { number }, service: boolean } --- a length-prefixed string at p of b (limit e): string, next | nil local function str(b: buffer, p: number, e: number): (string?, number) if p + 4 > e then return nil, p @@ -292,7 +283,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err return nil, Err.new(Err.CORRUPT, "an instance with two parents", at) end parented[child] = true - -- refuse cycles: the parent may not be a descendant of the child local up: Rbx.Instance? = parent while up do if up == child then @@ -311,7 +301,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err if not ended then return nil, Err.new(Err.TRUNCATED, "no END chunk", limit) end - -- instances PRNT does not mention are roots for _, inst in order do if not parented[inst] then table.insert(tree.roots, inst) @@ -329,7 +318,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err end -- ------------------------------------------------------------------------------------------------ encode --- the binary type of a property over a class's instances: type id, type name | nil, message local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?) local id, tname = nil, nil for _, inst in insts do @@ -381,7 +369,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local compress = o.compression ~= "none" local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true - -- every instance depth first; referents in that order local insts: { Rbx.Instance } = {} local refOf: { [any]: number } = {} local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {} @@ -409,7 +396,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, e end end - -- classes by name local byClass: { [string]: { Rbx.Instance } } = {} local names = {} for _, inst in insts do @@ -422,7 +408,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) table.insert(list, inst) end table.sort(names) - -- shared strings, in order of first use local sharedIdx: { [string]: number } = {} local sharedList: { string } = {} local ctx: Binary.Ctx = { @@ -497,7 +482,7 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) putStr(pw, pn) local tid = t :: number if tid == -1 then - -- Raw: the column read from a file, written back only when this class still has exactly its instances + -- Raw: written back only when this class still has exactly its instances local first = list[1].properties[pn] local raw = first and first.value local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer" diff --git a/src/Rosetta/model/rbxmx/init.luau b/src/Rosetta/model/rbxmx/init.luau index d6b3742..7dbcdc5 100644 --- a/src/Rosetta/model/rbxmx/init.luau +++ b/src/Rosetta/model/rbxmx/init.luau @@ -1,18 +1,8 @@ --!strict --- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, ``), read + write, to and from --- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save). --- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. --- Decode: , with of every type codecs/model/Rbx lists (string, BinaryString --- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN), --- token, BrickColor (as rbx-dom: an ; read back as BrickColor for the BrickColor properties of a short --- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame, --- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange, --- PhysicalProperties, Ref, SharedString (+ ), UniqueId, Font, SecurityCapabilities); unknown property --- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra. --- tree.place is true when a root is a Workspace (rbxlx). --- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent, --- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control --- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped. +-- model/rbxmx: Roblox XML model / place (.rbxmx / .rbxlx, ``) to and from a codecs/model/Rbx +-- RbxTree, from the rbx-dom notes (docs/xml.md), checked against rojo 7.7 and lune 0.11. Supports: every type +-- codecs/model/Rbx lists; unknown tags round-trip as "XmlRaw". Encode follows rbx-dom's layout. +-- Not supported: writing "Raw" values. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,17 +24,16 @@ local Rbxmx = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxDepth: number?, -- XML nesting limit (default 10000) + maxDepth: number?, -- default 10000 } export type EncodeOptions = { - indent: (number | string)?, -- default 2 spaces; 0 for none + indent: (number | string)?, -- default 2; 0 for none } -- ------------------------------------------------------------------------------------------------ constants local XmlNode = Xml.element local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch --- tag name -> type name for the simple (text) types local SCALAR_TAGS: { [string]: string } = { string = "String", ProtectedString = "ProtectedString", @@ -81,7 +70,7 @@ function Rbxmx.sniff(r: Bytes.Reader): number return 0 end --- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect) +-- a Workspace item makes a place function Rbxmx.variant(r: Bytes.Reader): string? local text = buffer.readstring(r.buf, r.base, r.limit - r.base) return if find(text, ' type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs --- come back as { pending = referent }) local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) local tag = node.name local scalar = SCALAR_TAGS[tag] @@ -298,7 +285,6 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er end local tree = Rbx.tree() tree.meta.source = { format = "rbxmx", version = root.attrs.version } - -- shared strings first (properties name them by key) local shared: { [string]: string } = {} for _, ss in Xml.children(root, "SharedStrings") do for _, s in Xml.children(ss, "SharedString") do @@ -310,7 +296,7 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er end end local byRef: { [string]: Rbx.Instance } = {} - local pending: { { any } } = {} -- { value table, field, referent } + local pending: { { any } } = {} local function item(node: Xml.Node, parent: any): Err.Err? local cls = node.attrs.class if type(cls) ~= "string" then @@ -381,7 +367,6 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er end -- ------------------------------------------------------------------------------------------------ encode --- the shortest text that reads back as the same float (single: f32 values; else f64) local function fmt(v: any, single: boolean?): string if type(v) ~= "number" then v = 0 @@ -435,7 +420,6 @@ local function xmlSafe(s: string): boolean return utf8.len(s) ~= nil end --- a property -> its element, or nil to skip local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node? local t, x = v.type, v.value local a = { name = name } diff --git a/src/Rosetta/model/robloxmesh/Parse.luau b/src/Rosetta/model/robloxmesh/Parse.luau index 85ab0c6..f9de7dd 100644 --- a/src/Rosetta/model/robloxmesh/Parse.luau +++ b/src/Rosetta/model/robloxmesh/Parse.luau @@ -1,10 +1,8 @@ --!strict --!native --!optimize 2 --- model/robloxmesh/Parse: Roblox FileMesh bytes to a flat record (the file's arrays as packed buffers), for every version: --- 1.00 / 1.01 (ASCII), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, skinning, subsets), 5.00 (+ FACS) and the --- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 through the lim.core --- callback). Written from MaximumADHD's "Roblox Mesh Format" notes (devforum 326114). Little endian. Returns nil, message on bad data. +-- model/robloxmesh/Parse: FileMesh bytes to a flat record, little endian, 1.00 - 7.00 (MaximumADHD's "Roblox Mesh +-- Format", devforum 326114); a Draco COREMESH v2 goes through the lim.core callback. Never throws. local Parse = {} local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring @@ -34,8 +32,6 @@ export type Record = { coreVersion: number?, -- 6.00+: 2 when the COREMESH was Draco-compressed } --- core: decodes a Draco-compressed COREMESH (v2) body at (b, off, len) into the vertex / face fields of a Record --- (numVerts, pos, nrm, uv, tan?, col?, numFaces, faces); the format's init passes it (codecs/model/Draco) export type Core = { numVerts: number, pos: buffer, nrm: buffer, uv: buffer, tan: buffer?, col: buffer?, numFaces: number, faces: buffer } export type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: number, len: number) -> (Core?, string?))? } @@ -116,7 +112,7 @@ local function ascii(text: string, version: string, lim: Limits): (Record?, stri end -- ------------------------------------------------------------------------------------------------ binary parts --- vertices of size vs (36 / 40) at p +-- vertices of 36 / 40 bytes local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) local col = if vs >= 40 then buffer.create(n * 4) else nil @@ -423,7 +419,6 @@ local function chunked(b: buffer, p: number, e: number, version: string, lim: Li return r, nil end --- parse(b, p, e, lim) -> Record | nil, message function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) if e - p < 13 then return nil, "truncated: no version line" @@ -448,7 +443,7 @@ function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, st return nil, "unsupported: version " .. version end --- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127) +-- packed tangent: signed bytes / 127 local function snorm(v: number): number local x = if v >= 128 then v - 256 else v return math.clamp(x / 127, -1, 1) diff --git a/src/Rosetta/model/robloxmesh/Write.luau b/src/Rosetta/model/robloxmesh/Write.luau index fe48f01..737eece 100644 --- a/src/Rosetta/model/robloxmesh/Write.luau +++ b/src/Rosetta/model/robloxmesh/Write.luau @@ -1,9 +1,8 @@ --!strict --!native --!optimize 2 --- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00: --- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning --- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws. +-- model/robloxmesh/Write: a flat record to FileMesh 2.00 (header, 36- or 40-byte vertices, faces) or 4.00 (24-byte +-- header, 40-byte vertices, skinning, faces, LOD offsets, bones, bone names, subsets). Never throws. local Parse = require("@rosetta/model/robloxmesh/Parse") local Bytes = require("@rosetta/core/Bytes") @@ -30,7 +29,6 @@ local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boole w.pos = p + (if colors then 40 else 36) end --- write(r, version) -> buffer ("2.00" | "4.00") function Write.write(r: Parse.Record, version: string): buffer local nv, nf = r.numVerts, r.numFaces local w = Bytes.writer(64 + nv * 48 + nf * 12) diff --git a/src/Rosetta/model/robloxmesh/init.luau b/src/Rosetta/model/robloxmesh/init.luau index ed8a749..41a1f40 100644 --- a/src/Rosetta/model/robloxmesh/init.luau +++ b/src/Rosetta/model/robloxmesh/init.luau @@ -1,22 +1,7 @@ --!strict --- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh --- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port. --- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, --- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown --- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2: a u32 size, then the Draco stream) decodes --- through codecs/model/Draco: its POSITION / NORMAL / TEX_COORD / COLOR attributes and a 4-component TANGENT or GENERIC --- one as the tangents (meta.source.draco = true). One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed --- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in --- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files' --- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes --- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw --- (meta.source.facs). meta.up = "y"; units are studs. --- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every --- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes --- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to --- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive). --- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing --- 3.00 / 5.00+ / FACS. +-- model/robloxmesh: Roblox FileMesh (.mesh), from MaximumADHD's "Roblox Mesh Format" (devforum.roblox.com/t/326114); no +-- port. Supports: reading 1.00 - 7.00 (Draco COREMESH v2 through codecs/model/Draco), writing 2.00 and 4.00. Not +-- supported: writing 3.00 / 5.00+ / FACS; FACS and HSRAVIS are kept raw. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -69,7 +54,6 @@ local function indices(r: Parse.Record, from: number, to: number): Types.Accesso return accessor(d, "u32", 1, n * 3) end --- a Draco-compressed COREMESH body -> the record's vertex / face fields local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, string?) -- the stream follows a u32 byte count (accepted without it too) if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then @@ -95,7 +79,6 @@ local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, str if not pos or pos.components < 3 then return nil, "corrupt: Draco COREMESH without positions" end - -- an attribute's values as numbers (normalized integers as -1..1 / 0..1) local function getter(a: Draco.Attribute): (number, number) -> number local t = if a.normalized then (({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) :: any)[a.type] or a.type else a.type local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n }) @@ -163,7 +146,7 @@ local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, str }, nil end --- Parse is native: nothing may throw through it, so the callback never does +-- Parse is native: nothing may throw through it local function safeCore(b: buffer, off: number, len: number): (Parse.Core?, string?) local ok, c, err = pcall(dracoCore, b, off, len) if not ok then @@ -199,7 +182,6 @@ function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene if r.col then attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) end - -- LOD ranges (offsets clamped to the faces) local offs = {} for _, o in r.lods do table.insert(offs, math.clamp(o, 0, nf)) @@ -220,7 +202,6 @@ function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene scene.meshes[1] = mesh scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } scene.roots[1] = 1 - -- bones and skinning local nb = #r.bones if nb > 0 then local world: { { number } } = table.create(nb) :: any @@ -306,7 +287,6 @@ local function num(attr: any, i: number, c: number, default: number): number return attr.values[i * attr.components + c + 1] end --- area-weighted vertex normals local function normals(pos: buffer, nv: number, corners: { number }): buffer local acc = table.create(nv * 3, 0) for f = 0, #corners // 3 - 1 do @@ -336,7 +316,6 @@ local function normals(pos: buffer, nv: number, corners: { number }): buffer return out end --- world matrices of every node (parents through children lists) local function worlds(scene: any): { [number]: { number } } local out: { [number]: { number } } = {} local parent: { [number]: number } = {} @@ -363,7 +342,6 @@ local function worlds(scene: any): { [number]: { number } } return out end --- the bones of a skin: Parse.Bone list, or nil, message local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) local joints = skin.joints if type(joints) ~= "table" or #joints == 0 then @@ -410,7 +388,6 @@ local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) return out, nil end --- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index) local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?) local nv = #order local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) @@ -502,7 +479,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, if src and type(src.lodType) == "number" then r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0 end - -- normals when the scene has none local nrm: buffer? = nil if not m.attrs.NORMAL then local pb = buffer.create(nv0 * 12) @@ -513,7 +489,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, end nrm = normals(pb, nv0, corners) end - -- the skin (4.00): the first node with a mesh and a skin local skin = nil if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then for _, n in scene.nodes or {} do @@ -533,7 +508,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 local wscale = if W.raw then 1 / 255 else 1 local nb = #bones - -- per vertex: up to 4 (joint, weight) pairs with weight > 0 local influences: { { { number } } } = table.create(nv0) :: any for v = 0, nv0 - 1 do local list = {} @@ -546,7 +520,7 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, end influences[v + 1] = list end - -- subsets: faces in order, a new subset when a face's joints do not fit in 26 + -- subsets: a new subset when a face's joints do not fit in 26 local faceIdx = buffer.create(nf * 12) local order: { number } = {} local s: any = nil @@ -646,7 +620,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, end r.faces = faces r.lods = { 0, nf } - -- extra LODs of a single untransformed primitive local part = m.parts[1] local mesh = part and part.mesh local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil diff --git a/src/Rosetta/model/schematic/Common.luau b/src/Rosetta/model/schematic/Common.luau index 50f7909..3085375 100644 --- a/src/Rosetta/model/schematic/Common.luau +++ b/src/Rosetta/model/schematic/Common.luau @@ -1,28 +1,25 @@ --!strict --- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from, --- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's, --- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). +-- model/schematic/Common: shared region record, NBT access and block entities as Sponge v3's { pos = { x, y, z }, id, +-- data } (MCEdit / Litematica use flat { x, y, z, id, ... }, Sponge v2 { Pos, Id, ... }). local Types = require("@rosetta/Types") local Nbt = require("@rosetta/codecs/text/Nbt") local Mc = require("@rosetta/codecs/model/Minecraft") local Common = {} --- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states +-- a block region: u16 indices per cell in Types.Voxels order (x fastest, then y, then z) into states export type Region = { name: string?, - size: { number }, -- x, y, z cells - position: { number }, -- the minimum corner relative to the schematic origin + size: { number }, + position: { number }, -- relative to the schematic origin states: { string }, indices: buffer, blockEntities: { any }, entities: { any }, } --- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil Common.int = Mc.int --- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) local x, y, z = Common.int(a), Common.int(b), Common.int(c) if not x or not y or not z then @@ -37,14 +34,11 @@ function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number return x, y, z end --- ints(v) -> the numbers of an intArray tag or a list of numbers | nil Common.ints = Mc.ints --- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca) Common.blockEntity = Mc.blockEntity Common.flatBlockEntity = Mc.flatBlockEntity --- list(v) -> v when it is an NBT list (array), else an empty list function Common.list(v: any): { any } if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then return v @@ -52,7 +46,6 @@ function Common.list(v: any): { any } return {} end --- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped) function Common.compound(fields: { { any } }): { [string]: any } local o, keys = {}, {} for _, kv in fields do @@ -64,8 +57,6 @@ function Common.compound(fields: { { any } }): { [string]: any } return Types.object(o, keys) end --- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key --- order (a decoded source compound: its other keys are kept, except those in drop), new keys after function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any } if type(base) ~= "table" or not Types.isObject(base) then return Common.compound(fields) @@ -98,7 +89,6 @@ function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean return Common.compound(out) end --- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed) function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer) local first: { [string]: number } = {} local remap: { number } = {} diff --git a/src/Rosetta/model/schematic/Litematic.luau b/src/Rosetta/model/schematic/Litematic.luau index ea76119..5e0fda1 100644 --- a/src/Rosetta/model/schematic/Litematic.luau +++ b/src/Rosetta/model/schematic/Litematic.luau @@ -1,9 +1,7 @@ --!strict --- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic, --- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size, --- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state --- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative --- to the region's minimum corner), Entities and pending ticks (kept as they are). +-- model/schematic/Litematic: .litematic, from LitematicaSchematic / LitematicaBitArray as documented by litemapy: +-- Metadata, named Regions (Position, Size may be negative), palette (0 = air), BlockStates spanning longs (>= 2 bits), +-- TileEntities relative to the region's minimum corner, Entities and pending ticks. local Types = require("@rosetta/Types") local Nbt = require("@rosetta/codecs/text/Nbt") local Mc = require("@rosetta/codecs/model/Minecraft") @@ -28,7 +26,6 @@ local function vec(v: { number }): any return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) end --- read(root, maxCells) -> { Region }, extra | nil, message function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) if not Types.isObject(root.Regions) then return nil, "no Regions" @@ -106,8 +103,6 @@ function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) } end --- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root --- (Metadata fields and each region's Position / Size signs and pending ticks are kept) function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?) local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil local regs, order = {}, {} @@ -163,7 +158,6 @@ function Litematic.write(regions: { Common.Region }, version: number, dataVersio local b = if baseRegions then baseRegions[name] else nil local bsize = if type(b) == "table" then xyz(b.Size) else nil if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then - -- keep the source's corner and signs for k = 1, 3 do if bsize[k] < 0 then size[k] = bsize[k] diff --git a/src/Rosetta/model/schematic/Mcedit.luau b/src/Rosetta/model/schematic/Mcedit.luau index 19ee8a6..dad64cd 100644 --- a/src/Rosetta/model/schematic/Mcedit.luau +++ b/src/Rosetta/model/schematic/Mcedit.luau @@ -1,10 +1,7 @@ --!strict --- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki --- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high --- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name --- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft --- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block --- nearest in colour). +-- model/schematic/Mcedit: MCEdit / WorldEdit .schematic (pre-1.13; Minecraft wiki "Schematic file format"): Width / +-- Height / Length, Blocks + Data (+ AddBlocks high nibbles, high nibble first), Materials = "Alpha", TileEntities, +-- Entities, WEOffset*, and the SchematicaMapping / BlockIDs name tables of Schematica and MCEdit-Unified. local Types = require("@rosetta/Types") local Nbt = require("@rosetta/codecs/text/Nbt") local Mc = require("@rosetta/codecs/model/Minecraft") @@ -14,7 +11,6 @@ local Mcedit = {} local Packed = Mc.Packed --- read(root, maxCells) -> { Region }, extra | nil, message function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) local blocks = root.Blocks if type(blocks) ~= "buffer" then @@ -152,15 +148,12 @@ local function nearest(state: string): (number, number) return bid, bd end --- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other --- fields are kept function Mcedit.write(r: Common.Region, base: any): (any, string?) local sx, sy, sz = r.size[1], r.size[2], r.size[3] if sx > 65535 or sy > 65535 or sz > 65535 then return nil, "a .schematic is at most 65535 cells on each axis" end local n = sx * sy * sz - -- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list local map: { [string]: number } = {} if type(base) == "table" then if Types.isObject(base.SchematicaMapping) then diff --git a/src/Rosetta/model/schematic/Sponge.luau b/src/Rosetta/model/schematic/Sponge.luau index a2f0d98..035d6c5 100644 --- a/src/Rosetta/model/schematic/Sponge.luau +++ b/src/Rosetta/model/schematic/Sponge.luau @@ -1,8 +1,7 @@ --!strict --- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the --- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the --- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities / --- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +-- model/schematic/Sponge: .schem (WorldEdit 7+, FAWE, Amulet), from SpongePowered/Schematic-Specification v1-3: Width / +-- Height / Length, Offset, Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities +-- (TileEntities / BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. local Types = require("@rosetta/Types") local Nbt = require("@rosetta/codecs/text/Nbt") local Mc = require("@rosetta/codecs/model/Minecraft") @@ -12,7 +11,6 @@ local Sponge = {} local Packed = Mc.Packed --- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child) function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) local version = Common.int(s.Version) or 1 local function u16(v: any): any @@ -81,8 +79,6 @@ function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } end --- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, --- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?) local sx, sy, sz = r.size[1], r.size[2], r.size[3] if sx > 65535 or sy > 65535 or sz > 65535 then diff --git a/src/Rosetta/model/schematic/init.luau b/src/Rosetta/model/schematic/init.luau index 70b5235..d859f9e 100644 --- a/src/Rosetta/model/schematic/init.luau +++ b/src/Rosetta/model/schematic/init.luau @@ -1,19 +1,7 @@ --!strict --- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3: --- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and --- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit, --- Sponge, Litematic. --- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic --- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as --- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation = --- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the --- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt). --- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's) --- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour, --- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the --- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same. --- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with --- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid). +-- model/schematic: Minecraft schematics, read + write: MCEdit / WorldEdit .schematic (pre-1.13), Sponge .schem v1-3 +-- (WorldEdit 7+) and Litematica .litematic. Not supported: block properties to pre-1.13 data values, Sponge biome +-- conversion between versions, rotated nodes. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -38,18 +26,18 @@ local Schematic = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxCells: number?, -- refuse schematics with more cells in total (default 2^26) - maxBytes: number?, -- refuse NBT that inflates past this (default 2^28) + maxCells: number?, -- default 2^26 + maxBytes: number?, -- default 2^28 } export type EncodeOptions = { variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem" - version: number?, -- Sponge 1 / 2 / 3 (default 3, or the source's), Litematica version (default 6, or the source's) - dataVersion: number?, -- Minecraft's DataVersion (default the source's, else 3953 = 1.21) - name: string?, -- the file name (its extension picks the variant); for .litematic also the default Metadata.Name - title: string?, -- .litematic Metadata.Name + version: number?, -- Sponge default 3, Litematica default 6 (or the source's) + dataVersion: number?, -- default the source's, else 3953 = 1.21 + name: string?, + title: string?, compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them - level: number?, -- deflate level - format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...) + level: number?, + format: string?, } -- ------------------------------------------------------------------------------------------------ constants @@ -79,7 +67,6 @@ function Schematic.sniff(r: Bytes.Reader): number return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0 end --- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes) function Schematic.variant(r: Bytes.Reader): string? local p = Nbt.peek(r.buf, r.base, r.limit - r.base) if not p then @@ -98,7 +85,6 @@ function Schematic.variant(r: Bytes.Reader): string? end -- ------------------------------------------------------------------------------------------------ decode --- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil local function variantOf(root: any): (string?, any) if type(root) ~= "table" or not Types.isObject(root) then return nil, nil @@ -233,7 +219,6 @@ local function regionsOf(value: any): ({ Common.Region }?, string?) return out, nil end --- merge(regions) -> one region covering them all (air where none is) local function merge(regions: { Common.Region }): Common.Region if #regions == 1 then return regions[1] diff --git a/src/Rosetta/model/smd/Read.luau b/src/Rosetta/model/smd/Read.luau index 4ad24a7..05560a5 100644 --- a/src/Rosetta/model/smd/Read.luau +++ b/src/Rosetta/model/smd/Read.luau @@ -1,12 +1,7 @@ --!strict --- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id, --- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone --- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px --- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted). --- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material --- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links, --- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond --- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation. +-- model/smd/Read: sections "nodes" (id, "name", parent), "skeleton" ("time n", "bone px py pz rx ry rz", Euler radians, +-- R = Rz Ry Rx; a bone missing from a later frame keeps its pose), "triangles" (a material line, then "bone px py pz +-- nx ny nz u v [links (bone weight)...]", model space, v up; the rest of the weight goes to the parent bone). local Types = require("@rosetta/Types") local Rig = require("@rosetta/codecs/model/Rig") @@ -20,7 +15,6 @@ export type Options = { fps: number?, name: string?, maxVertices: number? } type Bone = { id: number, name: string, parent: number } local ZERO: { number } = { 0, 0, 0, 0, 0, 0 } --- read(text, opts) -> Scene | nil, message function Read.read(text: string, opts: Options?): (Types.Scene?, string?) local lines: { string } = {} for line in string.gmatch(text, "[^\r\n]*") do @@ -177,7 +171,7 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?) local root: Types.Node = { name = opts and opts.name or "smd", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 - -- skeleton (bind pose: the first frame) + -- bind pose: the first frame local joints: { Rig.Joint } = {} local bind: { [number]: { number } } = frames[1] or {} for k, bn in bones do @@ -186,7 +180,6 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?) joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } end local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) - -- meshes if #batches > 0 then local mesh: Types.Mesh = { primitives = {} } for _, b in batches do @@ -244,7 +237,6 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?) table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil }) table.insert(root.children, #scene.nodes) end - -- animation if #frames > 1 or (#frames == 1 and #batches == 0) then local fps = opts and opts.fps or 30 local t: { number } = {} diff --git a/src/Rosetta/model/smd/Write.luau b/src/Rosetta/model/smd/Write.luau index 0a75ea1..5ff02e8 100644 --- a/src/Rosetta/model/smd/Write.luau +++ b/src/Rosetta/model/smd/Write.luau @@ -1,12 +1,6 @@ --!strict --- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node --- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose --- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled --- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every --- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material --- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the --- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless --- opts.triangles is true. +-- model/smd/Write: Scene -> SMD version 1: the first skin's joints (or one "root" bone), the bind pose or a sampled +-- animation, world-space triangles with Source links (GoldSrc style: the strongest joint as the parent bone only). local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Flatten = require("@rosetta/codecs/model/MeshFlatten") @@ -52,7 +46,6 @@ local function lerp(a: { number }, b: { number }, t: number): { number } return out end --- the value of channel ch at time tm (nil when the channel has no keys) local function sample(ch: Types.Channel, tm: number): { number }? local input, output = ch.input, ch.output local n = input.count @@ -91,7 +84,6 @@ local function sample(ch: Types.Channel, tm: number): { number }? return key(n - 1) end --- write(scene, opts) -> text | nil, message function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) if type(scene) ~= "table" or scene.kind ~= "scene" then return nil, "expected a Scene" @@ -179,7 +171,6 @@ function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) end end table.insert(out, "end") - -- triangles if not anim or (opts and opts.triangles) then local m, err = Flatten.merge(scene, function(name: string): boolean return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" diff --git a/src/Rosetta/model/smd/init.luau b/src/Rosetta/model/smd/init.luau index 745c07f..c59a92b 100644 --- a/src/Rosetta/model/smd/init.luau +++ b/src/Rosetta/model/smd/init.luau @@ -1,10 +1,6 @@ --!strict --- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the --- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a --- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation --- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation, --- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up. --- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations). +-- model/smd: Valve SMD (studiomdl "version 1" text, GoldSrc and Source), from the Valve Developer Community "SMD file +-- format" page; no code taken. Units as stored (inches in Valve's games), z up. Not supported: vertex animation (flex). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,8 +22,8 @@ local Smd = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - fps: number?, -- skeleton frames per second (default 30) - name: string?, -- the root node / animation name (the api passes the file name) + fps: number?, -- default 30 + name: string?, maxVertices: number?, -- default 2^24 } export type EncodeOptions = Write.Options diff --git a/src/Rosetta/model/stl/Decode.luau b/src/Rosetta/model/stl/Decode.luau index d99ad3c..61b856e 100644 --- a/src/Rosetta/model/stl/Decode.luau +++ b/src/Rosetta/model/stl/Decode.luau @@ -1,16 +1,13 @@ --!strict --!native --!optimize 2 --- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5 --- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that --- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws. +-- model/stl/Decode: binary STL facets (50 bytes: normal, 3 vertices, u16 attribute) and the 5-5-5 colours of VisCAM / +-- SolidView and Materialise Magics. Never throws: the caller bounds the facets first. local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift local Decode = {} --- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into --- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes). function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number local any = 0 for i = 0, n - 1 do @@ -42,14 +39,12 @@ function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer return any end --- 5-bit -> 8-bit, rounded local function x8(v: number): number return (v * 255 + 15) // 31 end --- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid, --- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour, --- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a). +-- VisCAM: bit 15 set = valid, red in bits 10..14, blue in 0..4. Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14. function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) for i = 0, n - 1 do local w = readu16(attr, i * 2) diff --git a/src/Rosetta/model/stl/init.luau b/src/Rosetta/model/stl/init.luau index aeb39ed..a15ad73 100644 --- a/src/Rosetta/model/stl/init.luau +++ b/src/Rosetta/model/stl/init.luau @@ -1,20 +1,7 @@ --!strict --- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description --- (Wikipedia "STL (file format)" and the 3D Systems SLC spec). --- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the --- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView: --- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the --- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in --- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly --- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in --- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final --- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material, --- solids, facets }. --- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans --- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after --- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle --- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either --- convention. Not supported: binary-only extensions other than the two colour conventions. +-- model/stl: STL (3D Systems; Wikipedia "STL (file format)", the SLC spec), ASCII and binary, read + write. Supports: +-- the VisCAM / SolidView and Materialise Magics colour conventions, a binary file starting with "solid" (size exactly +-- 84 + 50 * count), several ASCII solids. Not supported: other binary attribute extensions. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -35,18 +22,16 @@ local Stl = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxFaces: number?, -- refuse more facets (default 2^25) - colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the - -- header = magics, else any attribute with bit 15 set = viscam, else none) + maxFaces: number?, -- default 2^25 + colors: ("auto" | "viscam" | "magics" | "none")?, -- default "auto": "COLOR=" = magics, else bit 15 = viscam } export type EncodeOptions = { ascii: boolean?, -- default false (binary) - colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only) - defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly - -- that colour refer to it, the others carry their own (alpha 255) - name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh") - header: string?, -- the binary header text (at most 80 bytes; default "rosetta STL") - normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL + colors: ("viscam" | "magics")?, -- binary only + defaultColor: { number }?, -- magics object colour, 0..255 (default opaque white) + name: string?, -- default: the mesh / node name, else "mesh" + header: string?, -- at most 80 bytes; default "rosetta STL" + normals: ("compute" | "attribute")?, -- default: from the triangle } -- ------------------------------------------------------------------------------------------------ constants @@ -290,7 +275,7 @@ function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if size < 84 then return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) end - -- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED) + -- extra bytes after the facets are tolerated return decodeBinary(r, maxFaces, colors) end @@ -301,7 +286,6 @@ local function f32(v: number): number return buffer.readf32(scratch, 0) end --- a COLOR_0 component as 0..255 local function byte(a: Flatten.Attr, v: number): number if a.raw then if a.type == "unorm16" then @@ -341,7 +325,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err local C = m.attrs.COLOR_0 local corners = m.corners local nf = #corners // 3 - -- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based) local function normal(f: number): (number, number, number) local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] if N then @@ -403,7 +386,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end return buffer.fromstring(table.concat(out)), nil end - -- binary local buf = buffer.create(84 + 50 * nf) local header = o.header or "rosetta STL" if colors == "magics" then @@ -420,7 +402,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err end buffer.writestring(buf, 0, header) writeu32(buf, 80, nf) - -- the attribute words: colours, or the raw words of a single STL-decoded primitive local rawAttr: { number }? = nil if colors == nil and #m.parts == 1 then local ex = m.parts[1].prim.extras diff --git a/src/Rosetta/model/usda/Build.luau b/src/Rosetta/model/usda/Build.luau index 35141aa..521375f 100644 --- a/src/Rosetta/model/usda/Build.luau +++ b/src/Rosetta/model/usda/Build.luau @@ -1,22 +1,7 @@ --!strict --- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux --- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped; --- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh --- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight / --- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim. --- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the --- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local --- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond); --- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f / --- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor --- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every --- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated --- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed. --- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with --- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d -> --- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets). --- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in --- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +-- model/usda/Build: a USDA layer to a Scene, following the UsdGeom / UsdShade / UsdLux schemas (OpenUSD 26.x). Other +-- attributes than xform ops use their earliest sample (as UsdTimeCode.EarliestTime()). Not supported: composition arcs, +-- UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Parse = require("@rosetta/model/usda/Parse") @@ -53,7 +38,6 @@ local function str(v: any): string? end return nil end --- a tuple / scalar -> numbers (nil when not numeric) local function nums(v: any): { number }? if type(v) == "number" then return { v } @@ -90,7 +74,7 @@ local function num(v: any): number? return nil end --- the value of a property: its default, else its earliest time sample +-- a property's default, else its earliest time sample local function propValue(p: Prop?): any if not p then return nil @@ -117,7 +101,6 @@ local function joinPath(parent: string, name: string): string return if parent == "/" then "/" .. name else parent .. "/" .. name end --- resolve a (possibly relative) Sdf path against the prim path that holds it local function resolvePath(base: string, p: string): string if string.sub(p, 1, 1) == "/" then return p @@ -138,7 +121,6 @@ local function resolvePath(base: string, p: string): string end return "/" .. table.concat(out, "/") end --- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb" local function splitProp(p: string): (string, string?) local prim, prop = string.match(p, "^(.-)%.([^/]+)$") if prim and prop then @@ -161,7 +143,6 @@ end -- ------------------------------------------------------------------------------------------------ xform ops type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } --- the op stack of a prim: ops in xformOpOrder, resetXformStack local function xformOps(p: Prim): ({ Op }, boolean) local order = p.props.xformOpOrder local list = order and propValue(order) @@ -193,7 +174,6 @@ local function xformOps(p: Prim): ({ Op }, boolean) end local AXIS = { X = 1, Y = 2, Z = 3 } --- the matrix of one op for a value local function opMatrix(op: Op, v: any): { number }? local n = nums(v) if not n then @@ -217,7 +197,7 @@ local function opMatrix(op: Op, v: any): { number }? elseif k == "rotate" and op.axes then local axes = op.axes :: string local r: { number } = Types.Scene.IDENTITY :: any - -- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles + -- rotateXZY: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles for c = 1, #axes do local a = AXIS[string.sub(axes, c, c)] local angle = if #axes == 1 then n[1] or 0 else n[a] or 0 @@ -240,7 +220,6 @@ local function lerpValue(a: any, b: any, f: number, quat: boolean): any end local out = table.create(#na) if quat and #na == 4 then - -- (w, x, y, z): slerp through nlerp with the short path local dot = 0 for k = 1, 4 do dot += na[k] * nb[k] @@ -257,7 +236,7 @@ local function lerpValue(a: any, b: any, f: number, quat: boolean): any return { t = "tuple", v = out } end --- an op's value at time code t (samples interpolated linearly, held outside their range) +-- samples interpolated linearly, held outside their range local function opValueAt(op: Op, t: number?): any local p = op.prop local s = p.samples @@ -309,7 +288,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local unsupported: { [string]: boolean } = {} local meta = layer.meta - -- prim index (variants merged), paths local byPath: { [string]: Prim } = {} local parentOf: { [Prim]: string } = {} local pathOf: { [Prim]: string } = {} @@ -360,7 +338,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) parentOf[p] = parent local existing = byPath[path] if existing and existing ~= p then - -- over / def of the same path in one layer: merge into the first spec + -- over / def of the same path in one layer: merged into the first spec for _, pn in p.order do if not existing.props[pn] then existing.props[pn] = p.props[pn] @@ -375,7 +353,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(existing.children, c) end table.clear(p.children) - p.specifier = "class" -- skipped below + p.specifier = "class" else byPath[path] = p end @@ -396,7 +374,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) unsupported.subLayers = true end - -- a property of a prim path ("/a/b.inputs:x") local function propAt(path: string): (Prim?, Prop?) local pp, pn = splitProp(path) local prim = byPath[pp] @@ -406,7 +383,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return prim, prim.props[pn] end - -- --------------------------------------------------------------------------------------------- materials local texCoordIndex: { [string]: number } = {} local texCoordCount = 0 local function texCoordFor(name: string): number @@ -418,7 +394,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end return k end - -- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n + -- "st" first, so materials and meshes agree on TEXCOORD_n do local names: { [string]: boolean } = {} for _, p in byPath do @@ -448,7 +424,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end end - -- an input's resolved source: a value, or { shader = Prim, output = name } type Source = { value: any?, shader: Prim?, output: string? } local function input(prim: Prim, name: string, depth: number?): Source? local d = depth or 0 @@ -469,7 +444,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) if outName and tprim.typeName == "Shader" then return { shader = tprim, output = outName } elseif outName then - -- a NodeGraph output: follow its connection local op = tprim.props[tn] if op and op.connect and #op.connect > 0 then local t2 = resolvePath(tp, op.connect[1]) @@ -499,7 +473,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local textureIndex: { [string]: number } = {} local WRAP: { [string]: string } = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } - -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) local function textureRef(shader: Prim): Types.TextureRef? if shaderId(shader) ~= "UsdUVTexture" then return nil @@ -535,7 +508,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) textureIndex[key] = ti end local ref: Types.TextureRef = { texture = ti :: number } - -- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d) + -- st: UsdPrimvarReader_float2, maybe through UsdTransform2d local st = input(shader, "st") local reader = st and st.shader if reader and shaderId(reader) == "UsdTransform2d" then @@ -587,7 +560,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) mat.metallic = 0 mat.roughness = 0.5 mat.extras = { usd = { path = path } } - -- the surface shader local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] local shader: Prim? = nil if surf and surf.connect and #surf.connect > 0 then @@ -695,7 +667,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return #scene.materials end - -- the bound material of a prim (material:binding, inherited from ancestors) + -- material:binding, inherited from ancestors local function binding(prim: Prim, path: string): number? local p: Prim? = prim local pp = path @@ -733,7 +705,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return mi :: number end - -- --------------------------------------------------------------------------------------------- meshes type Primvar = { data: { number }, w: number, interp: string, idx: { number }? } local function primvar(p: Prop?, defaultInterp: string): Primvar? if not p then @@ -791,7 +762,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end faceStart[nfaces + 1] = acc end - -- primvars, validated local function sizeOk(pv: Primvar): boolean local n = (if pv.idx then #pv.idx else #pv.data // pv.w) local want = if pv.interp == "constant" then 1 @@ -848,7 +818,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end end end - -- the value of a primvar for (point, face, corner) (0-based), component c local function get(pv: Primvar, point: number, face: number, corner: number, c: number): number local e = if pv.interp == "constant" then 0 elseif pv.interp == "uniform" then face @@ -871,7 +840,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end end local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" - -- holes local hole: { [number]: boolean } = {} local hv = propValue(prim.props.holeIndices) if isArr(hv) then @@ -879,7 +847,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) hole[f] = true end end - -- face sets: GeomSubsets ("face" elements), the rest + -- face sets: GeomSubsets of "face" elements, then the rest local meshMaterial = binding(prim, path) local constantColor: { number }? = nil if color and color.interp == "constant" then @@ -921,9 +889,8 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end local mesh: Types.Mesh = { name = prim.name, primitives = {} } for _, set in sets do - -- vertices: one per point (vertex-rate data) or per corner local keyToVert: { [number]: number } = {} - local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based) + local vp, vf, vc = {}, {}, {} local nv = 0 local out: { number } = {} local faceSizes: { number } = {} @@ -1001,7 +968,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end local mi = set.material if color and not constantColor then - -- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity) if opacity then local a = Types.Scene.accessor(nil, "f32", 4, nv) for v = 1, nv do @@ -1048,7 +1014,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return mesh, nil end - -- --------------------------------------------------------------------------------------------- cameras / lights local function camera(prim: Prim): Types.Camera local function f(name: string, d: number): number return num(propValue(prim.props[name])) or d @@ -1095,7 +1060,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) return l end - -- --------------------------------------------------------------------------------------------- nodes local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 if tcps <= 0 then tcps = 24 @@ -1147,7 +1111,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(scene.nodes, n) local ni = #scene.nodes local ops, reset = xformOps(p) - -- animated ops: the local matrix at the union of their time codes local times: { number } = {} do local seen: { [number]: boolean } = {} @@ -1192,7 +1155,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local T, R, S = Mat4.decompose(localMatrix(ops, times[1])) n.translation, n.rotation, n.scale = T, R, S elseif #ops > 0 then - -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix local simple = true local stage = 0 for _, op in ops do @@ -1288,7 +1250,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(scene.animations, animation) end - -- stage metadata local up = str(meta.upAxis) scene.meta.up = if up == "Z" then "z" else "y" local mpu = num(meta.metersPerUnit) diff --git a/src/Rosetta/model/usda/Parse.luau b/src/Rosetta/model/usda/Parse.luau index e3ddd2e..0dfa18f 100644 --- a/src/Rosetta/model/usda/Parse.luau +++ b/src/Rosetta/model/usda/Parse.luau @@ -1,40 +1,33 @@ --!strict --- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text --- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes --- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships, --- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted), --- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast --- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching. --- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and --- returns nil, message, offset - nothing escapes. +-- model/usda/Parse: USD ASCII ("#usda 1.0") to prim specs, from the Sdf text grammar as Pixar's USD writes and reads +-- it; new code. .spline blocks and unknown constructs are skipped by bracket matching. Never throws. local Parse = {} --- values: numbers, booleans, strings, and these tagged tables -export type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened) +export type Arr = { t: "arr", w: number, v: { number } } -- w numbers per element (tuples flattened) export type Value = any export type Prop = { name: string, - rel: boolean, -- a relationship - typeName: string?, -- "point3f", "token", ... (attributes) + rel: boolean, + typeName: string?, array: boolean?, uniform: boolean?, custom: boolean?, - value: Value?, -- the default value (attributes) or the targets (relationships: { path strings }) + value: Value?, -- relationships: { path strings } hasValue: boolean?, samples: { times: { number }, values: { Value } }?, - connect: { string }?, -- connection target paths (attributes) + connect: { string }?, meta: { [string]: Value }?, } export type Prim = { - specifier: string, -- "def" | "over" | "class" + specifier: string, typeName: string?, name: string, meta: { [string]: Value }, props: { [string]: Prop }, - order: { string }, -- property names in file order + order: { string }, children: { Prim }, - variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children) + variantSets: { [string]: { [string]: Prim } }?, } export type Layer = { meta: { [string]: Value }, prims: { Prim } } @@ -51,12 +44,10 @@ local function fail(msg: string, at: number): never error({ usda = msg, at = at }, 0) end --- the parser over one text; positions are 1-based string indices local function parser(s: string, maxBytes: number) local n = #s local depth = 0 - -- whitespace and comments (newlines included) local function ws(i: number): number while true do local _, e = sfind(s, "^[ \t\r\n]+", i) @@ -64,13 +55,13 @@ local function parser(s: string, maxBytes: number) i = e + 1 end local c = sbyte(s, i) - if c == 35 then -- # + if c == 35 then local nl = sfind(s, "\n", i, true) i = if nl then nl + 1 else n + 1 - elseif c == 47 and sbyte(s, i + 1) == 47 then -- // + elseif c == 47 and sbyte(s, i + 1) == 47 then local nl = sfind(s, "\n", i, true) i = if nl then nl + 1 else n + 1 - elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */ + elseif c == 47 and sbyte(s, i + 1) == 42 then local _, ce = sfind(s, "*/", i + 2, true) if not ce then fail("unterminated comment", i) @@ -105,7 +96,7 @@ local function parser(s: string, maxBytes: number) end return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string if x == "x" then - return "\\x" .. c -- left alone (rare) + return "\\x" .. c end return ESC[c] or c end)) @@ -148,7 +139,6 @@ local function parser(s: string, maxBytes: number) return v, (e :: number) + 1 end end - -- inf / -inf / nan local w, e2 = sfind(s, "^[-+]?%a+", i) if w then local word = string.lower(ssub(s, w, e2)) @@ -163,7 +153,6 @@ local function parser(s: string, maxBytes: number) return nil, i end - -- skip a balanced (), [], {} block starting at i (strings and comments respected) local function skipBalanced(i: number): number local open = sbyte(s, i) local level = 0 @@ -202,7 +191,6 @@ local function parser(s: string, maxBytes: number) local value: (i: number) -> (Value, number) local metadata: (i: number) -> ({ [string]: Value }, number) - -- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list local function list(i: number): (Value, number) local close = sfind(s, "]", i + 1, true) if close then @@ -216,7 +204,7 @@ local function parser(s: string, maxBytes: number) w += 1 end elseif sfind(body, "[%(%)]") then - w = -1 -- nested tuples: the generic path + w = -1 end if w > 0 then local out: { number } = {} @@ -240,7 +228,6 @@ local function parser(s: string, maxBytes: number) end end end - -- generic local items = {} i += 1 while true do @@ -256,7 +243,7 @@ local function parser(s: string, maxBytes: number) v, i = value(i) table.insert(items, v) i = ws(i) - if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...) + if ssub(s, i, i) == "(" then local _ _, i = metadata(i) i = ws(i) @@ -268,7 +255,6 @@ local function parser(s: string, maxBytes: number) fail("expected ',' or ']' in a list", i) end end - -- all numbers, or all equal-width numeric tuples -> arr local w: number? = nil local flat: { number } = {} for _, it in items do @@ -326,7 +312,6 @@ local function parser(s: string, maxBytes: number) return { t = "tuple", v = items }, i end - -- { type key = value ... } (metadata dictionaries) local function dict(i: number): (Value, number) local out: { [string]: Value } = {} i += 1 @@ -403,7 +388,7 @@ local function parser(s: string, maxBytes: number) end local a: { [string]: any } = { t = "asset", v = path } local j = ws(i) - if ssub(s, j, j) == "<" then -- references = @file@ + if ssub(s, j, j) == "<" then local e = sfind(s, ">", j + 1, true) if not e then fail("unterminated path", j) @@ -444,7 +429,6 @@ local function parser(s: string, maxBytes: number) return v, i end - -- ( key = value ; "doc" ; prepend key = value ... ) function metadata(i: number): ({ [string]: Value }, number) local out: { [string]: Value } = {} i = expect(i, "(") @@ -481,9 +465,7 @@ local function parser(s: string, maxBytes: number) local v v, i = value(i + 1) if op == "delete" then - -- deletions only matter for composition elseif op and op ~= "reorder" then - -- prepend / append / add: merge into one list local prev = out[key :: string] if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then for _, x in v.v do @@ -499,7 +481,6 @@ local function parser(s: string, maxBytes: number) end end - -- time samples: { time: value, ... } local function samples(i: number): ({ times: { number }, values: { Value } }, number) local times: { number }, values: { Value } = {}, {} i = expect(i, "{") @@ -523,7 +504,7 @@ local function parser(s: string, maxBytes: number) i = expect(i, ":") local v v, i = value(i) - table.insert(times, t :: number) -- fail() threw on nil + table.insert(times, t :: number) table.insert(values, v) end return { times = times, values = values }, i @@ -562,7 +543,6 @@ local function parser(s: string, maxBytes: number) fail("expected a prim type or name", i) end i = ws(i) - -- dotted schema names (rare) while ssub(s, i, i) == "." do local more more, i = ident(i + 1) @@ -618,7 +598,7 @@ local function parser(s: string, maxBytes: number) end end - -- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + -- [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] local function property(i: number, first: string, p: Prim): number local word: string? = first local op: string? = nil @@ -685,7 +665,6 @@ local function parser(s: string, maxBytes: number) local v v, i = value(i) if op == "delete" then - -- composition only elseif suffix == "connect" then pr.connect = targets(v) elseif isRel then @@ -755,7 +734,6 @@ local function parser(s: string, maxBytes: number) end end - -- the whole layer local function layer(): Layer local i = 1 if ssub(s, 1, 3) == "\239\187\191" then @@ -799,7 +777,6 @@ local function parser(s: string, maxBytes: number) return layer end --- layer(text, opts?) -> Layer | nil, message, offset (0-based) function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?) local run = parser(text, maxBytes or 2 ^ 30) local ok, res = pcall(run) @@ -812,7 +789,6 @@ function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number? return nil, "parse error: " .. tostring(res), nil end --- version(text) -> the "#usda " string function Parse.version(text: string): string? return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") end diff --git a/src/Rosetta/model/usda/Write.luau b/src/Rosetta/model/usda/Write.luau index bd2a658..3eb4eac 100644 --- a/src/Rosetta/model/usda/Write.luau +++ b/src/Rosetta/model/usda/Write.luau @@ -1,15 +1,6 @@ --!strict --- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code. --- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim, --- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture --- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a --- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim, --- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are --- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale) --- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back), --- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the --- embedded bytes written into opts.files as _.. Not written: skins, morph targets, weights animation, --- lines / points primitives (counted in the returned notes). +-- model/usda/Write: Scene -> USD ASCII (UsdGeom / UsdShade / UsdLux); new code. timeCodesPerSecond 24. Not written: +-- skins, morph targets, weights animation, lines / points primitives. local Types = require("@rosetta/Types") local Write = {} @@ -48,7 +39,6 @@ local function asset(s: string): string end return "@" .. s .. "@" end --- a valid, sibling-unique prim name local function namer(): (string?, string) -> string local used: { [string]: boolean } = {} return function(name: string?, fallback: string): string @@ -69,7 +59,6 @@ local function namer(): (string?, string) -> string end end --- an accessor's elements as numbers (normalized types to floats) local function values(acc: Types.Accessor?): ({ number }?, number) if not acc then return nil, 0 @@ -88,7 +77,6 @@ local function values(acc: Types.Accessor?): ({ number }?, number) return out, c end --- array literal of tuples ("[(x, y, z), ...]") or scalars local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string local st = stride or width local n = count or (#vals // st) @@ -114,12 +102,11 @@ type Merged = { indices: { number }, normals: { number }?, uvs: { [number]: { number } }, - colors: { number }?, -- rgba + colors: { number }?, hasAlpha: boolean, subsets: { { faces: { number }, material: number? } }, } --- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) local idx: { number } if p.indices then @@ -176,7 +163,6 @@ local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number return counts, out end --- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? local prims: { Types.Primitive } = {} for _, p in mesh.primitives do @@ -192,7 +178,6 @@ local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? if #prims == 0 then return nil end - -- attributes every primitive has local all = { NORMAL = true } local uvSets: { number } = {} for k = 0, 7 do @@ -317,7 +302,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu local rootNames = namer() local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") - -- texture files local base: string = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" local texFile: { [number]: string } = {} for i, tex in scene.textures or {} do @@ -338,7 +322,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu texFile[i] = uri :: string end - -- animation: per node, per path -> { times, values (components) } type Track = { times: { number }, vals: { number }, comps: number } local tracks: { [number]: { [string]: Track? } } = {} local tcps = 24 @@ -353,7 +336,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu if vals and #times > 0 then local stride = comps local per = #vals // (comps * #times) - -- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value + -- CUBICSPLINE: in-tangent, value, out-tangent per key local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0 local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1 local tv = {} @@ -373,7 +356,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu end end - -- header table.insert(out, "#usda 1.0") table.insert(out, "(") line(1, "defaultPrim = " .. quote(rootName)) @@ -397,7 +379,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) end - -- xform ops of a node (+ its animation) local function xform(depth: number, ni: number, n: Types.Node) local tr: { [string]: Track? }? = tracks[ni] local order: { string } = {} @@ -418,7 +399,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu local t, r, s = n.translation, n.rotation, n.scale if n.matrix and #n.matrix == 16 then if tr then - -- animated: start from the matrix's TRS local m = n.matrix local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) @@ -476,7 +456,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu if doubleSided then line(depth, "uniform bool doubleSided = 1") end - -- extent local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for i = 0, #m.points // 3 - 1 do for c = 1, 3 do @@ -634,7 +613,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu lightBody(depth + 1, lig :: Types.Light) end local childNames = namer() - -- a camera / light that did not take the node's prim if cam and kind ~= "Camera" then table.insert(out, "") line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) @@ -678,7 +656,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu return table.concat(out, "\n"), notes end --- the Looks scope: materials as UsdPreviewSurface networks function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ()) local mats = scene.materials or {} if #mats == 0 then @@ -695,7 +672,6 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat line(depth + 1, "{") local d = depth + 2 line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") - -- texture nodes (one per distinct ref) type TexNode = { name: string, ref: Types.TextureRef, color: boolean } local texNodes: { TexNode } = {} local function texNode(ref: Types.TextureRef?, color: boolean): string? @@ -768,7 +744,6 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat end line(e, "token outputs:surface") line(d, "}") - -- primvar readers per texCoord set, transforms, textures local readers: { [number]: boolean } = {} for _, tn in texNodes do local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 diff --git a/src/Rosetta/model/usda/init.luau b/src/Rosetta/model/usda/init.luau index af4b27c..3dff272 100644 --- a/src/Rosetta/model/usda/init.luau +++ b/src/Rosetta/model/usda/init.luau @@ -1,20 +1,8 @@ --!strict --- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text --- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own --- reader / writer (pxr) and Blender's USD exporter. --- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start / --- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale, --- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one --- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every --- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices, --- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 / --- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone -> --- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files / --- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them). --- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples. --- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs --- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel --- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ. +-- model/usda: USD ASCII layers (.usda, text .usd) and USDZ packages of them, from the Sdf text format and the UsdGeom / +-- UsdShade / UsdLux docs (OpenUSD 26.x), checked against pxr and Blender's exporter. Not supported: USDC crate files, +-- composition arcs (listed in meta.source.unsupported), UsdSkel, blend shapes, curves / points / NURBS, instancers, +-- MaterialX, writing USDZ. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -37,18 +25,18 @@ local Usda = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives - flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin) - resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths) - files: { [string]: any }?, -- or: the files by asset path - maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25) - maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30) + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, -- default 2^25 + maxBytes: number?, -- default 2^30 } export type EncodeOptions = { - files: { [string]: any }?, -- receives embedded texture bytes as _. - name: string?, -- the destination's file name (names the texture files) - format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension) - upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up) + files: { [string]: any }?, -- as _. + name: string?, + format: string?, -- "usdz" -> UNSUPPORTED + upAxis: string?, -- default: from scene.meta.up metersPerUnit: number?, -- default scene.meta.unit or 1 } @@ -57,7 +45,6 @@ local function isUsdz(r: Bytes.Reader): boolean if r:peek(4) ~= "PK\3\4" then return false end - -- the first entry is the root layer local lo, hi = r:peekU8(26), r:peekU8(27) if lo < 0 or hi < 0 then return false @@ -74,7 +61,7 @@ function Usda.sniff(r: Bytes.Reader): number return 1 end if head == "PXR-USDC" then - return 0.9 -- recognised so the error says USDC is not supported + return 0.9 -- USDC magic, so the error says it is unsupported end if isUsdz(r) then return 0.95 @@ -209,7 +196,6 @@ function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Er end -- ------------------------------------------------------------------------------------------------ extras --- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover function Usda.parse(text: string): (Parse.Layer?, Err.Err?) local layer, msg, at = Parse.layer(text) if not layer then diff --git a/src/Rosetta/model/vox/Grid.luau b/src/Rosetta/model/vox/Grid.luau index 4a6601e..fe50ea3 100644 --- a/src/Rosetta/model/vox/Grid.luau +++ b/src/Rosetta/model/vox/Grid.luau @@ -1,14 +1,10 @@ --!strict --!native --- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI --- records. Callers check every range first; nothing here throws. +-- model/vox/Grid: XYZI records to and from a dense grid (cell x + sx * (y + sy * z); index 0 = empty). Never throws. local Grid = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the --- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted. --- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz. function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number local skipped = 0 local sxy = sx * sy @@ -24,7 +20,6 @@ function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, return skipped end --- count(data, cells) -> the number of non-empty cells in data[0, cells) function Grid.count(data: buffer, cells: number): number local n = 0 for k = 0, cells - 1 do @@ -35,8 +30,7 @@ function Grid.count(data: buffer, cells: number): number return n end --- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest). --- The caller sizes dst with count() (sx, sy, sz <= 256). +-- one XYZI record per non-empty cell (x fastest; sx, sy, sz <= 256) function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number local p = at local k = 0 diff --git a/src/Rosetta/model/vox/init.luau b/src/Rosetta/model/vox/init.luau index 3c6a561..8c5d605 100644 --- a/src/Rosetta/model/vox/init.luau +++ b/src/Rosetta/model/vox/init.luau @@ -1,17 +1,7 @@ --!strict --- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt) --- and the files MagicaVoxel 0.99.x saves (version 150 and 200). --- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP / --- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials, --- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown --- chunks are kept raw and written back. --- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per --- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as --- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is --- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes. --- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must --- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk. --- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring. +-- model/vox: MagicaVoxel .vox (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200). +-- Supports: every chunk (unknown, PACK, MATT kept raw); shapes centred on their node like MagicaVoxel. Not supported: +-- writing models over 256 cells per axis (MagicaVoxel's limit); node scale other than mirroring. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,10 +21,10 @@ local Vox = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27) + maxCells: number?, -- default 2^27 } export type EncodeOptions = { - version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one) + version: number?, -- default 200 (MagicaVoxel 0.99.7); 150 is the older one } type Dict = { [string]: string } type GraphNode = { @@ -123,7 +113,7 @@ local function ints(s: string?): { number } return out end --- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }); nil when not a permutation local function rotation(b: number): { { number } }? local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) if i0 > 2 or i1 > 2 or i0 == i1 then @@ -136,7 +126,6 @@ local function rotation(b: number): { { number } }? return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } end --- the node transform of a frame dictionary (_r, _t) local function applyFrame(node: Types.Node, f: Dict) local t = ints(f._t) local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 @@ -185,7 +174,7 @@ local function applyFrame(node: Types.Node, f: Dict) end end --- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers +-- MATL: _type -> type, the other keys without their "_", numbers as numbers local function material(d: Dict): Types.VoxelMaterial local m: Types.VoxelMaterial = { type = "diffuse" } for k, v in d do @@ -413,7 +402,6 @@ local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) return out, nil end --- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node) local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number? local t = graph[id] if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then @@ -453,7 +441,6 @@ local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: num return index end --- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?) local p, err = parse(r, opts) if not p then @@ -546,7 +533,6 @@ local function wdict(w: Bytes.Writer, d: { [string]: any }?) end end --- a node's transform as a frame dictionary (_r, _t) | nil, message local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?) local f: Dict = {} if base then @@ -646,7 +632,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) wdict(w, meta.info) end) end - -- models for _, v in models do local sx, sy, sz = v.size[1], v.size[2], v.size[3] chunk("SIZE", function() @@ -662,7 +647,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) w.pos = at + count * 4 end) end - -- the scene graph local records: { Record } = {} local nextId = 0 local function alloc(): number @@ -796,7 +780,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end end) end - -- layers if type(meta.layers) == "table" then for _, l in meta.layers do chunk("LAYR", function() @@ -814,7 +797,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end) end end - -- palette local pal = models[1].palette or DEFAULT_PALETTE chunk("RGBA", function() for i = 1, 256 do @@ -836,7 +818,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end end) end - -- materials local mats = models[1].materials if type(mats) == "table" then local ids = {} diff --git a/src/Rosetta/model/vrml/init.luau b/src/Rosetta/model/vrml/init.luau index fe28a56..a24962d 100644 --- a/src/Rosetta/model/vrml/init.luau +++ b/src/Rosetta/model/vrml/init.luau @@ -1,20 +1,7 @@ --!strict --- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over --- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code. --- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD, --- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and --- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord, --- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided), --- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated --- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor -> --- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons --- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless --- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres). --- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet / --- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights, --- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials). --- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and --- skins on write (the rest pose is written). +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl / .wrz over codecs/model/Vrml; new code. Supports: +-- the scene graph, DEF / USE, PROTO / EXTERNPROTO, the geometry nodes, Viewpoints, lights, interpolator ROUTEs as +-- animations. Not supported: VRML 1.0, Text, Script, sensors, sound, NURBS; morph targets and skins on write. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,16 +21,16 @@ local Wrl = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) - resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) - segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + files: { [string]: any }?, -- by uri or base name + resolve: ((uri: string) -> any)?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + segments: number?, -- default 32 maxVertices: number?, -- per geometry (default 2^24) } export type EncodeOptions = { - files: { [string]: any }?, -- receives the texture images (else url = texture.uri) - name: string?, -- the destination's file name (names the image files) + files: { [string]: any }?, -- else url = texture.uri + name: string?, flipV: boolean?, -- default true (the inverse of decode) } diff --git a/src/Rosetta/model/x/Build.luau b/src/Rosetta/model/x/Build.luau index 82e31c9..7db8317 100644 --- a/src/Rosetta/model/x/Build.luau +++ b/src/Rosetta/model/x/Build.luau @@ -1,9 +1,6 @@ --!strict --- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is --- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding --- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same). --- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep --- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall). +-- model/x/Build: the .x object tree to a Scene, from the DirectX template layouts. Direct3D is left-handed (y up, row +-- vectors): z is negated (matrices as S * M * S) and windings reversed, as assimp does; UVs stay top-left. local Types = require("@rosetta/Types") local Mat4 = require("@rosetta/codecs/model/Mat4") local Rig = require("@rosetta/codecs/model/Rig") @@ -16,7 +13,6 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32 type Node = Parse.Node --- a cursor over an object's flattened values type Vals = { v: { any }, i: number } local function num(c: Vals): number local x = c.v[c.i] @@ -34,7 +30,6 @@ local function str(c: Vals): string end return x end --- a non-negative integer (an index) local function index(c: Vals, limit: number): number local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then @@ -43,8 +38,6 @@ local function index(c: Vals, limit: number): number return n end --- a count of items that follow (each takes at least one value: a count past the data is refused before anything --- is allocated for it) local function count(c: Vals, limit: number): number local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then @@ -56,7 +49,7 @@ local function count(c: Vals, limit: number): number return n end --- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1) +-- S * M * S, S = diag(1, 1, -1) local function mirror(m: { number }): { number } local o = table.clone(m) for _, k in { 3, 7, 9, 10, 12, 15 } do @@ -140,7 +133,6 @@ local function accessorF32(values: { number }, comps: number): Types.Accessor return Scene.accessor(b, "f32", comps, n // comps) end --- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces) local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local scene = ctx.scene local c: Vals = { v = m.vals, i = 1 } @@ -168,7 +160,6 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) end faces[f] = face end - -- the optional data objects local normals: { number }? = nil local nfaces: { { number } }? = nil local uvSets: { { number } } = {} @@ -243,12 +234,11 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) end end - -- material per face (a single index applies to every face) + -- a single index applies to every face local function matOf(f: number): number local mi = if #faceMat == 1 then faceMat[1] else faceMat[f] return if mi then mi + 1 else 1 end - -- unique vertices per (position, normal index) local key: { [number]: number } = {} local srcPos: { number } = {} local srcNrm: { number } = {} @@ -264,7 +254,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local nface = nfaces and nfaces[f] local vs = table.create(n) :: { number } for k = 1, n do - local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept + local src = if k == 1 then 1 else n - k + 2 local p = face[src] local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1 local kk = p * (nNormals + 1) + q + 1 @@ -301,7 +291,6 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) return nil, nil end table.sort(order) - -- shared vertex attributes (one vertex buffer for every primitive of the mesh) local nout = #srcPos local P = table.create(nout * 3) :: { number } for v = 1, nout do @@ -415,7 +404,6 @@ local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, d node.matrix = m end elseif k.type == "Mesh" then - -- the first mesh on the frame's node, more as child nodes local mi, bones = mesh(ctx, k, triangulate) if mi then local holder = ni @@ -536,7 +524,6 @@ function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: num end end end - -- skins: bone names -> frames for _, ps in ctx.pendingSkins do local joints: { number } = {} local ibm = buffer.create(#ps.bones * 64) diff --git a/src/Rosetta/model/x/Parse.luau b/src/Rosetta/model/x/Parse.luau index e770dd9..692a269 100644 --- a/src/Rosetta/model/x/Parse.luau +++ b/src/Rosetta/model/x/Parse.luau @@ -1,21 +1,13 @@ --!strict --- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the --- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and --- binary tokens), checked against what assimp's XFileParser accepts (no code taken). --- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and --- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout), --- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped. --- Text: ; and , separators, // and # comments, quoted strings, s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0). --- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and --- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message. +-- model/x/Parse: .x text and binary tokens to { type, name?, vals, kids } objects, from Microsoft's "DirectX File +-- Format Specification", checked against assimp's XFileParser (no code taken). Templates are skipped; Blender's +-- "1.#IND00" / "1.#QNAN0" read as 0. Never throws: bad data returns nil, message. local Parse = {} export type Node = { type: string, name: string?, vals: { any }, kids: { Node } } local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring --- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }), --- "punct", "eof"; err holds a message after a bad token type Lexer = { next: () -> (string, any), err: string? } local KEYWORDS: { [number]: string } = { @@ -50,7 +42,7 @@ local function textLexer(s: string): Lexer return "eof", nil end local c = string.byte(s, p) - if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or # + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then local nl = string.find(s, "[\r\n]", p) p = if nl then nl + 1 else n + 1 else @@ -199,7 +191,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?) return if q then q[1] else "eof" end local budget = maxValues - -- skips a template / unknown block whose "{" was just read local function skipBlock(): string? local depth = 1 while depth > 0 do @@ -215,7 +206,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?) return nil end local body: (Node, number) -> string? - -- an object whose type token was read: [name] { ... } local function object(parent: Node, typ: string, depth: number): string? local name: string? = nil local kind, v = take() @@ -297,7 +287,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?) return root, nil end --- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?) local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from)) return tree(lex, maxValues) diff --git a/src/Rosetta/model/x/init.luau b/src/Rosetta/model/x/init.luau index 81338e0..2918210 100644 --- a/src/Rosetta/model/x/init.luau +++ b/src/Rosetta/model/x/init.luau @@ -1,20 +1,7 @@ --!strict --- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip", --- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format --- specification and the standard templates, checked against assimp's X importer and test models. --- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per --- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal --- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global --- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture, --- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x), --- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four --- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale, --- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped. --- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does. --- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in --- meta.source.skippedFaces). --- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key --- interpolation options (keys are linear). +-- model/x: DirectX .x, read only: text ("txt "), binary ("bin "), MSZIP ("tzip" / "bzip"), 32- and 64-bit floats; from +-- Microsoft's DirectX file format spec and templates, checked against assimp. AnimTicksPerSecond defaults to 4800. Not +-- supported: DeclData / FVFData, progressive and patch meshes, non-linear key interpolation. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -36,10 +23,10 @@ local X = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25) - maxValues: number?, -- refuse files with more numbers than this (default 2^27) - maxBytes: number?, -- refuse compressed files inflating to more (default 2^30) + triangulate: boolean?, -- default true + maxVertices: number?, -- default 2^25 + maxValues: number?, -- default 2^27 + maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants @@ -55,8 +42,7 @@ end -- ------------------------------------------------------------------------------------------------ decode -- MSZIP: a u32 total size (with the 16-byte file header), then blocks (u16 uncompressed size, u16 compressed size, --- "CK" + deflate data). The blocks are walked here; codecs/compress/Deflate.mszip inflates the chain (each block may --- refer back into the previous block's output). +-- "CK" + deflate data); each block may refer back into the previous block's output. local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?) if p + 4 > limit then return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) diff --git a/src/Rosetta/model/x3d/init.luau b/src/Rosetta/model/x3d/init.luau index ea3ddc6..8879bde 100644 --- a/src/Rosetta/model/x3d/init.luau +++ b/src/Rosetta/model/x3d/init.luau @@ -1,16 +1,7 @@ --!strict --- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv, --- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares). --- New code. --- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, --- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA, --- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial / --- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField; --- head meta, components and UNIT length (-> meta.unit). --- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the --- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras). --- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders, --- H-Anim skinning, scripts. +-- model/x3d: X3D (ISO/IEC 19775-1) XML (.x3d, 19776-1) and classic VRML (.x3dv, 19776-2) encodings, plain or gzipped, +-- over codecs/model/Vrml; new code. Supports: the model/vrml set plus the X3D geometry and material nodes. +-- Not supported: binary encodings (.x3db Fast Infoset / EXI), X3D JSON, Text, NURBS, shaders, H-Anim skinning, scripts. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,18 +21,18 @@ local X3d = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) - resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) - triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives - flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) - segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + files: { [string]: any }?, -- by uri or base name + resolve: ((uri: string) -> any)?, + triangulate: boolean?, -- default true + flipV: boolean?, -- default true + segments: number?, -- default 32 maxVertices: number?, -- per geometry (default 2^24) } export type EncodeOptions = { encoding: ("xml" | "x3dv")?, -- default "xml" - format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding - files: { [string]: any }?, -- receives the texture images (else url = texture.uri) - name: string?, -- the destination's file name (names the image files) + format: string?, -- "x3dv" / "x3dvz" select the classic encoding + files: { [string]: any }?, -- else url = texture.uri + name: string?, flipV: boolean?, -- default true (the inverse of decode) } diff --git a/src/Rosetta/music/669/init.luau b/src/Rosetta/music/669/init.luau index ab4e70e..50d14d0 100644 --- a/src/Rosetta/music/669/init.luau +++ b/src/Rosetta/music/669/init.luau @@ -1,11 +1,7 @@ --!strict --- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and --- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides --- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until --- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F), --- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms). --- Not supported: UNIS 669's "super fast" speed 0, writing. +-- music/669: Composer 669 / UNIS 669 modules ("if" / "JN"), ported from OpenMPT's Load_669.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Supports: 8 channels, 64-row patterns, played as the "s3m" family with 669's quirks +-- (periods in Hz, auto portamentos, effects D..H, a fixed 78 BPM). Not supported: UNIS 669's speed 0, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,16 +21,16 @@ local Six69 = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants local IT = Load.IT --- the 669 effects (high nibble of the effect byte) by name +-- effects: the high nibble of the effect byte local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" } -- ------------------------------------------------------------------------------------------------ sniff --- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too) +-- the 497-byte header (the magic is two bytes only, so the other fields are checked too) local function validHeader(r: Bytes.Reader): boolean if r:size() < 497 then return false @@ -197,7 +193,6 @@ function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Six69.decode(r, opts) if not m then diff --git a/src/Rosetta/music/ahx/init.luau b/src/Rosetta/music/ahx/init.luau index c888acf..eee4cd5 100644 --- a/src/Rosetta/music/ahx/init.luau +++ b/src/Rosetta/music/ahx/init.luau @@ -1,10 +1,7 @@ --!strict --- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples: --- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs). --- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel --- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's --- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's. --- Not supported: writing. +-- music/ahx: AHX (Abyss' Highest eXperience) 4-channel Amiga synth modules, "THX\0" .. "THX\2", rendered through +-- codecs/audio/Hively (a port of HivelyTracker's hvl2wav, BSD-3-Clause; at 44.1 kHz, stereo 0, equal to hvl2wav). +-- Supports: tracks, positions with transposes, PList instruments, subsongs. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +20,7 @@ local Ahx = { } -- ------------------------------------------------------------------------------------------------ types -export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, stereo (0..4), loop, maxDuration +export type RenderOptions = Hively.RenderOptions -- stereo 0..4 -- ------------------------------------------------------------------------------------------------ sniff function Ahx.sniff(r: Bytes.Reader): number @@ -41,7 +38,6 @@ function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Ahx.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local song, err = Ahx.decode(r) if not song then diff --git a/src/Rosetta/music/far/init.luau b/src/Rosetta/music/far/init.luau index 20861d7..c5ac494 100644 --- a/src/Rosetta/music/far/init.luau +++ b/src/Rosetta/music/far/init.luau @@ -1,11 +1,7 @@ --!strict --- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any --- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads --- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods --- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides, --- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed --- tempo OpenMPT uses (80 BPM in tracker terms). --- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing. +-- music/far: Farandole Composer modules (FAR, 16 channels), ported from OpenMPT's Load_far.cpp (BSD, +-- licenses/openmpt-LICENSE.txt). Plays as the "s3m" family with FAR's quirks (periods in Hz, a slide step of +-- 36318 / 1024 Hz, OpenMPT's fixed 80 BPM). Not supported: FAR's tempo effects (D / E), note offset (C), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +21,7 @@ local Far = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -40,7 +36,7 @@ function Far.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +-- effect byte -> S3M effect, parameter, volume byte (0 = none): OpenMPT's table local function effect(e: number): (number, number, number) local cmd, p = e // 16, e % 16 if cmd == 1 then @@ -220,7 +216,6 @@ function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Far.decode(r, opts) if not m then diff --git a/src/Rosetta/music/hmp/init.luau b/src/Rosetta/music/hmp/init.luau index f6a7e65..e2ea95f 100644 --- a/src/Rosetta/music/hmp/init.luau +++ b/src/Rosetta/music/hmp/init.luau @@ -1,14 +1,7 @@ --!strict --- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header) --- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the --- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE --- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per --- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker --- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a --- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP --- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the --- tracks apply on top. Renders through codecs/audio/MidiRender. --- Not supported: writing; HMP branch tables (skipped). +-- music/hmp: HMI SOS music: HMP ("HMIMIDIP", "HMIMIDIP013195") and HMI ("HMI-MIDISONG061595"), from the layout +-- notes (wildmidi only as a test reference). Decodes to a Types.Midi (format 1, a track per chunk; the tick rate at +-- HMP 0x38 / HMI byte 212, as division 60). Not supported: writing, HMP branch tables. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -43,8 +36,7 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set; --- otherwise the MIDI encoding +-- HMP deltas: 7-bit groups, least significant first, the last byte has bit 7 set; HMI: the MIDI encoding local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number) local v, shift = 0, 1 for _ = 1, 5 do @@ -79,14 +71,13 @@ end type Ctx = { loops: number, budget: number } --- one track [p, e) -> events (note-offs merged in) | nil, message local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?) local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} local tick, running = 0, 0 while p < e do local d, q = delta(b, p, e, hmp) if not d then - break -- (a track cut inside its last delta: keep what was read) + break end tick += d p = q @@ -170,7 +161,6 @@ local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ( return out, nil end --- the chunk table -> { { start, stop } } track ranges | nil, message, kind local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) local new = buffer.readstring(b, base + 8, 6) == "013195" local n = readu32(b, base + 0x30) @@ -261,7 +251,6 @@ function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Hmp.decode(r, opts) if not midi then diff --git a/src/Rosetta/music/hvl/init.luau b/src/Rosetta/music/hvl/init.luau index ea0f81a..92cb27e 100644 --- a/src/Rosetta/music/hvl/init.luau +++ b/src/Rosetta/music/hvl/init.luau @@ -1,10 +1,7 @@ --!strict --- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns, --- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module- --- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with --- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer --- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's. --- Not supported: writing. +-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1" (AHX extended: 4..16 channels, two effect columns, ring +-- modulation, panning, stereo separation), rendered through codecs/audio/Hively (a port of hvl2wav, BSD-3-Clause; at +-- 44.1 kHz equal to hvl2wav). Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +20,7 @@ local Hvl = { } -- ------------------------------------------------------------------------------------------------ types -export type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, loop, maxDuration (stereo: the file's) +export type RenderOptions = Hively.RenderOptions -- stereo comes from the file -- ------------------------------------------------------------------------------------------------ sniff function Hvl.sniff(r: Bytes.Reader): number @@ -41,7 +38,6 @@ function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) function Hvl.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local song, err = Hvl.decode(r) if not song then diff --git a/src/Rosetta/music/it/Itsex.luau b/src/Rosetta/music/it/Itsex.luau index 3a7daca..7176086 100644 --- a/src/Rosetta/music/it/Itsex.luau +++ b/src/Rosetta/music/it/Itsex.luau @@ -1,15 +1,11 @@ --!strict --!native --- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). --- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of --- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. --- --- Never throws: every read is bounds-checked; corrupt streams return nil, message. +-- music/it/Itsex: IT 2.14 / 2.15 (double-delta) sample decompression, from ITTECH.TXT: 0x8000-byte output blocks, each +-- a u16 length then an LSB-first bit stream of deltas with three width-change methods. local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 local Itsex = {} --- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) local out = buffer.create(frames * 4) local blockLen = if bits == 16 then 0x4000 else 0x8000 @@ -34,7 +30,6 @@ function Itsex.decompress(buf: buffer, off: number, limit: number, frames: numbe return nil, "compressed block runs past the end" end p = bend - -- bit reader over [bstart, bend) local bytePos = bstart local bitBuf = 0 local bitCount = 0 @@ -90,7 +85,6 @@ function Itsex.decompress(buf: buffer, off: number, limit: number, frames: numbe continue end end - -- a delta, sign-extended from its width local x = v if width < topWidth then local shift = 2 ^ width diff --git a/src/Rosetta/music/it/init.luau b/src/Rosetta/music/it/init.luau index d271f18..bc58101 100644 --- a/src/Rosetta/music/it/init.luau +++ b/src/Rosetta/music/it/init.luau @@ -1,12 +1,7 @@ --!strict --- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the --- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to --- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or --- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, --- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo --- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. --- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's --- extension chunks (plugins, extended instrument properties), writing. +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT), played through codecs/audio/Tracker. Supports: 64 channels, +-- instrument / sample mode, old and new instrument headers, envelopes, NNAs, resonant filters (default Zxx macros), +-- IT 2.14 / 2.15 compressed samples, the message. Not supported: embedded MIDI macros, OpenMPT extensions, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,7 +21,7 @@ local It = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -173,7 +168,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- channels: the highest one any pattern uses local nch = 1 local packed: { Bytes.Reader? } = {} local rowsOf: { number } = {} @@ -187,7 +181,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end local data = pr:slice(len) packed[p], rowsOf[p] = data, rows - -- scan for the channel count local scan = data:sub(0) local seen: { [number]: number } = {} while not scan:eof() do @@ -258,7 +251,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local mr = r:sub(msgOff, msgLen) m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") end - -- instruments for i = 1, insnum do local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) if not ins then @@ -266,7 +258,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end m.instruments[i] = ins end - -- samples local total = 0 for i = 1, smpnum do local h = r:sub(smpOff[i], 80) @@ -348,7 +339,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(rowsOf[p], nch) m.patterns[p] = pat @@ -415,7 +405,6 @@ function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = It.decode(r, opts) if not m then diff --git a/src/Rosetta/music/med/init.luau b/src/Rosetta/music/med/init.luau index 0956498..fb4154a 100644 --- a/src/Rosetta/music/med/init.luau +++ b/src/Rosetta/music/med/init.luau @@ -1,14 +1,7 @@ --!strict --- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks, --- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song --- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL --- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks --- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop --- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave --- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops, --- default pitch, volume). --- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and --- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing. +-- music/med: MED / OctaMED modules (MMD0..MMD3), ported from OpenMPT's Load_med.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); the first song plays as the "xm" family with Amiga periods. Supports: 1..64 tracks, +-- play sequences, hold / decay, IFF multi-octave samples. Not supported: synth / MIDI instruments, echo, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,7 +21,7 @@ local Med = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -78,7 +71,7 @@ end -- ------------------------------------------------------------------------------------------------ decode type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean } --- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes) +-- OpenMPT's MMDTempoToBPM (SPD / 8-channel / BPM modes) local function tempoToBpm(tempo: number, ctx: Ctx): number if ctx.bpm and not ctx.is8Ch then return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4 @@ -93,7 +86,7 @@ local function tempoToBpm(tempo: number, ctx: Ctx): number return tempo / 0.264 end --- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect) +-- MED command -> MOD / XM effect, param, note-cut flag: OpenMPT's ConvertMEDEffect local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean) local lo = math.min(p, 15) if cmd == 1 or cmd == 2 then @@ -179,7 +172,7 @@ local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolea return 0, 0, false end --- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping) +-- OpenMPT's octave wrapping local function wrapNote(note: number, vol7bit: boolean): number local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) if n > 132 and not vol7bit then @@ -190,7 +183,6 @@ local function wrapNote(note: number, vol7bit: boolean): number return if n >= 13 then n - 12 else 0 end --- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean) local br = r:sub(off) local ntracks, nrows, info @@ -300,7 +292,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if numSamples > 0 and smpOff == 0 then return nil, Err.new(Err.CORRUPT, "no sample table") end - -- channels: the widest block (at least 4) local nch = 4 local blockPtr: { number } = {} for b = 0, numBlocks - 1 do @@ -339,7 +330,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if ext.nameOff > 0 and ext.nameLen > 0 then m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) end - -- instruments and samples local needInstruments = false local instruments, samples = {}, {} local unsupported = {} @@ -419,7 +409,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- sample data local list = {} for i = 0, count - 1 do local s = Tracker.newSample(name) @@ -454,7 +443,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) frames, ls, le = frames * 2, ls * 2, le * 2 end end - -- the instrument extras if xsize > 0 then if x.hold > 0 and not isSynth then local env = Tracker.newEnvelope() @@ -591,7 +579,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end m.preamp = preamp - -- tempo, speed, volume, the pattern context local ctx: Ctx = { transpose = 36 + playTranspose - (if version > 2 then 24 else 0), is8Ch = bit32.band(flags, 0x40) ~= 0, @@ -606,7 +593,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if masterVol > 0 then m.globalVolume = math.min(masterVol, 64) * 2 end - -- blocks for b = 0, numBlocks - 1 do local p = blockPtr[b + 1] local pat, high = nil, false @@ -620,7 +606,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) for at, to in jumps do local prev = m.order[at - 1] if prev and prev < 254 and m.patterns[prev + 1] then - -- the block may be played elsewhere: give this order entry its own copy local src = m.patterns[prev + 1] local cp = Tracker.newPattern(src.rows, nch) buffer.copy(cp.data, 0, src.data) @@ -649,7 +634,6 @@ function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Med.decode(r, opts) if not m then diff --git a/src/Rosetta/music/midi/Smf.luau b/src/Rosetta/music/midi/Smf.luau index fc7dfac..85d99c1 100644 --- a/src/Rosetta/music/midi/Smf.luau +++ b/src/Rosetta/music/midi/Smf.luau @@ -1,10 +1,6 @@ --!strict --- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE --- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps --- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are --- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the --- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track --- has none. Written from the SMF 1.0 specification (no third-party code). +-- music/midi/Smf: SMF 1.0 MThd / MTrk <-> Types.Midi (running status also across meta / sysex, RIFF RMID unwrapped). +-- Writes what python mido writes: running status reset after meta / sysex, one end-of-track, track names at tick 0. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -43,13 +39,11 @@ end Smf.text = text -- ------------------------------------------------------------------------------------------------ read --- one MTrk body [p, e): events | nil, message, truncated local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) local events: { Types.MidiEvent } = {} local tick = 0 local running = 0 while p < e do - -- delta time local delta, n = 0, 0 repeat if p >= e then @@ -140,7 +134,6 @@ local function readTrack(b: buffer, p: number, e: number, budget: { number }): ( return events, nil, false end --- read(r, opts?) -> Midi | nil, Err function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) local strict = opts and opts.strict or false local budget = { opts and opts.maxEvents or 2 ^ 24 } @@ -267,7 +260,6 @@ local function byteList(d: any, want: number?): { number }? return d end --- write(midi, opts?) -> buffer | nil, Err function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) if type(midi) ~= "table" or type(midi.tracks) ~= "table" then return nil, Err.new(Err.ARG, "needs a Midi value with tracks") @@ -298,7 +290,6 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) if type(events) ~= "table" then return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list") end - -- stable order by tick local sorted = true local last = 0 for i, ev in events do @@ -324,7 +315,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) return order[a] < order[c] end) end - -- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own +-- a track-name meta event (0x03) at tick 0 when the track has none (as mido) if type(track.name) == "string" and track.name ~= "" then local named = false for _, ev in list do diff --git a/src/Rosetta/music/midi/init.luau b/src/Rosetta/music/midi/init.luau index 1611da1..0d6c0c0 100644 --- a/src/Rosetta/music/midi/init.luau +++ b/src/Rosetta/music/midi/init.luau @@ -1,14 +1,7 @@ --!strict --- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the --- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port). --- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / --- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, --- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke: --- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to --- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), encode (running --- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and --- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. --- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). +-- music/midi: Standard MIDI Files (SMF 1.0 formats 0 / 1 / 2, PPQ and SMPTE; RIFF RMID read), from the spec. Supports: +-- decode to a Types.Midi, .kar lyrics, encode (byte-identical to python mido by default), the tempo map, rendering +-- through codecs/audio/SoundFont. Not supported: RMID write, XMF / DLS banks, system common bytes in tracks. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,7 +23,7 @@ local Midi = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24) export type EncodeOptions = Smf.WriteOptions -- runningStatus (default true) -export type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices +export type RenderOptions = Render.RenderOptions -- ------------------------------------------------------------------------------------------------ sniff function Midi.sniff(r: Bytes.Reader): number @@ -44,8 +37,7 @@ function Midi.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and --- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags +-- .kar: FF 01 text in a "Words" track (or after an "@K" / "@T" header) and FF 05 lyrics; "@X" headers -> meta.karaoke[X] local function karaoke(midi: Types.Midi) local lyrics: { { time: number, tick: number, text: string } } = {} local headers: { [string]: { string } } = {} @@ -119,7 +111,6 @@ function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err? end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Midi.decode(r, opts) if not midi then @@ -129,26 +120,22 @@ function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) return Render.decoder(midi, opts) end --- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number return Render.seconds(Render.tempoMap(midi, track), tick) end --- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) Midi.tempoMap = Render.tempoMap Midi.seconds = Render.seconds --- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +-- as python mido's MidiFile.length (formats 0 / 1) function Midi.length(midi: Types.Midi): number return Render.length(midi) end --- text(data) -> the bytes of a text meta event as a string Midi.text = Smf.text return Midi diff --git a/src/Rosetta/music/mod/init.luau b/src/Rosetta/music/mod/init.luau index 1309897..e2fe34e 100644 --- a/src/Rosetta/music/mod/init.luau +++ b/src/Rosetta/music/mod/init.luau @@ -1,11 +1,7 @@ --!strict --- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, --- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or --- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through --- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" --- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). --- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter --- (E0x), PowerPacker-packed files. +-- music/mod: ProTracker / NoiseTracker / StarTrekker MODs (M.K., M!K!, FLT4, xCHN, xxCH, xxCN, CD81, OKTA, TDZx; +-- 15-sample Soundtracker by name or extension), from the ProTracker 2.3 docs. Writes 31-sample MODs from "mod" modules +-- and XM ones that fit. Not supported: FLT8's split patterns (read as 8 channels), the E0x filter, PowerPacker files. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,7 +20,7 @@ local Mod = { } export type DecodeOptions = { - maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) + maxBytes: number?, -- f32 bytes of sample data in total, default 64 MB } export type EncodeOptions = {} @@ -46,7 +42,7 @@ local FIXED: { [string]: number } = { ["EXO8"] = 8, } --- channels from the 4-byte signature at 1080, or nil +-- the 4-byte signature at offset 1080 local function signatureChannels(sig: string): number? local fixed = FIXED[sig] if fixed then @@ -143,7 +139,6 @@ function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.restart = if restart < songLength then restart else 0 m.meta.signature = if nsamples == 31 then sig else nil m.flags.amigaLimits = nch == 4 - -- patterns local npat = maxPat + 1 local patBytes = 64 * nch * 4 if not r:need(npat * patBytes) then @@ -168,7 +163,7 @@ function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.patterns[p + 1] = pat end r:skip(npat * patBytes) - -- sample data (8-bit signed; the last samples of a truncated file are cut short) +-- sample data: 8-bit signed local total = 0 for i = 1, nsamples do local s = m.samples[i] @@ -206,8 +201,6 @@ local function writeName(w: Bytes.Writer, s: string, n: number) w:fill(0, n - #t) end --- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to --- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) local ok, verr = Tracker.validate(m) if not ok then @@ -220,7 +213,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) if nch > 32 then return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") end - -- the sample for each instrument number local smpOf: { any } = {} if m.format == "xm" then for i, ins in m.instruments do @@ -273,7 +265,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) local len = math.min(s.length, 131070) local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) if s.channels == 2 then - -- mix stereo samples down local mono = buffer.create(len * 4) for k = 0, len - 1 do buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) @@ -349,7 +340,6 @@ function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Mod.decode(r, opts) if not m then diff --git a/src/Rosetta/music/mtm/init.luau b/src/Rosetta/music/mtm/init.luau index 622dea1..e8b4d8d 100644 --- a/src/Rosetta/music/mtm/init.luau +++ b/src/Rosetta/music/mtm/init.luau @@ -1,10 +1,7 @@ --!strict --- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared --- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM): --- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk --- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row). --- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing. +-- music/mtm: MultiTracker modules (MTM, 1..32 channels, patterns of shared tracks), ported from OpenMPT's Load_mtm.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "xm" family with Amiga periods, as OpenMPT does. Not supported: +-- MultiTracker's E9x / EDx retrigger timing and vibrato start phase (played as in XM), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,7 +21,7 @@ local Mtm = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -104,7 +101,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) for i = 1, nch do m.channelPan[i] = (pans[i] % 16) * 16 + 8 end - -- samples local sizes: { number } = {} for i = 1, numSamples do local s = Tracker.newSample(r:fixed(22)) @@ -135,7 +131,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.length = frames m.samples[i] = s end - -- the order list for i = 1, 128 do local o = r:u8() if i <= lastOrder + 1 then @@ -214,7 +209,6 @@ function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Mtm.decode(r, opts) if not m then diff --git a/src/Rosetta/music/mus/init.luau b/src/Rosetta/music/mus/init.luau index c4c1ee3..5ee9290 100644 --- a/src/Rosetta/music/mus/init.luau +++ b/src/Rosetta/music/mus/init.luau @@ -1,13 +1,7 @@ --!strict --- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format --- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter --- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel --- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at --- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without --- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per --- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont / --- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate. --- Not supported: writing (save as .mid through the midi format's encoder). +-- music/mus: DMX MUS ("MUS\x1a"; Doom, Heretic, Hexen, Strife), from Vladimir Arnost's "MUS File Format" (wildmidi +-- only as a test reference). Decodes to a Types.Midi as the usual converters map it (MUS channel 15 -> 9; 140 ticks/s +-- as division 70 at 500000 us per quarter). Not supported: writing (encode as .mid with the midi format). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -43,7 +37,6 @@ end -- ------------------------------------------------------------------------------------------------ decode local readu8 = buffer.readu8 --- the score [p, e) -> events | nil, message local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean) local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } } local map: { [number]: number } = { [15] = 9 } @@ -151,7 +144,6 @@ function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Mus.decode(r, opts) if not midi then diff --git a/src/Rosetta/music/okt/init.luau b/src/Rosetta/music/okt/init.luau index 58d9d83..2cbadfd 100644 --- a/src/Rosetta/music/okt/init.luau +++ b/src/Rosetta/music/okt/init.luau @@ -1,11 +1,7 @@ --!strict --- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can --- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style --- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with --- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample --- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once: --- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume. --- Not supported: the Amiga LED filter (F), writing. +-- music/okt: Oktalyzer modules (OKTASONG, 4..8 channels: each Amiga channel may be a mixed pair), ported from OpenMPT's +-- Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, loops as sustain +-- loops (released by R), the three arpeggios and note slides. Not supported: the LED filter (F), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,7 +22,7 @@ local Okt = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -39,7 +35,6 @@ function Okt.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a negative arpeggio offset as the equivalent positive one local function invert(p: number): number p %= 16 if p == 0 then @@ -48,7 +43,6 @@ local function invert(p: number): number return if p <= 12 then 12 - p else 24 - p end --- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean) if e == 1 and p > 0 then return "portaup", p, -1, false -- "portamento down (period)": the period goes down @@ -274,7 +268,6 @@ function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Okt.decode(r, opts) if not m then diff --git a/src/Rosetta/music/ptm/init.luau b/src/Rosetta/music/ptm/init.luau index f24eb73..10a438b 100644 --- a/src/Rosetta/music/ptm/init.luau +++ b/src/Rosetta/music/ptm/init.luau @@ -1,11 +1,7 @@ --!strict --- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD --- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the --- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx --- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger, --- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the --- byte stream, as PolyTracker stores them), ping-pong loops. --- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. +-- music/ptm: PolyTracker modules (PTMF, up to 32 channels), ported from OpenMPT's Load_ptm.cpp (BSD, +-- licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts PTM. Not supported: +-- reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,7 +21,7 @@ local Ptm = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -59,7 +55,6 @@ local function delta16(buf: buffer, off: number, frames: number, limit: number): return raw, n end --- a PolyTracker effect -> name?, param local function effect(cmd: number, param: number): (string?, number) if cmd == 0x10 then return "globalvol", math.min(param, 0x40) * 2 @@ -154,7 +149,6 @@ function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- samples local buf = r.buf for i = 1, nsmp do local h = r:slice(80) @@ -215,7 +209,6 @@ function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Ptm.decode(r, opts) if not m then diff --git a/src/Rosetta/music/s3m/init.luau b/src/Rosetta/music/s3m/init.luau index 0852553..6b14b5d 100644 --- a/src/Rosetta/music/s3m/init.luau +++ b/src/Rosetta/music/s3m/init.luau @@ -1,10 +1,7 @@ --!strict --- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism --- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio --- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning --- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 --- speed reference, as IT shows S3M files). --- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC). Supports: 32 PCM channels, 8 / 16-bit mono / stereo +-- samples, the panning table, ST3.00 fast slides, every ST3 effect; notes stored an octave up (S3M C-4 = note 61, as IT +-- shows S3M files). Not supported: AdLib (OPL) instruments (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +20,7 @@ local S3m = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -86,7 +83,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } - -- orders, parapointers, panning r:seek(96) for i = 1, ordnum do local o = r:u8() @@ -126,7 +122,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) m.channelPan[i] = pan m.channelMute[i] = c >= 16 end - -- samples local total = 0 local unsigned = ffi ~= 1 for i = 1, insnum do @@ -154,7 +149,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1 local off = (hi * 65536 + lo) * 16 len = math.min(len, 2 ^ 26) - -- a short file: keep what is there local avail = math.max(0, r:size() - off) // (nchs * bits // 8) len = math.min(len, avail) total += len * nchs * 4 @@ -170,7 +164,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- patterns for p = 1, patnum do local pat = Tracker.newPattern(64, nch) m.patterns[p] = pat @@ -230,7 +223,6 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = S3m.decode(r, opts) if not m then diff --git a/src/Rosetta/music/sf2/init.luau b/src/Rosetta/music/sf2/init.luau index f03a2a2..aac7027 100644 --- a/src/Rosetta/music/sf2/init.luau +++ b/src/Rosetta/music/sf2/init.luau @@ -1,9 +1,7 @@ --!strict --- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the --- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), --- presets / instruments / sample headers with global zones, generator merging into playable regions. --- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). --- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 spec), read-only, over codecs/audio/SoundFont (a TinySoundFont port). +-- Supports: INFO, 16 / 24-bit (sm24) samples, presets / instruments with global zones, generators merged into regions. +-- Not supported: writing, SF3 (Vorbis samples), modulators (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -37,7 +35,6 @@ function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont end -- ------------------------------------------------------------------------------------------------ extras --- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) Sf2.synth = SoundFont.synth Sf2.fallback = SoundFont.fallback diff --git a/src/Rosetta/music/stm/init.luau b/src/Rosetta/music/stm/init.luau index ec82b94..cad5581 100644 --- a/src/Rosetta/music/stm/init.luau +++ b/src/Rosetta/music/stm/init.luau @@ -1,10 +1,7 @@ --!strict --- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples). --- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module --- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the --- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump --- happens at the end of the pattern or at the next Cxx). --- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing. +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro), ported from OpenMPT's +-- Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt); played as the "s3m" family with ST2's tempo, no effect memory and +-- its deferred Bxx. Not supported: STX, ST2's noise for samples at volume 0 (silent), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,7 +21,7 @@ local Stm = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -221,7 +218,6 @@ function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Stm.decode(r, opts) if not m then diff --git a/src/Rosetta/music/ult/init.luau b/src/Rosetta/music/ult/init.luau index 7f9f004..698b075 100644 --- a/src/Rosetta/music/ult/init.luau +++ b/src/Rosetta/music/ult/init.luau @@ -1,12 +1,7 @@ --!strict --- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored --- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt). --- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects --- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect --- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone --- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune. --- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the --- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing. +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004, up to 32 channels), ported from OpenMPT's Load_ult.cpp +-- (BSD, licenses/openmpt-LICENSE.txt); played as the "it" family with Amiga periods, as OpenMPT converts ULT. Not +-- supported: reverse (5x2), "no loop" (5x1), E0x, offsets past 64 KiB, pre-1.4 log volumes, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,7 +21,7 @@ local Ult = { } export type DecodeOptions = { - maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) + maxBytes: number?, -- f32 bytes of sample data in total, default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -45,7 +40,7 @@ function Ult.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +-- OpenMPT's TranslateULTCommands local function translate(e: number, param: number, version: number): (string?, number) local name = EFFECTS[e] if e == 0 then @@ -94,7 +89,7 @@ local function translate(e: number, param: number, version: number): (string?, n return name, param end --- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +-- OpenMPT's CombineEffects (volume slide + vibrato / tone portamento without a parameter) local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number) if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0 @@ -104,8 +99,7 @@ local function combine(a: string?, pa: number, b: string?, pb: number): (string? return a, pa, b, pb end --- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param, --- lost global effect (name?, param) +-- event: [0xFC repeat] note instrument effects param1 param2 local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number) local rep = 1 local b = r:u8() @@ -297,7 +291,6 @@ function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Ult.decode(r, opts) if not m then diff --git a/src/Rosetta/music/umx/init.luau b/src/Rosetta/music/umx/init.luau index 6f3f971..82c172b 100644 --- a/src/Rosetta/music/umx/init.luau +++ b/src/Rosetta/music/umx/init.luau @@ -1,12 +1,7 @@ --!strict --- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package --- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): --- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each --- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first --- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and --- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is --- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it. --- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing. +-- music/umx: Unreal Engine 1 music packages (.umx, versions up to 128), ported from OpenMPT's UMXTools.cpp / +-- ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): the IT / S3M / XM / MOD module of a "music" export; decode +-- needs opts.decodeModule (the api passes it). Not supported: Unreal Engine 2+ packages (.uax), writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,8 +20,8 @@ local Umx = { } export type DecodeOptions = { - decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, -- loads the inner module (the api passes it) - index: number?, -- which music export to load (1-based, default 1) + decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, + index: number?, -- 1-based, default 1 } export type Entry = { name: string, data: buffer, format: string? } @@ -104,8 +99,6 @@ function Umx.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format: --- a guess from the inner module's signature: "it", "s3m", "xm", "mod") function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?) local h = header(r) if not h then @@ -210,7 +203,6 @@ function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Umx.decode(r, opts) if not m then diff --git a/src/Rosetta/music/xm/init.luau b/src/Rosetta/music/xm/init.luau index 124701c..bc3efe3 100644 --- a/src/Rosetta/music/xm/init.luau +++ b/src/Rosetta/music/xm/init.luau @@ -1,12 +1,7 @@ --!strict --- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / --- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and --- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit --- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga --- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files --- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). --- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's --- stereo-sample / extra-effect extensions on write. +-- music/xm: FastTracker 2 Extended Modules (XM 1.04), from the XM spec and FT2 behaviour notes. Supports: 8 / 16-bit +-- delta and ModPlug ADPCM samples, envelopes, linear / Amiga tables, every FT2 effect; writes "xm" (byte-identical in +-- FT2's layout) and "mod" modules. Not supported: OpenMPT's stereo-sample / extra-effect extensions on write. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -63,7 +58,6 @@ local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: numb e.loop = bit32.band(typ, 4) ~= 0 e.susStart, e.susEnd = sus + 1, sus + 1 e.loopStart, e.loopEnd = ls + 1, le + 1 - -- the raw fields, for a faithful re-save e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } return e end @@ -106,7 +100,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end m.meta.tracker = tracker m.meta.source = { format = "xm", tracker = tracker, version = version } - -- patterns if not r:seek(hdrStart + hdrSize) then return nil, r.err end @@ -158,7 +151,7 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) param = pr:u8() end if pr.err then - break -- a short pattern: the rest stays empty + break end if note == 97 then note = 255 @@ -177,7 +170,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- instruments and their samples local total = 0 for i = 1, nins do local start = r:tell() @@ -186,7 +178,6 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) r:u8() local ns = r:u16le() if r.err then - -- a file cut inside the instruments: keep what was read r.err = nil break end @@ -243,8 +234,7 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) s.pan = h.pan local frames = h.len // bps if h.res == 0xAD and bits == 8 then - -- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps - -- the samples whose nibbles are present +-- ModPlug ADPCM: a 16-byte delta table, then 4 bits per sample frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) total += frames * 4 if total > maxBytes then @@ -300,7 +290,6 @@ local function writeName(w: Bytes.Writer, s: string?, n: number) w:fill(0, n - #t) end --- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } local function instrumentsOf(m: any): ({ any }?, string?) local out = {} if m.format == "mod" then @@ -365,7 +354,7 @@ local function envelopeFields(e: any): (number, number, number, number, number) local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0) local raw = e.raw if raw and raw.type % 8 == typ then - typ = raw.type -- keep unknown bits + typ = raw.type end local function idx(v: number): number return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) @@ -378,7 +367,6 @@ local function envelopeFields(e: any): (number, number, number, number, number) return n, typ, sus, ls, le end --- encode(module, opts) -> XM bytes ("xm" or "mod" modules) function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) local ok, verr = Tracker.validate(m) if not ok then @@ -479,7 +467,6 @@ function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) w:u16le(buffer.len(data)) w:bytes(data) end - -- instruments for _, it in insts do local ins = it.ins local smps = it.samples @@ -561,7 +548,6 @@ function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local m, err = Xm.decode(r, opts) if not m then diff --git a/src/Rosetta/music/xmi/init.luau b/src/Rosetta/music/xmi/init.luau index c559028..5577258 100644 --- a/src/Rosetta/music/xmi/init.luau +++ b/src/Rosetta/music/xmi/init.luau @@ -1,12 +1,7 @@ --!strict --- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs, --- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description --- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track, --- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's --- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second --- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the --- first tempo event's value, unused). Renders through codecs/audio/MidiRender. --- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping. +-- music/xmi: Miles XMIDI (IFF: optional FORM XDIR, then CAT XMID of FORM XMID songs with TIMB / RBRN / EVNT), from +-- the XMIDI notes (Miles AIL, Ryan Nunn; wildmidi only as a test reference). Decodes one song to a Types.Midi at the +-- fixed 120 ticks per second (division 60). Not supported: writing, the RBRN branch table, MT-32 -> GM mapping. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -45,7 +40,6 @@ local readu8 = buffer.readu8 local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } --- a MIDI variable-length number at p -> value, next p (nil past e) local function vlq(b: buffer, p: number, e: number): (number?, number) local v = 0 for _ = 1, 4 do @@ -70,7 +64,6 @@ local function bytes(b: buffer, p: number, n: number): { number } return t end --- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?) local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} local tick, tempo = 0, nil @@ -137,7 +130,6 @@ local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Ty return Render.merge(list, offs), tick, tempo end --- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } } local out = {} local function form(c: Chunks.Chunk) @@ -203,7 +195,6 @@ function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Er end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) local midi, err = Xmi.decode(r, opts) if not midi then diff --git a/src/Rosetta/playlist/m3u/init.luau b/src/Rosetta/playlist/m3u/init.luau index 69a050f..592dcda 100644 --- a/src/Rosetta/playlist/m3u/init.luau +++ b/src/Rosetta/playlist/m3u/init.luau @@ -1,16 +1,7 @@ --!strict --- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no --- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain --- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / --- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media --- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, --- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base --- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, --- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. --- --- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" }) --- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls" --- local out = M3u.encode(pl, { title = "My Mix" }) +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists, absorbed from playlist-luau 3fc7fd3 (same author). Supports: +-- #EXTM3U / #EXTINF / #PLAYLIST, plain lists, BOM, CRLF / CR, Windows-1252, HLS master and media playlists; locations +-- resolve per RFC 3986; mp3 HLS segments are playable, .ts / .aac / fMP4 are flagged. Not supported: writing HLS tags. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,13 +25,12 @@ local M3u = { export type Entry = { url: string, title: string?, - duration: number?, -- seconds; nil when unknown (-1 in the file) - playable: boolean, -- an http(s) URL the player can fetch - reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... - -- HLS - bandwidth: number?, -- master: BANDWIDTH - codecs: string?, -- master: CODECS - attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + duration: number?, -- seconds; -1 in the file = unknown + playable: boolean, + reason: string?, + bandwidth: number?, -- BANDWIDTH + codecs: string?, -- CODECS + attributes: { [string]: string }?, -- EXT-X-STREAM-INF / EXT-X-MEDIA attribute list byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE } @@ -48,10 +38,10 @@ export type Hls = { master: boolean, targetDuration: number?, mediaSequence: number?, - endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + endList: boolean, -- EXT-X-ENDLIST (false = live) encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE - totalDuration: number?, -- media: sum of the segment durations - segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" + totalDuration: number?, + segmentFormat: string?, } export type Result = { @@ -60,13 +50,13 @@ export type Result = { meta: { [string]: any }, entries: { Entry }, warnings: { string }, - title: string?, -- #PLAYLIST: / PLS has none + title: string?, -- #PLAYLIST: hls: Hls?, } export type DecodeOptions = { - baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries - maxBytes: number?, -- refuse bigger files (default 64 MB) + baseUrl: string?, + maxBytes: number?, -- default 64 MB } export type EncodeOptions = { title: string?, -- #PLAYLIST: (default: the playlist's title) @@ -75,7 +65,6 @@ export type EncodeOptions = { -- ------------------------------------------------------------------------------------------------ constants local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } --- The extension of a URL's path (lower case), or nil local function extension(url: string): string? local p = Url.split(url).path local ext = string.match(p, "%.([%w]+)$") @@ -301,7 +290,6 @@ local function parseHls(ls: { string }, base: string?, baseScheme: string?, warn return res end --- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -326,8 +314,6 @@ function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Er end -- ------------------------------------------------------------------------------------------------ encode --- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:,). Durations are rounded; unknown = -1. --- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces. local function serialize(entries: { any }, opts: { title: string? }?): string local out = { "#EXTM3U" } local function clean(s: string): string @@ -350,8 +336,6 @@ local function serialize(entries: { any }, opts: { title: string? }?): string return table.concat(out, "\n") .. "\n" end --- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of --- entries ({ url, title?, duration? }) function M3u.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") diff --git a/src/Rosetta/playlist/pls/init.luau b/src/Rosetta/playlist/pls/init.luau index 38f91de..0553288 100644 --- a/src/Rosetta/playlist/pls/init.luau +++ b/src/Rosetta/playlist/pls/init.luau @@ -1,12 +1,7 @@ --!strict --- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from --- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case --- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a --- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local / --- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. --- --- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) --- local out = Pls.encode(pl) +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version), absorbed from +-- playlist-luau 3fc7fd3 (same author) plus a new writer. Supports: keys in any case / order, comments, BOM, CRLF / CR, +-- Windows-1252, numbering gaps; locations resolve per RFC 3986. Encode: Version=2, Length -1 for unknown durations. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,13 +25,12 @@ local Pls = { export type Entry = { url: string, title: string?, - duration: number?, -- seconds; nil when unknown (-1 in the file) - playable: boolean, -- an http(s) URL the player can fetch - reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... - -- HLS - bandwidth: number?, -- master: BANDWIDTH - codecs: string?, -- master: CODECS - attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + duration: number?, -- seconds; -1 in the file = unknown + playable: boolean, + reason: string?, + bandwidth: number?, -- BANDWIDTH + codecs: string?, -- CODECS + attributes: { [string]: string }?, -- EXT-X-STREAM-INF / EXT-X-MEDIA attribute list byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE } @@ -44,10 +38,10 @@ export type Hls = { master: boolean, targetDuration: number?, mediaSequence: number?, - endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + endList: boolean, -- EXT-X-ENDLIST (false = live) encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE - totalDuration: number?, -- media: sum of the segment durations - segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" + totalDuration: number?, + segmentFormat: string?, } export type Result = { @@ -56,13 +50,13 @@ export type Result = { meta: { [string]: any }, entries: { Entry }, warnings: { string }, - title: string?, -- #PLAYLIST: / PLS has none + title: string?, -- #PLAYLIST: hls: Hls?, } export type DecodeOptions = { - baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries - maxBytes: number?, -- refuse bigger files (default 64 MB) + baseUrl: string?, + maxBytes: number?, -- default 64 MB } -- ------------------------------------------------------------------------------------------------ constants @@ -129,7 +123,6 @@ local function parsePls(ls: { string }, base: string?, baseScheme: string?, warn return res end --- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -153,8 +146,6 @@ function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Er end -- ------------------------------------------------------------------------------------------------ encode --- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a --- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces. function Pls.encode(value: any, _opts: any?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") diff --git a/src/Rosetta/playlist/xspf/init.luau b/src/Rosetta/playlist/xspf/init.luau index f42ea8b..b308b61 100644 --- a/src/Rosetta/playlist/xspf/init.luau +++ b/src/Rosetta/playlist/xspf/init.luau @@ -1,15 +1,7 @@ --!strict --- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in rosetta (playlist-luau --- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, --- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, --- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; --- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other --- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. +-- playlist/xspf: XSPF 1 (https://xspf.org/spec) playlists on codecs/text/Xml. Supports: playlist and track metadata, +-- every track location (entry.locations), duration (ms), xml:base then opts.baseUrl (RFC 3986). -- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. --- --- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" }) --- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end --- local out = Xspf.encode(pl) -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,8 +22,8 @@ local Xspf = { -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { - baseUrl: string?, -- the playlist's own URL (or Windows path), for relative locations - maxBytes: number?, -- refuse bigger files (default 64 MB) + baseUrl: string?, + maxBytes: number?, -- default 64 MB } -- ------------------------------------------------------------------------------------------------ constants @@ -43,7 +35,6 @@ local function trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end --- the text of the first child element with this local name, trimmed (nil when missing or empty) local function field(node: any, name: string): string? for _, c in node.children do if type(c) == "table" and Xml.localName(c.name) == name then @@ -75,8 +66,6 @@ function Xspf.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd --- tracks become warnings) function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) local n = r.limit - r.pos if n > (opts and opts.maxBytes or 2 ^ 26) then @@ -161,8 +150,6 @@ function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, E end -- ------------------------------------------------------------------------------------------------ encode --- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list --- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints. function Xspf.encode(value: any, opts: { indent: number?, title: string? }?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") diff --git a/src/Rosetta/subtitle/ass/init.luau b/src/Rosetta/subtitle/ass/init.luau index 8c454fb..0517207 100644 --- a/src/Rosetta/subtitle/ass/init.luau +++ b/src/Rosetta/subtitle/ass/init.luau @@ -1,14 +1,7 @@ --!strict --- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of --- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles] --- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the --- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any --- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times. --- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become --- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw. --- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it, --- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. Not supported: --- rendering, karaoke timing (\k overrides are dropped from text, kept in cue.raw), embedded font / graphic decoding. +-- subtitle/ass: ASS (v4.00+) / SSA (v4.00) scripts (de-facto spec of Aegisub / libass / ffmpeg). Supports: Script +-- Info, Styles, Events (Dialogue / Comment), other sections verbatim, H:MM:SS.cc; {\i1} {\b1} {\u1} {\s1} as the shared +-- markup (cue.raw keeps the original). Not supported: rendering, karaoke timing (\k), embedded font / graphic decoding. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,10 +20,10 @@ local Ass = { } export type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } export type EncodeOptions = { - crlf: boolean?, -- CRLF line ends (default false) + crlf: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants @@ -63,7 +56,6 @@ local STYLE_DEFAULT: { [string]: string } = { Encoding = "0", } local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" } --- event fields -> cue keys (the rest keep their field name) local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" } local function trim(s: string): string @@ -78,7 +70,6 @@ local function fields(s: string): { string } return out end --- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil local function time(s: string): number? local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") if not h then @@ -88,7 +79,6 @@ local function time(s: string): number? return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + fr end --- ASS text -> the shared markup local TAGS = { i = "i", b = "b", u = "u", s = "s" } function Ass.toMarkup(raw: string): string local open: { [string]: boolean } = {} @@ -129,7 +119,6 @@ function Ass.toMarkup(raw: string): string return out end --- the shared markup -> ASS text function Ass.fromMarkup(text: string): string local s = string.gsub(text, "\r\n?", "\n") s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close: string, tag: string): string @@ -192,7 +181,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E end if section == "script info" then if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then - table.insert(infoOrder, line) -- a comment line, kept in place + table.insert(infoOrder, line) -- `;` / `!` comment line, kept in place else local k, v = string.match(line, "^([^:]+):%s?(.*)$") if k then @@ -265,7 +254,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E end if ok then if k == "Comment" then - cue.after = #subs.cues -- written back after that many dialogue lines + cue.after = #subs.cues table.insert(comments, cue) else table.insert(subs.cues, cue :: any) @@ -286,7 +275,6 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E subs.meta.comments = comments end if #sections > 0 then - -- drop trailing blank lines (the writer adds its own) for _, sec in sections do while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do table.remove(sec.lines) @@ -336,7 +324,6 @@ function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err. end table.sort(rest) table.move(rest, 1, #rest, #out + 1, out) - -- styles local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00" local sfmt: { string } = if type(meta.styleFormat) == "table" then meta.styleFormat else STYLE_FORMAT table.insert(out, "") @@ -374,7 +361,6 @@ function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err. end table.insert(out, "Style: " .. table.concat(vals, ",")) end - -- events local efmt: { string } = if type(meta.eventFormat) == "table" then meta.eventFormat else EVENT_FORMAT if efmt[#efmt] ~= "Text" then return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text") diff --git a/src/Rosetta/subtitle/srt/init.luau b/src/Rosetta/subtitle/srt/init.luau index 79c95d5..05d9518 100644 --- a/src/Rosetta/subtitle/srt/init.luau +++ b/src/Rosetta/subtitle/srt/init.luau @@ -1,11 +1,7 @@ --!strict --- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or --- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing --- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends --- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> / --- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text. --- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends. --- Not supported: positioning beyond keeping the coordinates; the tags are not validated. +-- subtitle/srt: SubRip text (de-facto; matches ffmpeg's srt demuxer / muxer). Supports: numbered or unnumbered +-- cues, `,` / `.` decimals, X1/Y1 coordinates (cue.settings), inner blank lines, BOM, CRLF / CR; text kept as is. +-- Not supported: positioning beyond keeping the coordinates; tags are not validated. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,16 +20,15 @@ local Srt = { } export type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } export type EncodeOptions = { - crlf: boolean?, -- CRLF line ends (default false: LF) + crlf: boolean?, -- default false (LF) } -- ------------------------------------------------------------------------------------------------ constants local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$" --- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary) local function text(r: Bytes.Reader): string? local s = buffer.readstring(r.buf, r.base, r.limit - r.base) if string.find(s, "\0", 1, true) then @@ -49,7 +44,6 @@ local function frac(digits: string): number return (tonumber(digits) :: number) / 10 ^ #digits end --- timing(line) -> start, stop, settings | nil local function timing(line: string): (number?, number?, string?) local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING) if not h1 then @@ -88,7 +82,7 @@ function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E local n = #lines local subs = Types.Subtitles.new() local i = 1 - local function isStart(k: number): boolean -- a cue starts at line k (index + timing, or a timing) + local function isStart(k: number): boolean local l = lines[k] if l == nil then return false @@ -112,7 +106,7 @@ function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E while i <= n do local l = lines[i] if string.match(l, "^%s*$") then - -- blank: the end of the cue unless more text follows before the next cue + -- a blank line ends the cue only before the next index / timing line local k = i while k <= n and string.match(lines[k], "^%s*$") do k += 1 @@ -125,7 +119,7 @@ function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E end i = k elseif timing(l) then - break -- a cue without the blank separator + break else table.insert(body, l) i += 1 @@ -167,7 +161,6 @@ function Srt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err. if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") end - -- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue local body = string.gsub(c.text, "\r\n?", "\n") local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else "" out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl diff --git a/src/Rosetta/subtitle/vtt/init.luau b/src/Rosetta/subtitle/vtt/init.luau index 26dec68..f9ed37c 100644 --- a/src/Rosetta/subtitle/vtt/init.luau +++ b/src/Rosetta/subtitle/vtt/init.luau @@ -1,10 +1,7 @@ --!strict --- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in --- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments --- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept --- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities). --- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text --- are dropped and `-->` escaped (WebVTT cue text cannot hold them). +-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the header (meta.header), cue ids, `[hh:]mm:ss.ttt` timings, +-- cue settings, NOTE (meta.notes), STYLE (meta.css) and REGION (meta.regions) blocks, BOM, CRLF / CR; cue text as +-- written. Encode drops blank lines in cue text and escapes `-->` (cue text cannot hold them). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -23,7 +20,7 @@ local Vtt = { } export type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } export type EncodeOptions = {} @@ -32,7 +29,6 @@ local function frac(digits: string): number return (tonumber(digits) :: number) / 10 ^ #digits end --- one timestamp at the start of s: seconds, the rest | nil local function timestamp(s: string): (number?, string) local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") if h then @@ -45,7 +41,6 @@ local function timestamp(s: string): (number?, string) return nil, s end --- timing(line) -> start, stop, settings | nil local function timing(line: string): (number?, number?, string?) local a, rest = timestamp((string.gsub(line, "^%s+", ""))) if not a then @@ -110,7 +105,6 @@ function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E i += 1 continue end - -- a block: lines up to the next blank local first = i while i <= n and lines[i] ~= "" do i += 1 @@ -160,7 +154,6 @@ local function stamp(t: number): string return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) end --- one block's text: no blank lines (they end a block), no `-->` local function clean(s: string): string s = string.gsub(s, "\r\n?", "\n") s = string.gsub(s, "\n[ \t]*\n", "\n") diff --git a/src/Rosetta/vector/svg/Parse.luau b/src/Rosetta/vector/svg/Parse.luau index a20655c..5189da4 100644 --- a/src/Rosetta/vector/svg/Parse.luau +++ b/src/Rosetta/vector/svg/Parse.luau @@ -1,11 +1,5 @@ --!strict --- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, --- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space --- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into --- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a --- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>. --- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported. --- Never throws. +-- vector/svg/Parse: an SVG document (an Xml tree) to a Types.Vector: the cascade, shapes, paints, groups, clips. local Xml = require("@rosetta/codecs/text/Xml") local Types = require("@rosetta/Types") local Style = require("@rosetta/vector/svg/Style") @@ -59,7 +53,7 @@ type Ctx = { groups: { any }, clips: { any }, unsupported: { [string]: number }, - vw: number, -- the current viewport (for percentages) + vw: number, vh: number, depth: number, useDepth: number, @@ -90,7 +84,7 @@ local function refId(s: string?): string? return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") end --- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style="" +-- cascade: presentation attributes < CSS rules (by specificity, then order) < style="" local function specified(n: Node, ctx: Ctx): { [string]: string } local out: { [string]: string } = {} for k, v in pairs(n.attrs :: any) do @@ -130,7 +124,6 @@ local function specified(n: Node, ctx: Ctx): { [string]: string } return out end --- computed(parent, n) -> the element's computed property strings local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string } local out: { [string]: string } = {} for k in pairs(INHERITED) do @@ -188,7 +181,6 @@ local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } return list end --- a gradient attribute, looked up through href templates local function gattr(g: Node, k: string, ctx: Ctx): string? local cur: Node? = g local guard = 0 @@ -250,7 +242,6 @@ local function gradient(g: Node, opacity: number, ctx: Ctx): any return p end --- paint(value, opacity, st) -> Paint | nil (none) local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any if value == nil then return nil @@ -370,7 +361,6 @@ local function transformOf(n: Node): M return IDENTITY end --- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox. local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number? local cp = ctx.ids[ref] if cp == nil or local_(cp) ~= "clipPath" then @@ -508,7 +498,6 @@ local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: numbe table.insert(ctx.vector.paths, p) end --- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y) function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M if vb == nil or vb[3] <= 0 or vb[4] <= 0 then return { 1, 0, 0, 1, x, y } @@ -553,7 +542,6 @@ local function viewBox(n: Node): { number }? end local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?) - -- a layer for opacity / clip-path local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) local clipRef = refId(st["clip-path"]) local g = group @@ -563,7 +551,6 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe local bbox: { number }? = nil local cp = ctx.ids[clipRef] if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then - -- the group's bounding box in its user space: walk once into a scratch vector local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips local scratch = Types.Vector.new(0, 0) ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} @@ -610,7 +597,7 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe end end --- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own +-- nested svg / symbol: overflow is hidden unless it says otherwise local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number? local ov = attr(n, "overflow") if ov == "visible" or ov == "auto" then @@ -698,7 +685,6 @@ walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: numbe end -- ------------------------------------------------------------------------------------------------ entry --- document(doc, opts) -> Vector | nil, message function Parse.document(doc: any): (Types.Vector?, string?) local root = doc.root if root == nil or Xml.localName(root.name) ~= "svg" then diff --git a/src/Rosetta/vector/svg/PathData.luau b/src/Rosetta/vector/svg/PathData.luau index 7f19860..ec78649 100644 --- a/src/Rosetta/vector/svg/PathData.luau +++ b/src/Rosetta/vector/svg/PathData.luau @@ -1,9 +1,6 @@ --!strict --- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands --- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the --- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a --- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the --- commands so far are kept, as the spec's error handling says). +-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3, SVG 2 "Path data"); arcs to cubics per implementation notes +-- F.6 (out-of-range radii scaled up); parsing stops at the first error, keeping the commands so far (as the spec says). local PathData = {} export type Cmd = { op: string, [number]: number } @@ -13,7 +10,6 @@ local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } --- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd }) if x1 == x2 and y1 == y2 then return @@ -81,14 +77,13 @@ local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: numbe end PathData.arc = arc --- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing) function PathData.parse(d: string): ({ Cmd }, boolean) local out: { Cmd } = {} local i, n = 1, #d - local cx, cy = 0, 0 -- current point - local sx, sy = 0, 0 -- subpath start - local lcx, lcy = 0, 0 -- last control point (for S / T) - local last = "" -- previous command letter (upper case) + local cx, cy = 0, 0 + local sx, sy = 0, 0 + local lcx, lcy = 0, 0 + local last = "" local cmd: string? = nil local rel = false local nums: { number } = table.create(7) :: { number } @@ -249,15 +244,12 @@ function PathData.parse(d: string): ({ Cmd }, boolean) return out, true end --- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box --- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge local px, py = 0, 0 for _, c in cmds do local op = c.op if op == "C" then - -- the curve's exact extrema local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] for axis = 1, 2 do local p0 = if axis == 1 then px else py @@ -328,7 +320,6 @@ function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) return x0, y0, x1, y1 end --- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros) local function num(v: number): string if v ~= v or v == math.huge or v == -math.huge then return "0" @@ -343,7 +334,6 @@ local function num(v: number): string end PathData.num = num --- serialize(cmds) -> path data text function PathData.serialize(cmds: { Cmd }): string local out = {} for _, c in cmds do @@ -360,7 +350,6 @@ function PathData.serialize(cmds: { Cmd }): string return table.concat(out, " ") end --- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } function PathData.toRaster(cmds: { Cmd }): { any } local out = table.create(#cmds) diff --git a/src/Rosetta/vector/svg/Render.luau b/src/Rosetta/vector/svg/Render.luau index 5967d81..113fd27 100644 --- a/src/Rosetta/vector/svg/Render.luau +++ b/src/Rosetta/vector/svg/Render.luau @@ -1,9 +1,5 @@ --!strict --- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd, --- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and --- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat, --- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox --- maps onto the image by meta.preserveAspectRatio. Never throws. +-- vector/svg/Render: a Types.Vector to an rgba8 Image via codecs/image/Raster and codecs/image/Blend. local Types = require("@rosetta/Types") local Raster = require("@rosetta/codecs/image/Raster") local Blend = require("@rosetta/codecs/image/Blend") @@ -42,7 +38,6 @@ local function stopColor(stops: { { number } }, t: number): (number, number, num return s[2], s[3], s[4], s[5] end --- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))? local stops = p.stops if type(stops) ~= "table" or #stops == 0 then @@ -128,7 +123,6 @@ local function gradientFn(p: any, device: M, bbox: { number }?): ((number, numbe end -- ------------------------------------------------------------------------------------------------ dashes --- subpaths of a command list with their closed flag local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } local out = {} local cur: { any }? = nil @@ -151,7 +145,6 @@ local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } return out end --- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol) local function polyline(cmds: { any }, tol: number): { number } local pts: { number } = {} local px, py = 0, 0 @@ -269,16 +262,14 @@ end -- ------------------------------------------------------------------------------------------------ rendering export type Options = { - background: { number }?, -- r, g, b, a under the drawing (default transparent) - tolerance: number?, -- curve flattening in device pixels (default 0.1) + background: { number }?, -- r, g, b, a; default transparent + tolerance: number?, -- device pixels; default 0.1 } --- the device transform scale (for stroke flattening tolerances) local function scaleOf(m: M): number return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) end --- rasterize(v, w, h, opts?) -> rgba8 Image function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image local o: Options = opts or {} local img = Types.Image.new(w, h) @@ -297,7 +288,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?) local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} local tol = o.tolerance or 0.1 local clipCache: { [number]: buffer } = {} - -- a clip's coverage over the whole image (1 byte per pixel) local function clipMask(id: number): buffer? if clipCache[id] then return clipCache[id] @@ -325,7 +315,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?) clipCache[id] = mask return mask end - -- the layer stack: { group id, image } local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } } local function chain(g: number?): { number } local out = {} @@ -365,7 +354,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?) if type(p) ~= "table" or type(p.d) ~= "table" then continue end - -- groups: pop the layers this path is not in, push the ones it needs local want = chain(p.group) local keep = 1 while keep < #stack and stack[keep + 1].id == want[keep] do diff --git a/src/Rosetta/vector/svg/Style.luau b/src/Rosetta/vector/svg/Style.luau index 8b624ca..02126fb 100644 --- a/src/Rosetta/vector/svg/Style.luau +++ b/src/Rosetta/vector/svg/Style.luau @@ -1,9 +1,5 @@ --!strict --- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba / --- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor), --- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated --- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped). --- Never throws. +-- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a <style> CSS subset. local Raster = require("@rosetta/codecs/image/Raster") local Style = {} @@ -57,7 +53,6 @@ local function hue(p: number, q: number, t: number): number return p end --- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value function Style.color(s: string, current: { number }?): any s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1"))) if s == "none" then @@ -136,7 +131,7 @@ function Style.color(s: string, current: { number }?): any return nil end --- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil +-- SVG number: sign? digits? ("." digits)? exponent? local function scan(s: string, i: number): (number?, number) local n = #s local st = i @@ -194,7 +189,6 @@ local function scan(s: string, i: number): (number?, number) return tonumber(string.sub(s, st, i - 1)), i end --- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100) local UNITS: { [string]: number } = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } function Style.length(s: string?, ref: number?, fontSize: number?): number? if s == nil then @@ -219,7 +213,6 @@ function Style.length(s: string?, ref: number?, fontSize: number?): number? return if k then x * k else nil end --- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else function Style.numbers(s: string?): { number } local out = {} if s == nil then @@ -242,7 +235,6 @@ function Style.numbers(s: string?): { number } return out end --- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error local mul = Raster.multiply Style.multiply = mul function Style.transform(s: string): { number }? @@ -285,7 +277,6 @@ function Style.transform(s: string): { number }? return m end --- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped) function Style.declarations(s: string): { [string]: string } local out: { [string]: string } = {} for decl in string.gmatch(s, "[^;]+") do @@ -333,7 +324,6 @@ local function selector(s: string): Selector? return sel end --- css(text, rules?) -> rules (appended to the list given) function Style.css(text: string, rules: { Rule }?): { Rule } local out: { Rule } = rules or {} text = string.gsub(text, "/%*.-%*/", "") @@ -362,7 +352,6 @@ function Style.css(text: string, rules: { Rule }?): { Rule } return out end --- matches(sel, tag, id, classes) -> boolean function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean if sel.tag and sel.tag ~= tag then return false diff --git a/src/Rosetta/vector/svg/Write.luau b/src/Rosetta/vector/svg/Write.luau index f012f15..7844453 100644 --- a/src/Rosetta/vector/svg/Write.luau +++ b/src/Rosetta/vector/svg/Write.luau @@ -1,7 +1,5 @@ --!strict --- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients --- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...> --- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message. +-- vector/svg/Write: a Types.Vector to SVG text; never throws (bad values return nil, message). local Xml = require("@rosetta/codecs/text/Xml") local Types = require("@rosetta/Types") local PathData = require("@rosetta/vector/svg/PathData") @@ -41,7 +39,6 @@ local function matrix(m: any): string? return "matrix(" .. table.concat(parts, " ") .. ")" end --- write(v) -> SVG text | nil, message function Write.vector(v: Types.Vector): (string?, string?) if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then return nil, "needs a Vector value" @@ -51,7 +48,6 @@ function Write.vector(v: Types.Vector): (string?, string?) local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} local defs = {} local gradients = 0 - -- paints -> attribute values (gradients go to defs) local function paintAttrs(p: any, which: string): { { any } } if type(p) ~= "table" then return { { which, "none" } } @@ -109,7 +105,6 @@ function Write.vector(v: Types.Vector): (string?, string?) return "url(#" .. clipIds[id] .. ")" end local root = {} - -- the open <g> stack: { id, children } local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } } local function chain(g: number?): { number } local out = {} diff --git a/src/Rosetta/vector/svg/init.luau b/src/Rosetta/vector/svg/init.luau index 51d6ca3..de2b73f 100644 --- a/src/Rosetta/vector/svg/init.luau +++ b/src/Rosetta/vector/svg/init.luau @@ -1,15 +1,7 @@ --!strict --- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs --- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg --- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from --- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke / --- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and --- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path --- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %). --- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and --- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector. --- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also --- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes. +-- vector/svg: SVG 1.1 / 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: shapes and paths, transforms, +-- nested svg / use / symbol, a CSS subset, gradients, clip-path, group opacity, strokes, dashes, units. Not supported +-- (meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject, switch conditions, CSS combinators. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -32,7 +24,7 @@ local Svg = { } export type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 64 MB) + maxBytes: number?, -- default 64 MB } export type EncodeOptions = {} export type RasterizeOptions = Render.Options @@ -77,8 +69,6 @@ function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox --- maps onto w x h by its preserveAspectRatio. function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?) if type(v) ~= "table" or type(v.paths) ~= "table" then return nil, Err.new(Err.ARG, "needs a Vector value") diff --git a/src/Rosetta/vector/tiled/Data.luau b/src/Rosetta/vector/tiled/Data.luau index f08f0d2..c0182ad 100644 --- a/src/Rosetta/vector/tiled/Data.luau +++ b/src/Rosetta/vector/tiled/Data.luau @@ -1,12 +1,10 @@ --!strict --- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip) --- to gids and back; property values and their types; number formatting. Never throws. +-- vector/tiled/Data: tile layer data shared by TMX and TMJ: CSV, base64 (raw / zlib / gzip), properties, numbers. local Base64 = require("@rosetta/core/Base64") local Deflate = require("@rosetta/codecs/compress/Deflate") local Data = {} --- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message function Data.csv(text: string): ({ number }?, string?) local out = {} for tok in string.gmatch(text, "[^,%s]+") do @@ -19,7 +17,6 @@ function Data.csv(text: string): ({ number }?, string?) return out, nil end --- base64(text, compression) -> { gid } | nil, message, unsupported? function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?) local raw, err = Base64.decode(text) if not raw then @@ -49,7 +46,6 @@ function Data.base64(text: string, compression: string?): ({ number }?, string?, return out, nil, nil end --- toBase64(gids, compression?, level?) -> text | nil, message function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?) local b = buffer.create(#gids * 4) for i, g in gids do @@ -73,7 +69,7 @@ function Data.toBase64(gids: { number }, compression: string?, level: number?): return Base64.encode(b), nil end --- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print +-- integers without a fraction (gids up to 2^32), others in the shortest form both runtimes print function Data.num(v: number): string if v % 1 == 0 and math.abs(v) < 2 ^ 53 then return string.format("%.0f", v) @@ -85,7 +81,7 @@ function Data.num(v: number): string return s end --- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line) +-- Tiled's CSV layout: one row per line function Data.csvText(gids: { number }, width: number): string local rows = {} local row = {} @@ -102,7 +98,7 @@ function Data.csvText(gids: { number }, width: number): string return "\n" .. table.concat(rows, ",\n") .. "\n" end --- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil) +-- Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque function Data.color(s: string?): string? if type(s) ~= "string" then return nil @@ -114,7 +110,6 @@ function Data.color(s: string?): string? return "#" .. h end --- property values: TMX / TMJ type names -> a Luau value from text function Data.value(typ: string, text: string): any if typ == "int" or typ == "float" or typ == "object" then return tonumber(text) or 0 @@ -126,7 +121,6 @@ function Data.value(typ: string, text: string): any return text end --- typeOf(v, declared?) -> the Tiled type to write for v function Data.typeOf(v: any, declared: string?): string if declared then return declared @@ -141,7 +135,6 @@ function Data.typeOf(v: any, declared: string?): string return "string" end --- sortedKeys(t) -> its string keys, sorted function Data.sortedKeys(t: { [any]: any }): { string } local out = {} for k in pairs(t) do diff --git a/src/Rosetta/vector/tiled/Tmj.luau b/src/Rosetta/vector/tiled/Tmj.luau index 2ef5610..25ea1df 100644 --- a/src/Rosetta/vector/tiled/Tmj.luau +++ b/src/Rosetta/vector/tiled/Tmj.luau @@ -1,6 +1,5 @@ --!strict --- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ --- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +-- vector/tiled/Tmj: TMJ / TSJ (JSON map format, Tiled 1.12 docs) <-> a Types.TileMap. local Types = require("@rosetta/Types") local Data = require("@rosetta/vector/tiled/Data") @@ -245,7 +244,6 @@ layer = function(v: any, depth: number): (any, string?, boolean?) return nil, "unknown layer type " .. tostring(v.type) end --- tileset(v) -> Tileset (a map's entry, or a .tsj root) function Tmj.tileset(v: any): any local ts: any = { firstGid = n(v.firstgid, 1), @@ -297,7 +295,6 @@ function Tmj.tileset(v: any): any return ts end --- read(value) -> TileMap | nil, message, unsupported? function Tmj.read(v: any): (any, string?, boolean?) if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then return nil, "not a Tiled map (type is not \"map\")" @@ -535,7 +532,6 @@ writeLayer = function(l: any, o: WriteOptions): (any, string?) return obj(fields), nil end --- tilesetValue(ts, inMap) -> a JSON object function Tmj.tilesetValue(ts: any, inMap: boolean): any if inMap and type(ts.source) == "string" then return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) @@ -590,7 +586,6 @@ function Tmj.tilesetValue(ts: any, inMap: boolean): any }) end --- write(map, opts) -> a JSON value | nil, message function Tmj.write(map: any, o: WriteOptions): (any, string?) local layers = {} for _, l in map.layers do diff --git a/src/Rosetta/vector/tiled/Tmx.luau b/src/Rosetta/vector/tiled/Tmx.luau index bbfcd65..de4ef47 100644 --- a/src/Rosetta/vector/tiled/Tmx.luau +++ b/src/Rosetta/vector/tiled/Tmx.luau @@ -1,6 +1,5 @@ --!strict --- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets. --- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +-- vector/tiled/Tmx: TMX / TSX (TMX map format, Tiled 1.12 docs) <-> a Types.TileMap. local Xml = require("@rosetta/codecs/text/Xml") local Types = require("@rosetta/Types") local Data = require("@rosetta/vector/tiled/Data") @@ -28,7 +27,6 @@ local function flag(n: Node, k: string, default: boolean): boolean end -- ------------------------------------------------------------------------------------------------ read --- <properties> -> values, types (types only for the non-string ones) local function properties(n: Node?): ({ [string]: any }, { [string]: string }?) local props: { [string]: any } = {} local types: { [string]: string }? = nil @@ -68,7 +66,6 @@ local function withProps(t: any, n: Node) end end --- the gids of a <data> (or <chunk>) node local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?) if encoding == "csv" then return Data.csv(Xml.text(d)) @@ -233,7 +230,6 @@ layer = function(n: Node): (any, string?, boolean?) return nil end --- a <tileset> element (in a map, or a .tsx root) -> Tileset function Tmx.tileset(n: Node): any local ts: any = { firstGid = num(n, "firstgid", 1), @@ -287,7 +283,6 @@ function Tmx.tileset(n: Node): any return ts end --- read(root) -> TileMap | nil, message, unsupported? function Tmx.read(root: Node): (any, string?, boolean?) if root.name ~= "map" then return nil, "the root element is <" .. root.name .. ">, not <map>" @@ -330,7 +325,6 @@ end type Attrs = { [string]: string } local function el(name: string, attrs: { { any } }, children: { any }?): Node - -- attrs in order; nil / default values dropped by the caller local o = Types.object() for _, kv in attrs do if kv[2] ~= nil then @@ -533,7 +527,6 @@ writeLayer = function(l: any, o: WriteOptions): (Node?, string?) return nil, "unknown layer type " .. tostring(t) end --- tilesetNode(ts, inMap) -> <tileset> function Tmx.tilesetNode(ts: any, inMap: boolean): Node if inMap and type(ts.source) == "string" then return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) @@ -578,7 +571,6 @@ function Tmx.tilesetNode(ts: any, inMap: boolean): Node }, kids) end --- write(map, opts) -> an XML document node | nil, message function Tmx.write(map: any, o: WriteOptions): (Node?, string?) local kids = {} addProps(kids, map) diff --git a/src/Rosetta/vector/tiled/init.luau b/src/Rosetta/vector/tiled/init.luau index 3414a12..ca95dbe 100644 --- a/src/Rosetta/vector/tiled/init.luau +++ b/src/Rosetta/vector/tiled/init.luau @@ -1,14 +1,7 @@ --!strict --- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map --- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib / --- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles, --- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers, --- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets --- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay --- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the --- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json". --- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external --- tilesets or images (callers resolve `source` / `imageSource` paths themselves). +-- vector/tiled: Tiled maps, TMX (XML) / TMJ (JSON), and TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map Format", "JSON +-- Map Format"). Supports: every orientation, tile / object / image / group layers, infinite maps, typed properties, +-- tilesets. Not supported: zstd layer data (Err.UNSUPPORTED), Wang sets / terrains, loading external tilesets / images. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,14 +24,14 @@ local Tiled = { } export type DecodeOptions = { - maxBytes: number?, -- refuse larger files (default 256 MB) + maxBytes: number?, -- default 256 MB } export type EncodeOptions = { - format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx + format: string?, -- "tmx" | "tsx" | "tmj" | "tsj" | "json"; default: the source's flavour, else tmx encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64" - compression: string?, -- base64 data: nil | "zlib" | "gzip" - level: number?, -- deflate level for compressed data (default 6) - indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON) + compression: string?, -- nil | "zlib" | "gzip" + level: number?, -- default 6 + indent: number?, -- default 1 (TMX), 2 (TMJ); 0 = compact JSON } -- ------------------------------------------------------------------------------------------------ sniff @@ -72,8 +65,6 @@ function Tiled.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its --- meta.tileset is true) | nil, Err function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) local maxBytes = opts and opts.maxBytes or 2 ^ 28 if r.limit - r.base > maxBytes then diff --git a/src/Rosetta/video/avi/init.luau b/src/Rosetta/video/avi/init.luau index 60b37da..0196896 100644 --- a/src/Rosetta/video/avi/init.luau +++ b/src/Rosetta/video/avi/init.luau @@ -1,13 +1,7 @@ --!strict --- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, on containers/Avi. --- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces --- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, --- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is --- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, --- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. --- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's --- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. --- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. +-- video/avi: AVI (RIFF AVI 1.0, OpenDML 1.02: super / standard indexes, idx1, AVIX pieces). Reads video through the +-- codecs/video/Video registry by FourCC and audio through opts.openAudio; dropped frames keep their slot. Writes +-- MJPEG + PCM s16 (AVI 1.0, idx1, odml). Not supported: writing over 1 GB, palette changes (##pc), text streams. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,18 +24,18 @@ local AviFormat = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8) - track: number?, -- the video track (stream index + 1) to decode - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p; BI_RGB gives rgba8 + track: number?, -- stream index + 1 + audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api } export type EncodeOptions = { - quality: number?, -- MJPEG quality 1..100 (default 90) - reencode: boolean?, -- encode the frames even when the source is MJPEG - audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one) + quality: number?, -- 1..100, default 90 + reencode: boolean?, + audio: boolean?, -- default: PCM s16 from the source's audio video: boolean?, - maxFps: number?, -- the highest frame rate variable delays may need (default 100) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -170,7 +164,6 @@ local function audioTrack(s: Avi.Stream, id: number): Types.Track return t end --- demux(r, opts?) -> the Demuxer | nil, Err function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) if not ok then @@ -197,7 +190,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } local dmx = Demux.new("avi", tracks, r.buf, meta) - -- packets in file order across streams: merge by offset local items: { { number } } = {} for k, st in streams do local s: Avi.Stream, t: any = st[1], st[2] @@ -227,7 +219,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -278,7 +269,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) end end - -- chunks in time order (the video packets already repeated to the constant rate) local chunks: { { any } } = {} for _, item in Source.interleave(streams) do table.insert(chunks, { item[1], item[2].data, true }) @@ -291,7 +281,6 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = AviFormat.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/fli/init.luau b/src/Rosetta/video/fli/init.luau index ac01974..f34ed25 100644 --- a/src/Rosetta/video/fli/init.luau +++ b/src/Rosetta/video/fli/init.luau @@ -1,12 +1,7 @@ --!strict --- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC --- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). --- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: --- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, --- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 --- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the --- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. --- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). +-- video/fli: Autodesk FLI / FLC / FLX animations, from Jim Kent's "FLC - Animator Pro Flic Files" (MultimediaWiki +-- "FLIC"): magics 0xAF11 (speed in 1/70 s), 0xAF12 / 0xAF44 (ms); frame chunks 0xF1FA / 0xF5FA, rgba8 through +-- codecs/video/Legacy; the ring frame is not shown. Not supported: writing, 1-bit FLICs, X-COM / Magic Carpet variants. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,9 +22,9 @@ local Fli = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) } -- ------------------------------------------------------------------------------------------------ constants @@ -56,7 +51,6 @@ function Fli.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer | nil, Err function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit local n = limit - base @@ -108,7 +102,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) default = true, bitsPerPixel = depth, } - -- the frame chunks local offs, sizes = {}, {} local p = base + HEADER while p + 6 <= limit do @@ -119,7 +112,7 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end if (cm == FRAME or cm == FRAME2) and size > 6 then if p + size > limit then - break -- a truncated last frame + break end table.insert(offs, p) table.insert(sizes, size) @@ -145,7 +138,6 @@ function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Fli.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/flv/Amf.luau b/src/Rosetta/video/flv/Amf.luau index 98fe321..4c30ece 100644 --- a/src/Rosetta/video/flv/Amf.luau +++ b/src/Rosetta/video/flv/Amf.luau @@ -1,11 +1,6 @@ --!strict --- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0 --- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference --- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the --- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws. --- --- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... } --- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... }) +-- video/flv/Amf: AMF0 values (AMF0 spec, FLV spec v10 script tags). Read: number, boolean, string, object, null, +-- undefined, reference, ECMA / strict array, date (ms), long string. Write: numbers, booleans, strings, arrays. local Bytes = require("@rosetta/core/Bytes") local Amf = {} @@ -90,13 +85,11 @@ readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any return nil end --- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep) function Amf.value(r: Bytes.Reader): any local ok, v = pcall(readValue, r, 0, {}) return if ok and not r.err then v else nil end --- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil function Amf.script(r: Bytes.Reader): (string?, any) local name = Amf.value(r) if type(name) ~= "string" then @@ -117,7 +110,6 @@ local function writeString(w: Bytes.Writer, s: string) w:string(s) end --- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null function Amf.writeValue(w: Bytes.Writer, v: any) local t = type(v) if t == "number" then @@ -139,8 +131,6 @@ function Amf.writeValue(w: Bytes.Writer, v: any) end end --- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as --- { key, { pairs = { ... } } } becomes an object) function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?) if object then w:u8(3) diff --git a/src/Rosetta/video/flv/Mux.luau b/src/Rosetta/video/flv/Mux.luau index b3f7749..8e4da8a 100644 --- a/src/Rosetta/video/flv/Mux.luau +++ b/src/Rosetta/video/flv/Mux.luau @@ -1,10 +1,6 @@ --!strict --- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag --- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264 --- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source --- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times), --- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made --- from the first ADTS header. Interpreted; never throws (returns nil, Err). +-- video/flv/Mux: the FLV writer (FLV spec v10): header, onMetaData, AVC / AAC sequence headers, tags interleaved by +-- decode time (ms, shifted so none is negative), H.264 end of sequence; ADTS AAC split into raw frames. local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Amf = require("@rosetta/video/flv/Amf") @@ -30,7 +26,6 @@ local function isAdts(s: any): boolean return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 end --- audioProblem(stream) -> why FLV cannot hold this audio stream | nil function Mux.audioProblem(s: any): string? local fmt = AUDIO_FORMATS[s.codec] if not fmt then @@ -124,7 +119,6 @@ local function f64At(b: buffer, at: number, v: number) end end --- mux(streams) -> buffer | nil, Err function Mux.mux(streams: { any }): (buffer?, Err.Err?) local video, audio = nil :: any, nil :: any for _, s in streams do @@ -167,7 +161,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) end end end - -- times: milliseconds, shifted so the earliest decode time is 0 when any is negative local shift = 0 local duration = 0 local vBytes, aBytes = 0, 0 @@ -211,7 +204,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) w:u32be(11 + n) end - -- onMetaData local props: { { any } } = { { "duration", duration } } if video then table.insert(props, { "width", video.width or 0 }) @@ -238,7 +230,6 @@ function Mux.mux(streams: { any }): (buffer?, Err.Err?) tag(18, 0, {}, metaBody) local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker - -- sequence headers local vid = if video then VIDEO_IDS[video.codec] else 0 if video and video.codec == "h264" then tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) diff --git a/src/Rosetta/video/flv/init.luau b/src/Rosetta/video/flv/init.luau index fc4c95d..c42d473 100644 --- a/src/Rosetta/video/flv/init.luau +++ b/src/Rosetta/video/flv/init.luau @@ -1,20 +1,7 @@ --!strict --- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's --- FourCC video tags). New in rosetta. --- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ... --- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by --- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1 --- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks --- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets --- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config), --- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through --- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer. --- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 / --- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at --- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data --- rates, codec ids, file size). --- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx --- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC). +-- video/flv: Flash Video (Adobe FLV spec v10, Enhanced RTMP FourCC tags). Reads the tags and onMetaData (AMF0) into a +-- Demuxer; decodes Sorenson Spark and H.264 (other codecs are UNSUPPORTED tracks), audio through opts.openAudio. +-- Writes copied packets, else PCM s16 at 5512..44100 Hz. Not supported: encrypted tags, multitrack / ModEx packets. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,17 +28,17 @@ local Flv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id (1 video, 2 audio) - audio: boolean?, -- false: do not open the audio track - maxPackets: number?, -- refuse files with more tags (default 2^24) + rgba: boolean?, -- default false: yuv420p + track: number?, -- 1 video, 2 audio + audio: boolean?, + maxPackets: number?, -- default 2^24 maxPixels: number?, openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - video: boolean?, -- false: no video - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped) - reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied + video: boolean?, + audio: boolean?, -- true: fail when the audio cannot be written (default: dropped) + reencodeAudio: boolean?, } -- ------------------------------------------------------------------------------------------------ constants @@ -118,7 +105,6 @@ local function copy(b: buffer, p: number, n: number): buffer return c end --- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?) if codec == "flv1" then local h = H263.header(b, p, n, true) @@ -152,7 +138,6 @@ local function frameSize(codec: string, b: buffer, p: number, n: number): (numbe return nil, nil end --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local o: OpenOptions = opts or {} local b, base, limit = r.buf, r.base, r.limit @@ -169,7 +154,7 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local tracks: { Types.Track } = {} local dmx = Demux.new("flv", tracks, b, meta) local vt: any, at: any = nil, nil - local keyOff, keyLen = -1, 0 -- the first video keyframe + local keyOff, keyLen = -1, 0 local maxPackets = o.maxPackets or 2 ^ 24 local count = 0 local p = base + dataOffset + 4 -- after PreviousTagSize0 @@ -316,7 +301,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end p = d + size + 4 end - -- the track facts onMetaData and the codec headers give local md: { [string]: any } = meta.metadata or {} if type(md.duration) == "number" and md.duration > 0 then meta.duration = md.duration @@ -338,7 +322,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) if type(fr) == "number" and fr > 0 and fr < 1000 then vt.frameRate = fr else - -- from the timestamps: the frames over the time they span local n = dmx:count(vt.id) local t0 = if n > 0 then dmx:info(vt.id, 1) else nil local t1 = if n > 1 then dmx:info(vt.id, n) else nil @@ -355,7 +338,6 @@ function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { @@ -365,7 +347,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not streams then return nil, err end - -- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true for i = #streams, 1, -1 do local s = streams[i] local why = s.kind == "audio" and Mux.audioProblem(s) @@ -387,7 +368,6 @@ function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Flv.demux, r, opts) if not ok then diff --git a/src/Rosetta/video/h264/init.luau b/src/Rosetta/video/h264/init.luau index 30811c3..ee08e6b 100644 --- a/src/Rosetta/video/h264/init.luau +++ b/src/Rosetta/video/h264/init.luau @@ -1,12 +1,7 @@ --!strict --- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg --- `-f h264` output, the JVT conformance bitstreams). New in rosetta. --- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a --- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw --- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). --- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, --- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is --- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). +-- video/h264: raw H.264 Annex B byte streams (.h264 / .264), cut into access units and decoded by codecs/video/H264 +-- (frame rate: the SPS VUI, else opts.frameRate, else 25). Writes H.264 tracks copied from any video (avcC to Annex B). +-- Not supported: encoding other codecs, what codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -29,10 +24,10 @@ local Format = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) - maxPixels: number?, -- largest picture (default 2^22 luma samples) - frameRate: number?, -- frames per second when the stream has no VUI timing (default 25) - deblock: boolean?, -- false skips the deblocking filter (faster, not conformant) + rgba: boolean?, -- default false: yuv420p + maxPixels: number?, -- default 2^22 luma samples + frameRate: number?, -- default 25 + deblock: boolean?, -- false: faster, not conformant } -- ------------------------------------------------------------------------------------------------ sniff @@ -65,7 +60,6 @@ function Format.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local units = H264.accessUnits(buf, base, limit - base) @@ -106,7 +100,6 @@ function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) if not streams then @@ -133,7 +126,6 @@ function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Format.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mkv/Mux.luau b/src/Rosetta/video/mkv/Mux.luau index 5c7408b..5e367f2 100644 --- a/src/Rosetta/video/mkv/Mux.luau +++ b/src/Rosetta/video/mkv/Mux.luau @@ -1,9 +1,6 @@ --!strict --- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), --- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of --- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative --- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come --- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment (SeekHead, Info with a 1 ms TimecodeScale, Tracks, +-- Clusters of SimpleBlocks cut at keyframes after 2 s or before the 16-bit timestamp overflows, a CuePoint each). local Err = require("@rosetta/core/Err") local Ebml = require("@rosetta/containers/Ebml") local Video = require("@rosetta/codecs/video/Video") @@ -36,7 +33,6 @@ local AUDIO_IDS: { [string]: string } = { } Mux.AUDIO_IDS = AUDIO_IDS --- codecId(stream) -> the Matroska CodecID | nil function Mux.codecId(kind: string, codec: string): string? if kind == "video" then local e = Video.entry(codec) @@ -64,12 +60,10 @@ export type Options = { clusterSeconds: number?, -- default 2 } --- mux(streams, opts) -> buffer | nil, Err function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) local webm = opts.webm == true local app = opts.app or "rosetta" local clusterSpan = opts.clusterSeconds or 2 - -- tracks local ids: { string } = {} local videoIndex = 0 for i, s in streams do @@ -150,7 +144,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) end body:close(tracks) - -- clusters local cues: { { number } } = {} -- { time ms, track, cluster offset in body } local cl: number? = nil local clTime = 0 @@ -264,7 +257,6 @@ function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) bodyBuf = nb end - -- the file local out = Ebml.writer(buffer.len(bodyBuf) + 256) local eb = out:open(ID.EBML) out:uint(0x4286, 1) diff --git a/src/Rosetta/video/mkv/Parse.luau b/src/Rosetta/video/mkv/Parse.luau index 1a64348..ecc0964 100644 --- a/src/Rosetta/video/mkv/Parse.luau +++ b/src/Rosetta/video/mkv/Parse.luau @@ -1,9 +1,6 @@ --!strict --- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles --- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, --- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, --- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by --- default). Interpreted (it only walks headers); never throws. +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Info / Tracks / Cues / Tags / chapter titles, Clusters +-- (SimpleBlock, BlockGroup, Xiph / EBML / fixed lacing, unknown sizes); timescale 1e9 / TimecodeScale. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Ebml = require("@rosetta/containers/Ebml") @@ -138,7 +135,6 @@ local SUBS: { [string]: string } = { ["S_HDMV/PGS"] = "pgs", } --- codecFor(CodecID, bitDepth) -> our codec id local function codecFor(id: string, kind: string, bits: number?): string if kind == "video" then return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) @@ -219,8 +215,7 @@ local function parseAudio(buf: buffer, off: number, len: number, t: any) end end --- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption --- are not +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0); not bzip / lzo or encryption local function parseEncodings(buf: buffer, off: number, len: number, t: any): string? for id, o, n in Ebml.children(buf, off, off + len) do if id == ID.ContentEncoding then @@ -418,7 +413,7 @@ type Ctx = { maxPackets: number, } --- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +-- Block / SimpleBlock: track, relative timecode, flags, lacing local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?) local buf = ctx.buf local limit = off + len @@ -543,7 +538,6 @@ local function block(ctx: Ctx, off: number, len: number, clusterTime: number, si end end --- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number local buf = ctx.buf local pos = off @@ -591,9 +585,6 @@ end export type Options = { maxPackets: number? } --- parse(buf, base, limit, opts) -> a Demux | nil, Err --- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data --- offset | nil, Err function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?) local id, size, data = Ebml.header(buf, base, limit) if id ~= ID.EBML or not size or not data then @@ -620,7 +611,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) end local pos = data + size - -- the Segment (skip anything else at the top level) local segData, segEnd = -1, limit while pos < limit do local sid, ssize, sdata = Ebml.header(buf, pos, limit) @@ -663,7 +653,6 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) elseif cid == ID.Cluster then if unknown then - -- find its end: walk children until a top-level ID local p = cdata while p < segEnd do local xid, xsize, xdata = Ebml.header(buf, p, segEnd) diff --git a/src/Rosetta/video/mkv/init.luau b/src/Rosetta/video/mkv/init.luau index db5e356..430f9af 100644 --- a/src/Rosetta/video/mkv/init.luau +++ b/src/Rosetta/video/mkv/init.luau @@ -1,16 +1,7 @@ --!strict --- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in --- rosetta, on containers/Ebml. --- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, --- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video --- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio --- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text --- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. --- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied --- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from --- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. --- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, --- track.unsupported says why), chapters / attachments (skipped), writing subtitles. +-- video/mkv: Matroska / WebM (RFC 9559, the WebM guidelines), on containers/Ebml. Reads every packet (all lacings, +-- header stripping and zlib, unknown-size clusters, Cues, Tags) into a Demuxer, text subtitle tracks as cues. Writes +-- WebM or Matroska (copied, else MJPEG + PCM s16). Not supported: bzip2 / lzo, encryption, chapters, attachments. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,22 +24,22 @@ local Mkv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track number to decode (default: the first video track) - audio: boolean?, -- false: do not open the audio track - maxPackets: number?, -- refuse files with more packets (default 2^24) + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, + maxPackets: number?, -- default 2^24 maxPixels: number?, openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska - webm: boolean?, -- the same as format = "webm" - quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90) - reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG) - video: boolean?, -- false: no video stream - audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped) + format: string?, -- "webm": DocType webm, WebM codecs only; else Matroska + webm: boolean?, -- as format = "webm" + quality: number?, -- 1..100, default 90 + reencode: boolean?, + video: boolean?, + audio: boolean?, -- true: fail if the audio cannot be written (default: dropped) title: string?, - clusterSeconds: number?, -- target cluster length (default 2) + clusterSeconds: number?, -- seconds, default 2 } -- ------------------------------------------------------------------------------------------------ constants @@ -67,7 +58,6 @@ function Mkv.sniff(r: Bytes.Reader): number return 0.5 end --- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) function Mkv.variant(r: Bytes.Reader): string? local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) if ok and docType == "webm" then @@ -77,8 +67,6 @@ function Mkv.variant(r: Bytes.Reader): string? end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) --- or a Demuxer function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") @@ -121,7 +109,6 @@ function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) if not ok then @@ -130,7 +117,6 @@ function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) return dmx, err end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mkv.demux(r, opts) if not dmx then @@ -140,7 +126,6 @@ function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Er end -- ------------------------------------------------------------------------------------------------ extras --- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? local track = nil for _, t in dmx.tracks do diff --git a/src/Rosetta/video/mp4/init.luau b/src/Rosetta/video/mp4/init.luau index 1d76faa..4358c59 100644 --- a/src/Rosetta/video/mp4/init.luau +++ b/src/Rosetta/video/mp4/init.luau @@ -1,18 +1,7 @@ --!strict --- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on --- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in rosetta. --- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first --- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as --- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG --- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through --- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / --- 'lpcm' / 'ipcm'). --- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied --- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v --- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV --- only; MP4 drops other audio unless opts.audio = true, which fails). --- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented --- writing, timed text tracks, encrypted tracks. +-- video/mp4: MP4 / M4V / MOV / 3GP (ISO/IEC 14496-12 / 14496-14, QuickTime), on containers/IsoBmff. Reads every +-- track into a Demuxer (pts = dts + composition offset, moved by the edit list; fragments too). Writes MP4 or MOV: +-- video copied, else MJPEG; audio copied, else PCM s16 (MOV). Not supported: fragmented writing, timed text, DRM. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -36,18 +25,18 @@ local Mp4 = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video track id (default: the first video track) + track: number?, -- default: the first video track audio: boolean?, maxPixels: number?, maxSamples: number?, openAudio: any?, -- set by the api } export type EncodeOptions = { - format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom') - quality: number?, -- MJPEG quality when frames are encoded (default 90) - reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied + format: string?, -- "mov": QuickTime (brand 'qt '); else MP4 (brand 'isom') + quality: number?, -- default 90 + reencode: boolean?, video: boolean?, - audio: boolean?, -- false: no audio; true: fail when the audio cannot be written + audio: boolean?, -- true: fail when the audio cannot be written } -- ------------------------------------------------------------------------------------------------ constants @@ -106,7 +95,6 @@ local function pcmCodec(t: any): string return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be") end --- demux(r, opts?) -> the Demuxer | nil, Err function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) if not ok then @@ -164,7 +152,6 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) table.insert(src, it) end local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand }) - -- samples in file order across tracks local items: { { number } } = {} for k, it in src do -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio @@ -215,7 +202,6 @@ local function dOps(head: buffer?): buffer? return w:finish() end --- encode(video, opts?) -> buffer | nil, Err function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) o.quality = o.quality or 90 @@ -329,7 +315,6 @@ function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Mp4.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mpegps/init.luau b/src/Rosetta/video/mpegps/init.luau index 9cca184..f722a41 100644 --- a/src/Rosetta/video/mpegps/init.luau +++ b/src/Rosetta/video/mpegps/init.luau @@ -1,12 +1,7 @@ --!strict --- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / --- .vob / VCD .dat). New in rosetta, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both --- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get --- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). --- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its --- sequence extension), audio through the api's opts.openAudio hook. --- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1, 13818-1: .mpg / .vob / VCD .dat), on containers/MpegPs and +-- containers/MpegEs: a packet per picture (the PTS of the PES it starts in, else from the GOP's temporal references), +-- audio packets = PES payloads; 90 kHz. Not supported: writing, H.264 in PS, DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -30,7 +25,7 @@ local Ps = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream) + track: number?, -- 0xE0..; default: the first video stream audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -48,7 +43,6 @@ function Ps.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) local total = 0 for _, p in s.pes do @@ -119,7 +113,6 @@ local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) end end --- demux(r, opts?) -> the Demuxer | nil, Err function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) if r:peek(4) == "\0\0\1\179" then -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps @@ -181,7 +174,6 @@ function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ps.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/mpegts/init.luau b/src/Rosetta/video/mpegts/init.luau index 07c703b..cabffea 100644 --- a/src/Rosetta/video/mpegts/init.luau +++ b/src/Rosetta/video/mpegts/init.luau @@ -1,13 +1,7 @@ --!strict --- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, --- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS --- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the --- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, --- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / --- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. --- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, --- PES without PTS for video before the first one (dropped). +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts, .m2ts, HLS) over containers/MpegTs (from mpegts-luau); +-- one PES = one packet, 90 kHz; MPEG-1 / 2 (types 0x01 / 0x02, private ones told by an MPEG-2 sequence extension), +-- H.264, MP1-3 / ADTS AAC. Not supported: writing, scrambled streams, video PES before the first PTS (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -31,7 +25,7 @@ local Ts = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { rgba: boolean?, - track: number?, -- the video PID to decode (default: the first video stream of the PMT) + track: number?, -- default: the first video stream of the PMT audio: boolean?, maxPixels: number?, openAudio: any?, -- set by the api @@ -52,8 +46,7 @@ local CODEC: { [string]: string } = { } -- ------------------------------------------------------------------------------------------------ sniff --- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart --- (fewer in a short file) within the first 2 KB +-- 188 or 192 (M2TS): three sync bytes a packet apart (fewer in a short file) within the first 2 KB local function packetSize(r: Bytes.Reader): (number, number) local n = r:remaining() for start = 0, math.min(n, 2048) - 1 do @@ -112,7 +105,6 @@ local function mpegAudioCodec(u: any): string return "mp2" end --- demux(r, opts?) -> the Demuxer | nil, Err function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) local size, off = packetSize(r) if size == 0 then @@ -164,7 +156,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) for _, u in units do track(u.pid, u.kind, u.codec, u.streamType, nil) end - -- codec details from the first unit local seen: { [number]: boolean } = {} for _, u in units do local t = byPid[u.pid] @@ -234,7 +225,6 @@ function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Ts.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/ogv/init.luau b/src/Rosetta/video/ogv/init.luau index 8a12660..6e5dbab 100644 --- a/src/Rosetta/video/ogv/init.luau +++ b/src/Rosetta/video/ogv/init.luau @@ -1,15 +1,7 @@ --!strict --- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, --- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux. --- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from --- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, --- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / --- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's --- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. --- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied --- (the audio pages come from containers/AudioWrap and are interleaved by time). --- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), --- encoding Theora (there is no encoder: other sources cannot be written). +-- video/ogv: Ogg Theora video (Theora I spec, RFC 3533 / 5334), on containers/Ogg: Theora (granule = keyframe << shift +-- | frames since; the headers Xiph-laced into track.config) and Vorbis / Opus / FLAC streams of the first group. Writes +-- copied Theora + audio. Not supported: chained files, Skeleton / Kate / Speex streams, encoding Theora. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -34,23 +26,22 @@ local Ogv = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) - track: number?, -- the video track id to decode (default: the first video track) - audio: boolean?, -- false: do not open the audio track + rgba: boolean?, -- default false: yuv420p + track: number?, -- default: the first video track + audio: boolean?, maxPixels: number?, - verify: boolean?, -- false: skip the page CRC checks (default true) + verify: boolean?, -- default true openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder } export type EncodeOptions = { - audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) + audio: boolean?, -- true: fail when the audio cannot be copied (default: dropped) } -- ------------------------------------------------------------------------------------------------ constants local AUDIO = { vorbis = true, opus = true, flac = true } -- ------------------------------------------------------------------------------------------------ sniff --- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain --- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +-- a Theora identification header in a bos page (plain Ogg audio is left to the audio formats) function Ogv.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 @@ -78,7 +69,6 @@ function Ogv.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ encode --- the pages of an Ogg buffer: { offset, size, serial, granule, bos } local function pages(b: buffer): { { number } } local out = {} local pos = 0 @@ -93,7 +83,6 @@ local function pages(b: buffer): { { number } } return out end --- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = opts or {} local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) @@ -137,7 +126,6 @@ function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) end local video = mux:finish() - -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time local audio: buffer? = nil local arate, askip = 1, 0 if as and o.audio ~= false then @@ -232,7 +220,6 @@ end type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } --- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) if not ogg then @@ -301,7 +288,7 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) break end if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then - continue -- a stray header + continue end table.insert(packets, p) if base == nil and p.granule >= 0 then @@ -392,7 +379,6 @@ function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) return dmx, nil end --- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local ok, dmx, err = pcall(Ogv.demux, r, opts) if not ok then diff --git a/src/Rosetta/video/smk/Audio.luau b/src/Rosetta/video/smk/Audio.luau index bde9edd..615a74a 100644 --- a/src/Rosetta/video/smk/Audio.luau +++ b/src/Rosetta/video/smk/Audio.luau @@ -1,20 +1,15 @@ --!strict --!native --!optimize 2 --- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker --- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), --- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ --- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per --- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / --- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives --- them. Never throws: trees are bounded and every read past the packet gives zero bits. +-- video/smk/Audio: Smacker packed audio (SMKA, MultimediaWiki "Smacker"): u32 unpacked size, then LSB-first bits: data, +-- stereo, 16-bit flags, an 8-bit Huffman tree per channel and byte, the first samples raw (16-bit byte-swapped, right +-- first), then wrapping deltas. Raw u8 / s16le too; floats as ffmpeg gives them (u8 (v - 128) / 128, s16 v / 32768). local Smacker = require("@rosetta/codecs/video/Legacy/Smacker") local readu8, readi16 = buffer.readu8, buffer.readi16 local Audio = {} --- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) local n = buffer.len(d) if not packed then @@ -43,7 +38,7 @@ function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean local br = Smacker.bits(d, 4, n - 4) local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk if bit(br) == 0 then - return 0, {} -- no data + return 0, {} end local stereo = bit(br) local wide = bit(br) diff --git a/src/Rosetta/video/smk/init.luau b/src/Rosetta/video/smk/init.luau index ded8c40..e741837 100644 --- a/src/Rosetta/video/smk/init.luau +++ b/src/Rosetta/video/smk/init.luau @@ -1,16 +1,7 @@ --!strict --- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description --- (MultimediaWiki "Smacker"). --- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio --- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette --- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() --- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the --- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio --- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it --- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that --- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, --- track) the Decoder of any of its audio tracks. --- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). +-- video/smk: RAD Smacker video (SMK2, SMK4), from MultimediaWiki "Smacker": header, up to 7 audio tracks, Huffman +-- trees, per-frame palette updates; rgba8 through codecs/video/Legacy/Smacker, audio through video/smk/Audio; the ring +-- frame only with opts.ringFrame. Not supported: writing, Bink audio tracks (flags 0x08 / 0x04). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -33,11 +24,11 @@ local Smk = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- (frames are rgba8 already) + rgba: boolean?, -- frames are rgba8 already maxPixels: number?, -- default 2^26 - audio: boolean?, -- false: do not open the audio track - ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) - openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) + audio: boolean?, + ringFrame: boolean?, -- also show the ring frame (as ffmpeg) + openAudio: any?, -- the api's hook, only for Bink audio } -- ------------------------------------------------------------------------------------------------ constants @@ -59,7 +50,6 @@ function Smk.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) local pal = buffer.create(1024) buffer.copy(pal, 0, old, 0, 1024) @@ -96,7 +86,6 @@ local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer return pal end --- demux(r, opts?) -> the Demuxer | nil, Err function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < HEADER then @@ -247,7 +236,6 @@ function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) local codec = track.codec if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then @@ -299,7 +287,6 @@ function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) }) end --- open(r, opts?) -> a VideoDecoder | nil, Err function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Smk.demux(r, opts) if not dmx then diff --git a/src/Rosetta/video/y4m/init.luau b/src/Rosetta/video/y4m/init.luau index 2e97994..838a642 100644 --- a/src/Rosetta/video/y4m/init.luau +++ b/src/Rosetta/video/y4m/init.luau @@ -1,11 +1,7 @@ --!strict --- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta. --- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder --- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono --- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. --- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 --- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), --- alpha (C444alpha drops it). +-- video/y4m: YUV4MPEG2 (mjpegtools / ffmpeg). Reads the W H F I A C X tags and FRAMEs as yuv420p (C422 / C444 +-- averaged, Cmono neutral chroma, high bit depths scaled to 8). Writes "C420jpeg" as ffmpeg does for yuv420p (BT.601 +-- limited range). Not supported: interlaced field handling (the I tag is kept in meta), alpha (C444alpha drops it). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,13 +23,12 @@ local Y4m = { -- ------------------------------------------------------------------------------------------------ types export type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + rgba: boolean?, -- default false: yuv420p maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the - -- shortest frame, longer frames repeated) - maxFps: number?, -- the highest rate uneven frame times may need (default 100) + frameRate: { number }?, -- { num, den } of the F tag (default: the shortest frame's rate) + maxFps: number?, -- default 100 } -- ------------------------------------------------------------------------------------------------ constants @@ -77,7 +72,6 @@ local function frameSize(pf: string, bits: number, w: number, h: number): number return w * h * bps end --- demux(r, opts?) -> the raw-video Demuxer | nil, Err function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) local buf, base, limit = r.buf, r.base, r.limit local nl = -1 @@ -164,7 +158,7 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end local data = e + 1 if data + size > limit then - break -- a truncated last frame is dropped + break end dmx:add(1, k, k, 1, true, data, size) k += 1 @@ -175,7 +169,6 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(video, opts?) -> buffer | nil, Err function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) if not streams then @@ -197,7 +190,6 @@ function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ open --- open(r, opts?) -> a VideoDecoder | nil, Err function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local dmx, err = Y4m.demux(r, opts) if not dmx then