comments: host + core checksums / Bits / Err / Input / Sniff down to specs
This commit is contained in:
1 parent
0bd7b87d2b
commit
5c42fae954
11 files changed
+12
-143
No files matched your search
@@ -2,19 +2,14 @@
|
||||
--!native
|
||||
-- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author;
|
||||
-- no third-party code). Never throws: the range is clamped.
|
||||
--
|
||||
-- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it)
|
||||
-- Adler32.string(s, adler?) -> u32
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- Adler-32 of buf[off, off + len), continuing adler (default 1)
|
||||
local function adler32(buf: buffer, off: number, len: number, adler: number?): number
|
||||
local a0 = adler or 1
|
||||
local a, b = a0 % 65536, a0 // 65536
|
||||
local i, e = off, off + len
|
||||
while i < e do
|
||||
-- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far
|
||||
-- more, but keeping the sums small keeps them exact and cheap.
|
||||
-- zlib NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32
|
||||
local stop = math.min(e, i + 5552)
|
||||
while i < stop do
|
||||
a += readu8(buf, i)
|
||||
@@ -27,7 +22,6 @@ local function adler32(buf: buffer, off: number, len: number, adler: number?): n
|
||||
return b * 65536 + a
|
||||
end
|
||||
|
||||
-- clamp (offset, length) to the buffer
|
||||
local function range(buf: buffer, offset: number?, length: number?): (number, number)
|
||||
local n = buffer.len(buf)
|
||||
local o = math.clamp(offset or 0, 0, n)
|
||||
|
||||
@@ -4,12 +4,6 @@
|
||||
-- Used by tiled map data, glTF / SVG / CSS data: URIs, plist <data>, YAML !!binary, FBX, the Brotli static tables.
|
||||
-- decode skips whitespace, accepts missing padding and both alphabets; any other character, data after padding or a
|
||||
-- lone last character is an error. Never throws.
|
||||
--
|
||||
-- local s = Base64.encode(buf) -- buffer | string -> string ("" for empty input)
|
||||
-- local s2 = Base64.encode(buf, { url = true, pad = false, wrap = 76 }, offset, length)
|
||||
-- local b, err = Base64.decode(s) -- string | buffer -> buffer | nil, "message"
|
||||
-- local b2, mime = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, msg
|
||||
-- local uri = Base64.dataUri(buf, "image/png")
|
||||
local Base64 = {}
|
||||
|
||||
export type EncodeOptions = {
|
||||
@@ -37,7 +31,6 @@ buffer.writeu8(DEC, string.byte("="), 65)
|
||||
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
-- encode(data, opts?, offset?, length?) -> base64 text of data[offset, offset + length)
|
||||
function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: number?, length: number?): string
|
||||
local buf: buffer = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
local total = buffer.len(buf)
|
||||
@@ -45,7 +38,7 @@ function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: numb
|
||||
local n = math.clamp(length or (total - o), 0, total - o)
|
||||
local enc = if opts and opts.url then ENC_URL else ENC
|
||||
local pad = not (opts and opts.pad == false)
|
||||
local wrap = if opts and opts.wrap and opts.wrap >= 4 then opts.wrap // 4 else 0 -- groups per line
|
||||
local wrap = if opts and opts.wrap and opts.wrap >= 4 then opts.wrap // 4 else 0
|
||||
local full = n // 3
|
||||
local rest = n - full * 3
|
||||
local textLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1)
|
||||
@@ -92,7 +85,6 @@ function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: numb
|
||||
return buffer.tostring(out)
|
||||
end
|
||||
|
||||
-- decode(s) -> buffer | nil, message
|
||||
function Base64.decode(s: string | buffer): (buffer?, string?)
|
||||
local src: buffer = if type(s) == "string" then buffer.fromstring(s) else s
|
||||
local n = buffer.len(src)
|
||||
@@ -129,8 +121,7 @@ function Base64.decode(s: string | buffer): (buffer?, string?)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
-- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[<mime>][;params][;base64],<data>" (percent-encoded data
|
||||
-- when not base64)
|
||||
-- RFC 2397: data:[<mime>][;params][;base64],<data> (percent-encoded data when not base64)
|
||||
function Base64.decodeDataUri(uri: string): (buffer?, string?)
|
||||
if string.sub(uri, 1, 5) ~= "data:" then
|
||||
return nil, "not a data: URI"
|
||||
@@ -159,7 +150,6 @@ function Base64.decodeDataUri(uri: string): (buffer?, string?)
|
||||
return buffer.fromstring(decoded), mime
|
||||
end
|
||||
|
||||
-- dataUri(buf, mime?) -> "data:<mime>;base64,..."
|
||||
function Base64.dataUri(buf: buffer | string, mime: string?): string
|
||||
return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf)
|
||||
end
|
||||
|
||||
@@ -2,25 +2,14 @@
|
||||
--!native
|
||||
-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data
|
||||
-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write.
|
||||
--
|
||||
-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes.
|
||||
-- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see
|
||||
-- codecs/compress/Deflate/Inflate) and uses these for headers.
|
||||
--
|
||||
-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED).
|
||||
--
|
||||
-- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader
|
||||
-- local v = br:read(5); if br.err then return nil, br.err end
|
||||
-- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish()
|
||||
-- local w = { buf = buffer.create(n), pos = 0, acc = 0, cnt = 0 }; Bits.msbPut(w, v, nbits) -- encoders' fast path
|
||||
-- (a plain record the caller sizes / grows itself: MP3, MP2 and FLAC frames)
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
local readu8, blen = buffer.readu8, buffer.len
|
||||
local floor = math.floor
|
||||
|
||||
-- 2^n for n = 0..32
|
||||
local POW = table.create(33, 0)
|
||||
for i = 0, 32 do
|
||||
POW[i + 1] = 2 ^ i
|
||||
@@ -29,7 +18,6 @@ end
|
||||
local Bits = {}
|
||||
Bits.POW = POW
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ readers
|
||||
export type BitReader = {
|
||||
buf: buffer,
|
||||
pos: number, -- next byte to load
|
||||
@@ -108,14 +96,12 @@ function Lsb.skip(self: any, n: number)
|
||||
end
|
||||
Lsb.read(self, n)
|
||||
end
|
||||
-- align(): drop the bits up to the next byte boundary
|
||||
function Lsb.align(self: any)
|
||||
local k = self.cnt % 8
|
||||
if k > 0 then
|
||||
Lsb.read(self, k)
|
||||
end
|
||||
end
|
||||
-- bytePos(): the offset of the first byte not yet (even partly) consumed
|
||||
function Lsb.bytePos(self: any): number
|
||||
return self.pos - floor(self.cnt / 8)
|
||||
end
|
||||
@@ -196,7 +182,6 @@ local function reader(meta: any, buf: buffer, offset: number?, length: number?):
|
||||
return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any
|
||||
end
|
||||
|
||||
-- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader
|
||||
function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader
|
||||
return reader(Lsb, buf, offset, length)
|
||||
end
|
||||
@@ -204,7 +189,6 @@ function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReade
|
||||
return reader(Msb, buf, offset, length)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writers
|
||||
export type BitWriter = {
|
||||
out: Bytes.Writer, -- the bytes so far (whole bytes only)
|
||||
acc: number,
|
||||
@@ -234,7 +218,6 @@ function LsbW.write(self: any, v: number, n: number)
|
||||
end
|
||||
self.acc, self.cnt = acc, cnt
|
||||
end
|
||||
-- align(): pad with zero bits to a byte boundary
|
||||
function LsbW.align(self: any)
|
||||
if self.cnt > 0 then
|
||||
self.out:u8(self.acc)
|
||||
@@ -278,8 +261,7 @@ function MsbW.finish(self: any): buffer
|
||||
return self.out:finish()
|
||||
end
|
||||
|
||||
-- msbPut(w, v, n): append the low n bits (n <= 32) of the non-negative integer v to the record w = { buf, pos, acc,
|
||||
-- cnt }, MSB first. No growth: the caller keeps buf large enough (whole bytes go to buf[pos]; acc holds cnt < 8 bits).
|
||||
-- w = { buf, pos, acc, cnt }: no growth (the caller keeps buf large enough); acc holds cnt < 8 bits
|
||||
export type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number }
|
||||
function Bits.msbPut(w: RawWriter, v: number, n: number)
|
||||
if n == 0 then
|
||||
@@ -299,7 +281,6 @@ function Bits.msbPut(w: RawWriter, v: number, n: number)
|
||||
w.acc, w.cnt, w.pos = acc, cnt, p
|
||||
end
|
||||
|
||||
-- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter
|
||||
function Bits.lsbWriter(capacity: number?): BitWriter
|
||||
return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any
|
||||
end
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8.
|
||||
-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author;
|
||||
-- no third-party code). Never throws: the range is clamped.
|
||||
--
|
||||
-- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it)
|
||||
-- Crc32.string(s, crc?) -> u32
|
||||
-- Crc32.msb(buf, offset, length, init?) -> u32 the MSB-first (unreflected) 0x04C11DB7 CRC, raw register: no
|
||||
-- inversions (Ogg: init 0; MPEG-2 sections / bzip2: 0xFFFFFFFF)
|
||||
-- Crc32.MSB_TABLE its 1-based byte table, for codecs that inline it (bzip2)
|
||||
-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; no third-party code). Never throws.
|
||||
local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
|
||||
@@ -43,8 +36,6 @@ for n = 0, 255 do
|
||||
T7[n + 1] = c
|
||||
end
|
||||
|
||||
-- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion
|
||||
-- happens inside), so crc(b, crc(a)) == the CRC of a .. b.
|
||||
local function crc32(buf: buffer, off: number, len: number, crc: number?): number
|
||||
local c = bxor(crc or 0, 0xFFFFFFFF)
|
||||
local i, e = off, off + len
|
||||
@@ -77,7 +68,6 @@ local function crc32(buf: buffer, off: number, len: number, crc: number?): numbe
|
||||
return bxor(c, 0xFFFFFFFF)
|
||||
end
|
||||
|
||||
-- clamp (offset, length) to the buffer
|
||||
local function range(buf: buffer, offset: number?, length: number?): (number, number)
|
||||
local n = buffer.len(buf)
|
||||
local o = math.clamp(offset or 0, 0, n)
|
||||
@@ -95,10 +85,10 @@ function Crc32.string(s: string, crc: number?): number
|
||||
return crc32(buffer.fromstring(s), 0, #s, crc)
|
||||
end
|
||||
|
||||
-- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths)
|
||||
Crc32.raw = crc32
|
||||
|
||||
-- the MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected): Ogg pages, MPEG-2 PSI sections, bzip2 blocks
|
||||
-- MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected, raw register, no inversions): Ogg pages (init 0),
|
||||
-- MPEG-2 PSI sections and bzip2 blocks (init 0xFFFFFFFF)
|
||||
local MSB = table.create(256, 0)
|
||||
for n = 0, 255 do
|
||||
local c = lshift(n, 24)
|
||||
@@ -109,7 +99,6 @@ for n = 0, 255 do
|
||||
end
|
||||
Crc32.MSB_TABLE = MSB
|
||||
|
||||
-- msb(buf, off, len, init?) -> the register after buf[off, off + len) (no inversions; the caller checked the range)
|
||||
function Crc32.msb(buf: buffer, off: number, len: number, init: number?): number
|
||||
local c = init or 0
|
||||
for i = off, off + len - 1 do
|
||||
|
||||
@@ -2,9 +2,6 @@
|
||||
-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data).
|
||||
-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7".
|
||||
-- Never throws: --!native modules may require it.
|
||||
--
|
||||
-- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos)
|
||||
-- if err.code == Err.UNSUPPORTED then ... end
|
||||
local Err = {}
|
||||
|
||||
-- codes
|
||||
@@ -33,24 +30,16 @@ Meta.__tostring = function(e: Err): string
|
||||
return s .. ": " .. e.message
|
||||
end
|
||||
|
||||
-- new(code, message, offset?) -> Err
|
||||
function Err.new(code: string, message: string, offset: number?): Err
|
||||
return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any
|
||||
end
|
||||
|
||||
-- the kinds a private submodule may report: Err codes in either case ("truncated", "CORRUPT", ...)
|
||||
local KIND: { [string]: string } = {}
|
||||
for _, c in { "TRUNCATED", "CORRUPT", "CHECKSUM", "UNSUPPORTED", "LIMIT", "ARG", "IO", "UNKNOWN_FORMAT" } do
|
||||
KIND[c] = c
|
||||
KIND[string.lower(c)] = c
|
||||
end
|
||||
|
||||
-- from(message, offset?, kind?) -> Err: the error plumbing between a private submodule (which returns
|
||||
-- nil / false, "message"[, kind]) and the contract. kind names the code ("truncated", "LIMIT", ...); without it the
|
||||
-- message decides: a "<code>: ..." prefix ("limit: ...", "unsupported: ...") names the code and is dropped;
|
||||
-- "...truncated..." / "...past the end" / "...runs past..." -> TRUNCATED; "unsupported..." -> UNSUPPORTED;
|
||||
-- "checksum..." -> CHECKSUM; anything else CORRUPT. An Err passes
|
||||
-- through unchanged.
|
||||
function Err.from(message: any, offset: number?, kind: string?): Err
|
||||
if Err.is(message) then
|
||||
return message
|
||||
@@ -74,13 +63,10 @@ function Err.from(message: any, offset: number?, kind: string?): Err
|
||||
return Err.new(code :: string, msg, offset)
|
||||
end
|
||||
|
||||
-- is(v) -> true when v is an Err
|
||||
function Err.is(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == Meta
|
||||
end
|
||||
|
||||
-- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to
|
||||
-- tag errors with the format name.
|
||||
function Err.wrap(e: any, format: string?): Err
|
||||
if not Err.is(e) then
|
||||
e = Err.new(Err.CORRUPT, tostring(e))
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
--!strict
|
||||
-- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files
|
||||
-- through the host adapter the API passes in (core never requires host itself).
|
||||
--
|
||||
-- local buf, err, name = Input.resolve(src, opts, host)
|
||||
--
|
||||
-- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path
|
||||
-- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that).
|
||||
-- name: the path (for the extension fallback) or opts.name. Never throws.
|
||||
@@ -17,12 +14,10 @@ export type HostLike = {
|
||||
exists: (path: string) -> boolean,
|
||||
}
|
||||
|
||||
-- looksLikePath(s) -> true for short strings without NUL / newline bytes
|
||||
function Input.looksLikePath(s: string): boolean
|
||||
return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]")
|
||||
end
|
||||
|
||||
-- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err
|
||||
function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?)
|
||||
local o = opts or {}
|
||||
local t = type(src)
|
||||
@@ -50,7 +45,6 @@ function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err
|
||||
return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil
|
||||
end
|
||||
|
||||
-- extension(name) -> the lower-case extension without the dot ("png"), or nil
|
||||
function Input.extension(name: string?): string?
|
||||
if not name then
|
||||
return nil
|
||||
@@ -59,8 +53,6 @@ function Input.extension(name: string?): string?
|
||||
return if ext then string.lower(ext) else nil
|
||||
end
|
||||
|
||||
-- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive
|
||||
-- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found)
|
||||
function Input.sibling(opts: any?, uri: string): buffer?
|
||||
if type(opts) ~= "table" then
|
||||
return nil
|
||||
|
||||
@@ -3,11 +3,6 @@
|
||||
--!optimize 2
|
||||
-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM);
|
||||
-- not for security.
|
||||
--
|
||||
-- local h = Md5.new()
|
||||
-- h:update(buf, offset?, length?) -- any number of times
|
||||
-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again)
|
||||
-- Md5.hex(digest) / Md5.of(buf) -> hex string
|
||||
-- Never throws (ranges are clamped to the buffer).
|
||||
local Md5 = {}
|
||||
|
||||
@@ -145,7 +140,6 @@ function Md5.new(): State
|
||||
}
|
||||
end
|
||||
|
||||
-- hex(digest) -> 32 lower-case hex digits
|
||||
function Md5.hex(d: string): string
|
||||
local out = table.create(#d)
|
||||
for i = 1, #d do
|
||||
@@ -154,7 +148,6 @@ function Md5.hex(d: string): string
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
-- of(buf, offset?, length?) -> hex digest
|
||||
function Md5.of(buf: buffer, offset: number?, length: number?): string
|
||||
local h = Md5.new()
|
||||
h:update(buf, offset, length)
|
||||
|
||||
@@ -1,27 +1,18 @@
|
||||
--!strict
|
||||
-- core/Sniff: helpers for the formats' sniff functions (which return 0..1 from the first bytes, never consuming and
|
||||
-- never throwing): magic comparison and the start of a text file without its UTF-8 byte order mark.
|
||||
--
|
||||
-- function Qoi.sniff(r) return Sniff.magic(r, "qoif") end -- 1 or 0
|
||||
-- function Gz.sniff(r) return Sniff.magic(r, "\31\139\8", 0, 0.9) end -- a custom score
|
||||
-- local head = Sniff.text(r, 64) -- the first 64 bytes, BOM dropped
|
||||
-- local head = Sniff.text(r, 512, true) -- ... and leading whitespace too
|
||||
-- local text = Sniff.dropBom(whole) -- decoders: the BOM off a whole file
|
||||
local Sniff = {}
|
||||
|
||||
type Peeker = { peek: (any, number, number?) -> string }
|
||||
|
||||
-- magic(r, s, at?, score?) -> score (default 1) when the bytes at offset at (default 0) are s, else 0
|
||||
function Sniff.magic(r: Peeker, s: string, at: number?, score: number?): number
|
||||
return if r:peek(#s, at) == s then score or 1 else 0
|
||||
end
|
||||
|
||||
-- dropBom(s) -> s without a leading UTF-8 byte order mark (for decoders reading a whole text file)
|
||||
function Sniff.dropBom(s: string): string
|
||||
return if string.sub(s, 1, 3) == "\239\187\191" then string.sub(s, 4) else s
|
||||
end
|
||||
|
||||
-- text(r, n, trim?) -> up to n bytes from the start without a UTF-8 BOM (and leading whitespace when trim)
|
||||
function Sniff.text(r: Peeker, n: number, trim: boolean?): string
|
||||
local s = r:peek(n)
|
||||
if string.sub(s, 1, 3) == "\239\187\191" then
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
--!strict
|
||||
-- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for
|
||||
-- paths outside them; converts the standard types to LÖVE objects:
|
||||
-- host.toImageData(img) -> love ImageData (rgba8)
|
||||
-- host.fromImageData(imageData) -> Image (rgba8)
|
||||
-- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit)
|
||||
-- paths outside them. ImageData is rgba8; SoundData is 16-bit.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
@@ -42,7 +39,6 @@ function Host.readFile(path: string): (buffer?, Err.Err?)
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
-- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io
|
||||
function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?)
|
||||
local s = buffer.tostring(data)
|
||||
if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then
|
||||
@@ -73,7 +69,6 @@ function Host.exists(path: string): boolean
|
||||
return false
|
||||
end
|
||||
|
||||
-- toImageData(img) -> ImageData | nil, Err
|
||||
function Host.toImageData(img: any): (any, Err.Err?)
|
||||
if img.format ~= "rgba8" then
|
||||
return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format))
|
||||
@@ -90,7 +85,6 @@ function Host.toImageData(img: any): (any, Err.Err?)
|
||||
return love().image.newImageData(img.width, img.height, "rgba8", bytes)
|
||||
end
|
||||
|
||||
-- fromImageData(imageData) -> Image (rgba8 copy)
|
||||
function Host.fromImageData(id: any): Types.Image
|
||||
local w, h = id:getDimensions()
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
@@ -105,11 +99,9 @@ function Host.fromImageData(id: any): Types.Image
|
||||
return img
|
||||
end
|
||||
|
||||
-- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end).
|
||||
function Host.toSoundData(a: any): (any, Err.Err?)
|
||||
local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate
|
||||
if samples == nil then
|
||||
-- a Decoder: read everything
|
||||
local parts, total = {}, 0
|
||||
while true do
|
||||
local out, n = a:read(65536)
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
--!strict
|
||||
-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the
|
||||
-- standard types to engine objects:
|
||||
-- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first)
|
||||
-- host.meshPages(prim, opts?) -> { MeshPage } a triangle Primitive split into pages that fit one EditableMesh
|
||||
-- host.pageData(prim, page, opts?) -> PageData a page's vertices as flat arrays (scaled, centred, sRGB colours)
|
||||
-- host.toEditableMesh(prim, page?, opts?) -> EditableMesh, centre one page as an EditableMesh
|
||||
-- meshPages / pageData are pure (no engine calls: tests/host/roblox.luau runs them on every runtime).
|
||||
-- standard types to EditableImage / EditableMesh.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
@@ -25,7 +20,6 @@ function Host.exists(_path: string): boolean
|
||||
return false
|
||||
end
|
||||
|
||||
-- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8".
|
||||
function Host.toEditableImage(img: any): (any, Err.Err?)
|
||||
if img.format ~= "rgba8" then
|
||||
return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format))
|
||||
@@ -42,24 +36,8 @@ function Host.toEditableImage(img: any): (any, Err.Err?)
|
||||
return ei
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------------------------------------- meshes
|
||||
-- A triangle Primitive (F.ops.mesh.merge gives one in world space) becomes EditableMeshes page by page. One
|
||||
-- EditableMesh holds at most ~20k triangles and 60k vertices (measured in Studio: surfacenet-luau MeshOut), and a client
|
||||
-- has only 8 growable ones at a time: build a page, turn it into what you keep (a MeshPart, a FixedSize copy through
|
||||
-- AssetService:CreateEditableMeshAsync), destroy it, then build the next.
|
||||
--
|
||||
-- local prims = F.ops.mesh.merge(scene, { byMaterial = true })
|
||||
-- for _, prim in prims do
|
||||
-- for _, page in assert(F.host.meshPages(prim)) do
|
||||
-- local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs
|
||||
-- local part = AssetService:CreateMeshPartAsync(Content.fromObject(em))
|
||||
-- part.Position = Vector3.new(centre[1], centre[2], centre[3])
|
||||
-- end
|
||||
-- end
|
||||
--
|
||||
-- Axes: Roblox is right-handed, y up, like glTF: z-up sources (STL, VOX, CAD) go through F.ops.mesh.setUp(scene, "y")
|
||||
-- before merging. Winding: counter-clockwise front faces, as glTF. UVs keep the glTF top-left origin (opts.flipV
|
||||
-- turns them over). Colours: COLOR_0 is linear (glTF); EditableMesh colours are sRGB, so they are converted.
|
||||
-- EditableMesh limits (measured in Studio): ~20k triangles and 60k vertices each, 8 growable per client.
|
||||
-- Roblox is y-up, right-handed, counter-clockwise front faces, as glTF; EditableMesh colours are sRGB, COLOR_0 linear.
|
||||
|
||||
export type MeshPage = {
|
||||
first: number, -- the first triangle (0-based) of the primitive in this page
|
||||
@@ -97,7 +75,6 @@ export type MeshOptions = {
|
||||
yieldEvery: number?, -- default 2000
|
||||
}
|
||||
|
||||
-- the index of each corner (0-based vertex numbers) or nil, Err
|
||||
local function cornerReader(prim: any): ((number) -> number)?
|
||||
local idx = prim.indices
|
||||
if not idx then
|
||||
@@ -125,8 +102,6 @@ local function checkPrim(prim: any): (number, Err.Err?)
|
||||
return n // 3, nil
|
||||
end
|
||||
|
||||
-- meshPages(prim, opts?) -> { MeshPage } | nil, Err: consecutive triangle runs, each within maxTriangles (back faces
|
||||
-- counted when doubleSided) and maxVertices.
|
||||
function Host.meshPages(prim: any, opts: MeshOptions?): ({ MeshPage }?, Err.Err?)
|
||||
local tris, err = checkPrim(prim)
|
||||
if err then
|
||||
@@ -195,8 +170,6 @@ local function toSrgb(c: number): number
|
||||
return if c <= 0.0031308 then c * 12.92 else 1.055 * c ^ (1 / 2.4) - 0.055
|
||||
end
|
||||
|
||||
-- pageData(prim, page, opts?) -> PageData | nil, Err: the page's vertex attributes as flat number arrays, ready for
|
||||
-- engine calls (positions relative to the origin and scaled, unit normals, uvs, sRGB colours).
|
||||
function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData?, Err.Err?)
|
||||
local _, err = checkPrim(prim)
|
||||
if err then
|
||||
@@ -239,7 +212,6 @@ function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData
|
||||
positions[j + 2] = ((getP :: any)(v, 1) - oy) * sy
|
||||
positions[j + 3] = ((getP :: any)(v, 2) - oz) * sz
|
||||
if normals then
|
||||
-- normals of a scaled mesh scale by the inverse
|
||||
local x, y, z = (getN :: any)(v, 0) / sx, (getN :: any)(v, 1) / sy, (getN :: any)(v, 2) / sz
|
||||
local len = math.sqrt(x * x + y * y + z * z)
|
||||
if len > 0 then
|
||||
@@ -274,9 +246,6 @@ function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData
|
||||
}, nil
|
||||
end
|
||||
|
||||
-- toEditableMesh(prim, page?, opts?) -> EditableMesh, centre { x, y, z } | nil, Err. Without a page the whole
|
||||
-- primitive must fit one (else Err.LIMIT: use meshPages). Positions are relative to the centre (place the MeshPart
|
||||
-- there). Engine errors (no free EditableMesh, limits) come back as Err.IO; a mesh this call created is destroyed then.
|
||||
function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (any, any)
|
||||
local o: MeshOptions = opts or {}
|
||||
local pg = page
|
||||
@@ -331,7 +300,6 @@ function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (a
|
||||
if C and cids then
|
||||
local k = (i - 1) * 4
|
||||
local r, g, b, a = C[k + 1], C[k + 2], C[k + 3], C[k + 4]
|
||||
-- equal colours share one id (voxel palettes, flat-coloured models)
|
||||
local key = string.format("%d,%d,%d,%d", math.floor(r * 255 + 0.5), math.floor(g * 255 + 0.5), math.floor(b * 255 + 0.5), math.floor(a * 255 + 0.5))
|
||||
local id = palette[key]
|
||||
if not id then
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
--!strict
|
||||
-- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE
|
||||
-- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system).
|
||||
--
|
||||
-- local host = require("@rosetta/host")
|
||||
-- print(host.name) -- "roblox" | "love" | "luajit" | "luau"
|
||||
-- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO
|
||||
-- -- where there is no file system)
|
||||
local Err = require("@rosetta/core/Err")
|
||||
|
||||
export type Host = {
|
||||
@@ -39,9 +34,7 @@ elseif name == "luajit" then
|
||||
else
|
||||
host = require("@rosetta/host/Luau") :: any
|
||||
end
|
||||
-- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine
|
||||
-- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only
|
||||
-- allows more traces; set _G.ROSETTA_NO_JIT_TUNE = true before requiring the library to leave them alone.
|
||||
-- LuaJIT: the big decoders outgrow the default 1000 traces / 8 MB of mcode; _G.ROSETTA_NO_JIT_TUNE = true skips this.
|
||||
if G.jit ~= nil and type(G.jit.opt) == "table" and not G.ROSETTA_NO_JIT_TUNE then
|
||||
pcall(G.jit.opt.start, "maxtrace=8000", "maxmcode=65536")
|
||||
end
|
||||
|
||||
Reference in new issue
Block a user