ws-cleanup: merge ws/cleanup-types (type annotations)

This commit is contained in:
4DBug committed 2026-10-31 11:27:42 -05:00
commit 5d7c223ab8
115 files changed
+583 -515

No files matched your search

+19 -11
View File
@@ -28,7 +28,7 @@ local BPP: { [string]: number } = {
graya8 = 2, graya8 = 2,
alpha8 = 1, alpha8 = 1,
} }
Types.BPP = table.freeze(BPP) Types.BPP = table.freeze(BPP) :: { [string]: number }
export type ImageMeta = { export type ImageMeta = {
colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ... colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ...
@@ -430,7 +430,7 @@ local COMPONENT_SIZE: { [string]: number } = {
snorm8 = 1, snorm8 = 1,
snorm16 = 2, snorm16 = 2,
} }
Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) :: { [string]: number }
-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer) -- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer)
function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor
local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4)) local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4))
@@ -673,7 +673,7 @@ local OBJECT = { __object = true }
local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends) -- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any } function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
local o = t or {} local o: { [any]: any } = t or {}
if getmetatable(o) == nil then if getmetatable(o) == nil then
setmetatable(o, OBJECT) setmetatable(o, OBJECT)
end end
@@ -769,13 +769,13 @@ local function p2(n: number): string
return string.format("%02d", n) return string.format("%02d", n)
end end
local function fmtDate(d: any): string local function fmtDate(d: any): string
local s = "" local s: string = ""
if d.year then if d.year then
s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1) s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1)
end end
if d.hour then if d.hour then
if s ~= "" then if s ~= "" then
s ..= "T" s = s .. "T"
end end
s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0) s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0)
local ns = d.nanosecond or 0 local ns = d.nanosecond or 0
@@ -864,11 +864,11 @@ end
-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil -- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
function DateLib.parse(s: string): Date? function DateLib.parse(s: string): Date?
local d: any = {} local d: any = {}
local rest = s local rest: string = s
local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$") local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$")
if y then if y then
d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd) d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd)
rest = r1 rest = r1 :: string
if rest == "" then if rest == "" then
return if DateLib.valid(d) then DateLib.new(d) else nil return if DateLib.valid(d) then DateLib.new(d) else nil
end end
@@ -883,17 +883,17 @@ function DateLib.parse(s: string): Date?
return nil return nil
end end
d.hour, d.minute = tonumber(h), tonumber(mi) d.hour, d.minute = tonumber(h), tonumber(mi)
rest = r2 rest = r2 :: string
local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") local sec, r3 = string.match(rest, "^:(%d%d)(.*)$")
if not sec then if not sec then
return nil return nil
end end
d.second = tonumber(sec) d.second = tonumber(sec)
rest = r3 rest = r3 :: string
local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") local frac, r4 = string.match(rest, "^%.(%d+)(.*)$")
if frac then if frac then
d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9))
rest = r4 rest = r4 :: string
else else
d.nanosecond = 0 d.nanosecond = 0
end end
@@ -973,6 +973,14 @@ export type VectorPath = {
strokeWidth: number, strokeWidth: number,
transform: { number }?, -- a, b, c, d, e, f transform: { number }?, -- a, b, c, d, e, f
opacity: number, opacity: number,
group: number?, -- index into meta.groups (svg <g> nesting: opacity / clip-path per group)
clip: number?, -- index into meta.clips (a clip-path)
id: string?,
strokeDashArray: { number }?,
strokeDashOffset: number?,
strokeLineJoin: ("miter" | "round" | "bevel")?, -- default "miter"
strokeLineCap: ("butt" | "round" | "square")?, -- default "butt"
strokeMiterLimit: number?,
} }
export type Vector = { export type Vector = {
kind: "vector", kind: "vector",
@@ -1105,6 +1113,6 @@ Types.CATEGORIES = table.freeze({
subtitle = "subtitles", subtitle = "subtitles",
music = "music", music = "music",
playlist = "playlist", playlist = "playlist",
}) } :: { [string]: string })
return Types return Types
+4 -3
View File
@@ -177,7 +177,8 @@ local function folder(r: Bytes.Reader): Folder
check(r) check(r)
local nin, nout = 1, 1 local nin, nout = 1, 1
if bit32.band(flags, 0x10) ~= 0 then if bit32.band(flags, 0x10) ~= 0 then
nin, nout = number(r), number(r) nin = number(r)
nout = number(r)
if nin > 64 or nout > 64 then if nin > 64 or nout > 64 then
bad(r, "bad coder stream count") bad(r, "bad coder stream count")
end end
@@ -416,11 +417,11 @@ local function filesInfo(r: Bytes.Reader): { File }
if n > 1000000 then if n > 1000000 then
bad(r, "too many files", Err.LIMIT) bad(r, "too many files", Err.LIMIT)
end end
local files: { File } = table.create(n) local files: { File } = table.create(n) :: { File }
for i = 1, n do for i = 1, n do
files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false }
end end
local empties = {} local empties: { number } = {}
while true do while true do
local t = byte(r) local t = byte(r)
if t == K.End then if t == K.End then
+16 -12
View File
@@ -144,7 +144,9 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
if not b then if not b then
return nil, e return nil, e
end end
src, so, sl = b, 0, buffer.len(b) src = b
so = 0
sl = buffer.len(b)
else else
local k = table.find(f.packed, inIdx) local k = table.find(f.packed, inIdx)
if not k then if not k then
@@ -162,14 +164,14 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
src = ctx.buf src = ctx.buf
end end
local id = c.id local id = c.id
local opts = { maxBytes = ctx.maxBytes } local opts: { maxBytes: number?, verify: boolean? } = { maxBytes = ctx.maxBytes }
if id == "\0" then if id == "\0" then
if sl < size then if sl < size then
return nil, Err.new(Err.TRUNCATED, "short stored stream") return nil, Err.new(Err.TRUNCATED, "short stored stream")
end end
local b = buffer.create(size) local b = buffer.create(size)
buffer.copy(b, 0, src, so, size) buffer.copy(b, 0, src, so, size)
return b return b, nil
elseif id == "\3\1\1" then elseif id == "\3\1\1" then
if buffer.len(c.props) < 5 then if buffer.len(c.props) < 5 then
return nil, Err.new(Err.CORRUPT, "bad LZMA properties") return nil, Err.new(Err.CORRUPT, "bad LZMA properties")
@@ -195,7 +197,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
if buffer.len(b) ~= size then if buffer.len(b) ~= size then
return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size") return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size")
end end
return b return b, nil
elseif FILTERS[id] then elseif FILTERS[id] then
if sl ~= size then if sl ~= size then
return nil, Err.new(Err.CORRUPT, "filter size mismatch") return nil, Err.new(Err.CORRUPT, "filter size mismatch")
@@ -206,7 +208,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
if not ok then if not ok then
return nil, e return nil, e
end end
return b return b, nil
end end
return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported")
end end
@@ -226,7 +228,7 @@ local function folderMethod(f: Header.Folder): string
end end
function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
local o = opts or {} local o: DecodeOptions = opts or {}
local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30 local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30
local checkCrc = o.checkCrc ~= false local checkCrc = o.checkCrc ~= false
local b, base, limit = r.buf, r.base, r.limit local b, base, limit = r.buf, r.base, r.limit
@@ -280,17 +282,19 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then
return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch") return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch")
end end
hbuf, hoff, hlen = hb, 0, buffer.len(hb) hbuf = hb
hoff = 0
hlen = buffer.len(hb)
end end
if not parsed then if not parsed then
return nil, Err.new(Err.CORRUPT, "nested encoded headers") return nil, Err.new(Err.CORRUPT, "nested encoded headers")
end end
local s = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
a.meta.folders = #s.folders a.meta.folders = #s.folders
a.meta.solid = false a.meta.solid = false
-- folder caches and the substream -> folder map -- folder caches and the substream -> folder map
local cache: { [number]: buffer } = {} local cache: { [number]: buffer } = {}
local subFolder, subOffset = {}, {} local subFolder: { number }, subOffset: { number } = {}, {}
do do
local si = 1 local si = 1
for fi, f in s.folders do for fi, f in s.folders do
@@ -311,7 +315,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
local function folderData(fi: number): (buffer?, Err.Err?) local function folderData(fi: number): (buffer?, Err.Err?)
local c = cache[fi] local c = cache[fi]
if c then if c then
return c return c, nil
end end
local f = s.folders[fi] local f = s.folders[fi]
local d, e = decodeFolder(ctx, s, f) local d, e = decodeFolder(ctx, s, f)
@@ -322,7 +326,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch")
end end
cache[fi] = d cache[fi] = d
return d return d, nil
end end
local si = 0 local si = 0
for _, file in parsed.files do for _, file in parsed.files do
@@ -376,7 +380,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
if checkCrc and want and Crc32.raw(out, 0, size) ~= want then if checkCrc and want and Crc32.raw(out, 0, size) ~= want then
return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name) return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name)
end end
return out return out, nil
end end
end end
Archive.put(a, e) Archive.put(a, e)
+4 -4
View File
@@ -49,7 +49,7 @@ local function header(b: buffer, o: number, e: number): { [string]: any }
if bit32.band(flg, 4) ~= 0 and q + 2 <= e then if bit32.band(flg, 4) ~= 0 and q + 2 <= e then
q += 2 + buffer.readu16(b, q) q += 2 + buffer.readu16(b, q)
end end
for _, f in { { 8, "name" }, { 16, "comment" } } do for _, f in { { 8, "name" }, { 16, "comment" } } :: { { any } } do
if bit32.band(flg, f[1]) ~= 0 then if bit32.band(flg, f[1]) ~= 0 then
local s = q local s = q
while q < e and buffer.readu8(b, q) ~= 0 do while q < e and buffer.readu8(b, q) ~= 0 do
@@ -85,7 +85,7 @@ function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
size = buffer.len(out), size = buffer.len(out),
compressedSize = r.limit - r.base, compressedSize = r.limit - r.base,
method = "deflate", method = "deflate",
mtime = if h.mtime and h.mtime > 0 then h.mtime else nil, mtime = if h.mtime and h.mtime > 0 then h.mtime :: number else nil,
dir = false, dir = false,
data = out, data = out,
}) })
@@ -94,7 +94,7 @@ end
-- ------------------------------------------------------------------------------------------------ encode -- ------------------------------------------------------------------------------------------------ encode
function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {} local o: EncodeOptions = opts or {}
local level = if o.level == nil then 6 else o.level local level = if o.level == nil then 6 else o.level
if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
return nil, Err.new(Err.ARG, "level must be 0..9") return nil, Err.new(Err.ARG, "level must be 0..9")
@@ -111,7 +111,7 @@ function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if not items then if not items then
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
end end
local files = {} local files: typeof(items) = {}
for _, it in items do for _, it in items do
if not it.entry.dir then if not it.entry.dir then
table.insert(files, it) table.insert(files, it)
+1 -1
View File
@@ -70,7 +70,7 @@ end
-- ------------------------------------------------------------------------------------------------ decode -- ------------------------------------------------------------------------------------------------ decode
function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
local o = opts or {} local o: DecodeOptions = opts or {}
local n = r.limit - r.base local n = r.limit - r.base
local out, res local out, res
local method local method
+1 -1
View File
@@ -136,7 +136,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
end end
function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o = opts or {} local o: DecodeOptions = opts or {}
local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22)
if ierr then if ierr then
return nil, ierr return nil, ierr
+16 -16
View File
@@ -78,42 +78,42 @@ end
local function sampleFormat(comp: string, bits: number): (string?, string?) local function sampleFormat(comp: string, bits: number): (string?, string?)
if comp == "NONE" or comp == "twos" or comp == "" then if comp == "NONE" or comp == "twos" or comp == "" then
if bits >= 1 and bits <= 8 then if bits >= 1 and bits <= 8 then
return "s8" return "s8", nil
elseif bits <= 16 then elseif bits <= 16 then
return "s16be" return "s16be", nil
elseif bits <= 24 then elseif bits <= 24 then
return "s24be" return "s24be", nil
elseif bits <= 32 then elseif bits <= 32 then
return "s32be" return "s32be", nil
end end
return nil, "bad sample size " .. bits return nil, "bad sample size " .. bits
elseif comp == "sowt" then elseif comp == "sowt" then
if bits >= 1 and bits <= 8 then if bits >= 1 and bits <= 8 then
return "s8" return "s8", nil
elseif bits <= 16 then elseif bits <= 16 then
return "s16le" return "s16le", nil
elseif bits <= 24 then elseif bits <= 24 then
return "s24le" return "s24le", nil
elseif bits <= 32 then elseif bits <= 32 then
return "s32le" return "s32le", nil
end end
return nil, "bad sample size " .. bits return nil, "bad sample size " .. bits
elseif comp == "raw " then elseif comp == "raw " then
return "u8" return "u8", nil
elseif comp == "in24" then elseif comp == "in24" then
return "s24be" return "s24be", nil
elseif comp == "in32" then elseif comp == "in32" then
return "s32be" return "s32be", nil
elseif comp == "42ni" then elseif comp == "42ni" then
return "s32le" return "s32le", nil
elseif comp == "fl32" or comp == "FL32" then elseif comp == "fl32" or comp == "FL32" then
return "f32be" return "f32be", nil
elseif comp == "fl64" or comp == "FL64" then elseif comp == "fl64" or comp == "FL64" then
return "f64be" return "f64be", nil
elseif comp == "ulaw" or comp == "ULAW" then elseif comp == "ulaw" or comp == "ULAW" then
return "ulaw" return "ulaw", nil
elseif comp == "alaw" or comp == "ALAW" then elseif comp == "alaw" or comp == "ALAW" then
return "alaw" return "alaw", nil
end end
return nil, "compression " .. string.format("%q", comp) return nil, "compression " .. string.format("%q", comp)
end end
+2 -2
View File
@@ -350,7 +350,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table")
end end
end end
local offsets = table.create(#sizes, 0) local offsets = table.create(#(sizes :: { number }), 0)
local o = p.dataStart local o = p.dataStart
for i, s in sizes :: { number } do for i, s in sizes :: { number } do
offsets[i] = o offsets[i] = o
@@ -585,7 +585,7 @@ end
-- encode(audio | decoder, opts?) -> buffer | nil, Err -- encode(audio | decoder, opts?) -> buffer | nil, Err
function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {} local o: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end end
+4 -4
View File
@@ -121,7 +121,7 @@ end
-- open(r, opts?) -> Types.Decoder | nil, Err -- open(r, opts?) -> Types.Decoder | nil, Err
function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o = opts or {} local o: DecodeOptions = opts or {}
local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples })
if not movie then if not movie then
return nil, err return nil, err
@@ -169,9 +169,9 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
-- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex) -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex)
local smpb = tags.itunsmpb local smpb = tags.itunsmpb
if gapless and not t.edits and smpb then if gapless and not t.edits and smpb then
local f = {} local f: { number } = {}
for w in string.gmatch(smpb, "%x+") do for w in string.gmatch(smpb, "%x+") do
table.insert(f, tonumber(w, 16)) table.insert(f, tonumber(w, 16) :: number)
end end
if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then
skip = f[2] skip = f[2]
@@ -337,7 +337,7 @@ end
-- ------------------------------------------------------------------------------------------------ encode -- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A -- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A
function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {} local o: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end end
+14 -5
View File
@@ -561,7 +561,8 @@ local function intensityStereo(h1: number, h3: number, gr: number)
kr = 1 kr = 1
end end
end end
kl, kr = f32(kl * s), f32(kr * s) kl = f32(kl * s)
kr = f32(kr * s)
for k = left * 4, (left + n - 1) * 4, 4 do for k = left * 4, (left + n - 1) * 4, 4 do
local v = rf(GRBUF, k) local v = rf(GRBUF, k)
wf(GRBUF, k + 2304, v * kr) wf(GRBUF, k + 2304, v * kr)
@@ -1183,8 +1184,14 @@ local function synth(xl: number, dstl: number, nch: number, lins: number)
a3 += z3 * w0 - y3 * w1 a3 += z3 * w0 - y3 * w1
vz -= 256 vz -= 256
vy += 256 vy += 256
z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) z0 = rf(SYN, vz)
y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) z1 = rf(SYN, vz + 4)
z2 = rf(SYN, vz + 8)
z3 = rf(SYN, vz + 12)
y0 = rf(SYN, vy)
y1 = rf(SYN, vy + 4)
y2 = rf(SYN, vy + 8)
y3 = rf(SYN, vy + 12)
b0 += z0 * w3 + y0 * w2 b0 += z0 * w3 + y0 * w2
b1 += z1 * w3 + y1 * w2 b1 += z1 * w3 + y1 * w2
b2 += z2 * w3 + y2 * w2 b2 += z2 * w3 + y2 * w2
@@ -1212,8 +1219,10 @@ local function synth(xl: number, dstl: number, nch: number, lins: number)
a2 += z2 * w0 - y2 * w1 a2 += z2 * w0 - y2 * w1
vz -= 256 vz -= 256
vy += 256 vy += 256
z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) z0 = rf(SYN, vz)
y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) z2 = rf(SYN, vz + 8)
y0 = rf(SYN, vy)
y2 = rf(SYN, vy + 8)
b0 += z0 * w3 + y0 * w2 b0 += z0 * w3 + y0 * w2
b2 += z2 * w3 + y2 * w2 b2 += z2 * w3 + y2 * w2
a0 += y0 * w3 - z0 * w2 a0 += y0 * w3 - z0 * w2
+3 -1
View File
@@ -375,7 +375,9 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
local q = floor((x * inv + 1) * L / 2) local q = floor((x * inv + 1) * L / 2)
return if q < 0 then 0 elseif q > L - 1 then L - 1 else q return if q < 0 then 0 elseif q > L - 1 then L - 1 else q
end end
q0, q1, q2 = quant(sb[o + 1]), quant(sb[o + 2]), quant(sb[o + 3]) q0 = quant(sb[o + 1])
q1 = quant(sb[o + 2])
q2 = quant(sb[o + 3])
end end
if ba >= 17 then if ba >= 17 then
put(w, q0 + L * (q1 + L * q2), tripleBits(ba)) put(w, q0 + L * (q1 + L * q2), tripleBits(ba))
+2 -2
View File
@@ -101,7 +101,7 @@ function Index.build(b: buffer, start: number, stop: number): Index?
if first then if first then
first = false first = false
hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) :: number
version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5 version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5
if fLayer == 3 then if fLayer == 3 then
local ret, frames, d, p = Core.vbrTag(b, pos, fs) local ret, frames, d, p = Core.vbrTag(b, pos, fs)
@@ -150,7 +150,7 @@ function Index.build(b: buffer, start: number, stop: number): Index?
end end
if n == cap then if n == cap then
cap *= 2 cap *= 2
OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) :: buffer
end end
buffer.writeu32(OFF, n * 4, pos) buffer.writeu32(OFF, n * 4, pos)
buffer.writeu16(SIZE, n * 2, fs) buffer.writeu16(SIZE, n * 2, fs)
+5 -3
View File
@@ -179,7 +179,8 @@ local function parseV2(b: buffer, o: number, size: number, tags: any)
local p, e = o + 10, bodyEnd local p, e = o + 10, bodyEnd
if band(flags, 0x80) ~= 0 and ver < 4 then if band(flags, 0x80) ~= 0 and ver < 4 then
body = deunsync(b, p, e) body = deunsync(b, p, e)
p, e = 0, buffer.len(body) p = 0
e = buffer.len(body)
end end
if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then
-- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe) -- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe)
@@ -216,7 +217,8 @@ local function parseV2(b: buffer, o: number, size: number, tags: any)
end end
if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then
fb = deunsync(body, fs, fe) fb = deunsync(body, fs, fe)
fs, fe = 0, buffer.len(fb) fs = 0
fe = buffer.len(fb)
end end
end end
if not skip and fs < fe then if not skip and fs < fe then
@@ -273,7 +275,7 @@ function Tags.parse(b: buffer): (any, number, number)
if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then
local o = start + size - 128 local o = start + size - 128
tags.id3v1 = true tags.id3v1 = true
local v1 = { local v1: { [string]: any } = {
title = v1String(b, o + 3, 30), title = v1String(b, o + 3, 30),
artist = v1String(b, o + 33, 30), artist = v1String(b, o + 33, 30),
album = v1String(b, o + 63, 30), album = v1String(b, o + 63, 30),
+2 -2
View File
@@ -132,7 +132,7 @@ export type Channel = {
bandType: { number }, -- [g * maxSfb + sfb + 1] bandType: { number }, -- [g * maxSfb + sfb + 1]
sf: { number }, sf: { number },
-- tns -- tns
tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter tnsFilters: { { { number } } }, -- per window: { length, order, direction, coefs ... } flattened per filter
} }
export type State = { export type State = {
@@ -447,7 +447,7 @@ local function spectralData(st: State, c: Channel, pulses: { number }?): string?
return "bad spectral code" return "bad spectral code"
end end
-- unpack the symbol into dim values (first value most significant) -- unpack the symbol into dim values (first value most significant)
local vals1, vals2, vals3, vals4 local vals1: number, vals2: number, vals3: number, vals4: number
if dim == 4 then if dim == 4 then
vals4 = sym % mod - off vals4 = sym % mod - off
sym = (sym - (sym % mod)) / mod sym = (sym - (sym % mod)) / mod
+1 -1
View File
@@ -310,7 +310,7 @@ function Aac.decoder(asc: any): (Decoder?, Err.Err?)
sbr = false, sbr = false,
ps = false, ps = false,
frameLength = 1024, frameLength = 1024,
} } :: Config
else else
return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer")
end end
+2 -2
View File
@@ -267,8 +267,8 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number
local x = bitsAt(b, pos, 8) local x = bitsAt(b, pos, 8)
local y = bitsAt(b, pos + 8, 8) local y = bitsAt(b, pos + 8, 8)
pos += 16 pos += 16
mode[c], denShift[c] = rshift(x, 4), band(x, 15) mode[c], denShift[c] = rshift(x, 4), band(x, 15) :: number
pbFactor[c], order[c] = rshift(y, 5), band(y, 31) pbFactor[c], order[c] = rshift(y, 5), band(y, 31) :: number
if pos + order[c] * 16 > limit then if pos + order[c] * 16 > limit then
return nil, "frame runs past the end" return nil, "frame runs past the end"
end end
+3 -3
View File
@@ -182,11 +182,11 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n
local mbuf: buffer? = nil local mbuf: buffer? = nil
local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1 local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1
if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then
mw, mh = floor(mask.width), floor(mask.height) mw, mh = floor(mask.width), floor(mask.height) :: number
if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then
mbuf = mask.pixels mbuf = mask.pixels
end end
mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) :: number
mdef = (tonumber(mask.default) or 255) / 255 mdef = (tonumber(mask.default) or 255) / 255
elseif type(mask) == "table" then elseif type(mask) == "table" then
mdef = (tonumber(mask.default) or 255) / 255 mdef = (tonumber(mask.default) or 255) / 255
@@ -224,7 +224,7 @@ local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: n
local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255 local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255
local mr, mg, mb = sr, sg, sb local mr, mg, mb = sr, sg, sb
if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then
mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) :: number
elseif m == 6 then elseif m == 6 then
if lum(sr, sg, sb) >= lum(br, bg, bb) then if lum(sr, sg, sb) >= lum(br, bg, bb) then
mr, mg, mb = br, bg, bb mr, mg, mb = br, bg, bb
+1 -1
View File
@@ -297,7 +297,7 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?)
local cmds: { any } = {} local cmds: { any } = {}
local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count
local sp = 0 local sp = 0
local trans: { number } = table.create(32, 0) local trans = table.create(32, 0) :: { number }
local x, y = 0, 0 local x, y = 0, 0
local open = false local open = false
local maskbits = 0 local maskbits = 0
+2 -2
View File
@@ -296,8 +296,8 @@ function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w:
local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number
if x + 7 <= lastX then if x + 7 <= lastX then
local p = row + x local p = row + x
d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) :: number
d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7) d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7) :: number
else else
d0 = readu8(src, row + math.min(x, lastX)) d0 = readu8(src, row + math.min(x, lastX))
d1 = readu8(src, row + math.min(x + 1, lastX)) d1 = readu8(src, row + math.min(x + 1, lastX))
+4 -4
View File
@@ -38,7 +38,7 @@ local CLCAP = Huffman.capacity(19, CLBITS, 7)
-- fixed Huffman tables -- fixed Huffman tables
local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local FLITS, FDISTS local FLITS: number, FDISTS: number
do do
local l = bcreate(288) local l = bcreate(288)
bfill(l, 0, 8, 144) bfill(l, 0, 8, 144)
@@ -69,7 +69,7 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
local op = 0 local op = 0
local pos = start local pos = start
local bitbuf, bitcnt, over = 0, 0, 0 local bitbuf, bitcnt, over = 0, 0, 0
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer
local clt = bcreate(CLCAP * 4) local clt = bcreate(CLCAP * 4)
local lens = bcreate(320) local lens = bcreate(320)
local final = 0 local final = 0
@@ -132,13 +132,13 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
pos += n pos += n
continue continue
end end
local lsub, dsub local lsub: number, dsub: number
if btype == 1 then if btype == 1 then
lt, dt = FLIT, FDIST lt, dt = FLIT, FDIST
lsub, dsub = FLITS, FDISTS lsub, dsub = FLITS, FDISTS
elseif btype == 2 then elseif btype == 2 then
if lt == FLIT then if lt == FLIT then
lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer
end end
local hlit = band(bitbuf, 31) + 257 local hlit = band(bitbuf, 31) + 257
local hdist = band(rshift(bitbuf, 5), 31) + 1 local hdist = band(rshift(bitbuf, 5), 31) + 1
+12 -12
View File
@@ -146,12 +146,12 @@ local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, st
if e - p < 6 + nf * 3 then if e - p < 6 + nf * 3 then
return nil, "corrupt", "short SOF" return nil, "corrupt", "short SOF"
end end
local comps = {} local comps: { Comp } = {}
local hmax, vmax = 1, 1 local hmax, vmax = 1, 1
for i = 0, nf - 1 do for i = 0, nf - 1 do
local q = p + 6 + i * 3 local q = p + 6 + i * 3
local hv = readu8(b, q + 1) local hv = readu8(b, q + 1)
local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2) local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2) :: number
if h < 1 or h > 4 or v < 1 or v > 4 then if h < 1 or h > 4 or v < 1 or v > 4 then
return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v
end end
@@ -164,7 +164,7 @@ local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, st
return nil, "corrupt", "duplicate component id " .. id return nil, "corrupt", "duplicate component id " .. id
end end
end end
hmax, vmax = math.max(hmax, h), math.max(vmax, v) hmax, vmax = math.max(hmax, h), math.max(vmax, v) :: number
table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp) table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp)
end end
local mcusX = math.ceil(width / (8 * hmax)) local mcusX = math.ceil(width / (8 * hmax))
@@ -186,7 +186,7 @@ local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, st
vmax = vmax, vmax = vmax,
mcusX = mcusX, mcusX = mcusX,
mcusY = mcusY, mcusY = mcusY,
} }, nil, nil
end end
local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string
@@ -243,7 +243,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then
return nil, "arg", "scale must be 1, 2, 4 or 8" return nil, "arg", "scale must be 1, 2, 4 or 8"
end end
local maxPixels = (opts and opts.maxPixels) or 2 ^ 26 local maxPixels: number = (opts and opts.maxPixels) or 2 ^ 26
local quant: { [number]: buffer } = {} local quant: { [number]: buffer } = {}
local dcT: { [number]: buffer } = {} local dcT: { [number]: buffer } = {}
local acT: { [number]: buffer } = {} local acT: { [number]: buffer } = {}
@@ -429,7 +429,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
frame = f frame = f
st.frame = f st.frame = f
if headerOnly then if headerOnly then
return st return st, nil, nil
end end
elseif SOF_REFUSED[m] then elseif SOF_REFUSED[m] then
return nil, "unsupported", SOF_REFUSED[m] .. " JPEG" return nil, "unsupported", SOF_REFUSED[m] .. " JPEG"
@@ -445,7 +445,7 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then
return nil, "corrupt", "bad SOS segment" return nil, "corrupt", "bad SOS segment"
end end
local sc = {} local sc: { Comp } = {}
local blocks = 0 local blocks = 0
for i = 0, ns - 1 do for i = 0, ns - 1 do
local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2) local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2)
@@ -559,12 +559,12 @@ function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly:
st.icc = icc st.icc = icc
end end
if headerOnly then if headerOnly then
return st return st, nil, nil
end end
if scans == 0 then if scans == 0 then
return nil, "truncated", "no image data" return nil, "truncated", "no image data"
end end
return st return st, nil, nil
end end
local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK } local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK }
@@ -697,7 +697,7 @@ end
function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
local f: Frame = st.frame local f: Frame = st.frame
if st.scale ~= 1 or f.precision ~= 8 then if st.scale ~= 1 or f.precision ~= 8 then
return nil return nil, nil, nil, nil
end end
local comps = f.comps local comps = f.comps
local space = colorSpaceOf(f, st.adobe, st.jfif) local space = colorSpaceOf(f, st.adobe, st.jfif)
@@ -721,11 +721,11 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
end end
end end
if not mode then if not mode then
return nil return nil, nil, nil, nil
end end
for _, c in comps do for _, c in comps do
if c.coef and not c.quant then if c.coef and not c.quant then
return nil -- output() reports the missing table return nil, nil, nil, nil -- output() reports the missing table
end end
end end
local w, h = f.width, f.height local w, h = f.width, f.height
+2 -2
View File
@@ -301,7 +301,7 @@ end
-- progressive state (jcphuff.c) -- progressive state (jcphuff.c)
local EOBRUN = 0 local EOBRUN = 0
local BE = 0 local BE = 0
local CORR: { number } = table.create(1000, 0) local CORR = table.create(1000, 0) :: { number }
local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) } local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) }
local curAcFreq: { number } = {} local curAcFreq: { number } = {}
@@ -803,7 +803,7 @@ function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options):
end end
local driSent = false local driSent = false
for _, sc in script do for _, sc in script do
local sComps = {} local sComps: { Comp } = {}
for _, ci in sc.comps do for _, ci in sc.comps do
table.insert(sComps, comps[ci]) table.insert(sComps, comps[ci])
end end
+2 -2
View File
@@ -285,7 +285,7 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?):
return nil, Err.new(Err.CORRUPT, "bad delta filter properties") return nil, Err.new(Err.CORRUPT, "bad delta filter properties")
end end
Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1) Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1)
return true return true, nil
end end
local f = BCJ[id] local f = BCJ[id]
if not f then if not f then
@@ -298,7 +298,7 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?):
return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties")
end end
f(b, o, n, start) f(b, o, n, start)
return true return true, nil
end end
-- ------------------------------------------------------------------------------------------------ xz -- ------------------------------------------------------------------------------------------------ xz
+4 -4
View File
@@ -61,7 +61,7 @@ function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?)
if buffer.len(d) < n * size then if buffer.len(d) < n * size then
return nil, "accessor data shorter than count * components" return nil, "accessor data shorter than count * components"
end end
local out = table.create(n) local out = table.create(n) :: { number }
if t == "f32" then if t == "f32" then
for i = 0, n - 1 do for i = 0, n - 1 do
out[i + 1] = readf32(d, i * 4) out[i + 1] = readf32(d, i * 4)
@@ -142,7 +142,7 @@ local function localMatrix(node: any): ({ number }?, string?)
if not numList(node.matrix, 16) then if not numList(node.matrix, 16) then
return nil, "node matrix is not 16 numbers" return nil, "node matrix is not 16 numbers"
end end
local m = table.create(16) local m = table.create(16) :: { number }
for i = 1, 16 do for i = 1, 16 do
m[i] = node.matrix[i] m[i] = node.matrix[i]
end end
@@ -304,7 +304,7 @@ local function faces(prim: any, nv: number): (any, any, string?)
end end
idx = v idx = v
else else
idx = table.create(nv) idx = table.create(nv) :: { number }
for i = 1, nv do for i = 1, nv do
idx[i] = i - 1 idx[i] = i - 1
end end
@@ -318,7 +318,7 @@ local function faces(prim: any, nv: number): (any, any, string?)
if mode == "triangles" then if mode == "triangles" then
local n = #idx - #idx % 3 local n = #idx - #idx % 3
if n ~= #idx then if n ~= #idx then
local c = table.create(n) local c = table.create(n) :: { number }
table.move(idx, 1, n, 1, c) table.move(idx, 1, n, 1, c)
idx = c idx = c
end end
+6 -6
View File
@@ -134,7 +134,7 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color
local box = boxes[pick] local box = boxes[pick]
local lo, hi, c = box[1], box[2], box[3] local lo, hi, c = box[1], box[2], box[3]
-- sort the range by the channel, ties by bin number: unique numeric keys, no comparator -- sort the range by the channel, ties by bin number: unique numeric keys, no comparator
local keys = table.create(hi - lo + 1) local keys = table.create(hi - lo + 1) :: { number }
for i = lo, hi do for i = lo, hi do
keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i] keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i]
end end
@@ -157,7 +157,7 @@ local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color
boxes[pick] = scored(lo, cut) boxes[pick] = scored(lo, cut)
table.insert(boxes, scored(cut + 1, hi)) table.insert(boxes, scored(cut + 1, hi))
end end
local pal = table.create(#boxes) local pal = table.create(#boxes) :: { Color }
for i, box in boxes do for i, box in boxes do
pal[i] = mean(cnt, sums, bins, box[1], box[2]) pal[i] = mean(cnt, sums, bins, box[1], box[2])
end end
@@ -247,7 +247,7 @@ local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color }
break break
end end
local list = byLevel[lv] local list = byLevel[lv]
local order = table.create(#list) local order = table.create(#list) :: { { any } }
for i, node in list do for i, node in list do
order[i] = { node, subtotal(node), i } order[i] = { node, subtotal(node), i }
end end
@@ -338,7 +338,7 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color },
local dither = opts and opts.dither or false local dither = opts and opts.dither or false
local tidx = opts and opts.transparentIndex local tidx = opts and opts.transparentIndex
-- the searchable entries (the transparent slot is excluded) -- the searchable entries (the transparent slot is excluded)
local pr, pg, pb, pi = {}, {}, {}, {} local pr: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {}
for i, c in palette do for i, c in palette do
if tidx == nil or i - 1 ~= tidx then if tidx == nil or i - 1 ~= tidx then
table.insert(pr, c[1] or 0) table.insert(pr, c[1] or 0)
@@ -350,12 +350,12 @@ function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color },
local np = #pr local np = #pr
-- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best -- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best
do do
local order = table.create(np) local order = table.create(np) :: { number }
for k = 1, np do for k = 1, np do
order[k] = pg[k] * 65536 + k order[k] = pg[k] * 65536 + k
end end
table.sort(order) table.sort(order)
local r2, g2, b2, i2 = table.create(np), table.create(np), table.create(np), table.create(np) local r2, g2, b2, i2 = table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number }
for k = 1, np do for k = 1, np do
local j = order[k] % 65536 local j = order[k] % 65536
r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j] r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j]
+10 -10
View File
@@ -111,7 +111,7 @@ function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c
return self return self
end end
function Builder.close(self: Builder): Builder function Builder.close(self: Builder): Builder
table.insert(self.cmds, { op = "close" }) table.insert(self.cmds, { op = "close" } :: Cmd)
return self return self
end end
-- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths -- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths
@@ -159,12 +159,12 @@ local function flatten(path: any, transform: Transform?, tolerance: number?, min
local cmds = commands(path) local cmds = commands(path)
local polys: { { number } } = {} local polys: { { number } } = {}
if not cmds then if not cmds then
return polys return polys, nil, nil, nil, nil
end end
local m = transform or Raster.IDENTITY local m = transform or Raster.IDENTITY
local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then
return polys return polys, nil, nil, nil, nil
end end
local tol = tolerance or 0.1 local tol = tolerance or 0.1
if type(tol) ~= "number" or not (tol > 0.001) then if type(tol) ~= "number" or not (tol > 0.001) then
@@ -271,7 +271,7 @@ local function flatten(path: any, transform: Transform?, tolerance: number?, min
table.insert(polys, cur) table.insert(polys, cur)
end end
if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then
return polys return polys, nil, nil, nil, nil
end end
return polys, bx0, by0, bx1, by1 return polys, bx0, by0, bx1, by1
end end
@@ -411,7 +411,7 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?)
local o: Options = opts or {} local o: Options = opts or {}
local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance)
if not bx0 then if not bx0 then
return nil return nil, nil
end end
if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then
return nil, "coordinates out of range" return nil, "coordinates out of range"
@@ -427,7 +427,7 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?)
end end
local W, H = X1 - X0, Y1 - Y0 local W, H = X1 - X0, Y1 - Y0
if W <= 0 or H <= 0 then if W <= 0 or H <= 0 then
return nil return nil, nil
end end
local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26 local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26
if W * H > maxPixels then if W * H > maxPixels then
@@ -464,7 +464,7 @@ function Raster.mask(path: any, opts: Options?): (Mask?, string?)
writeu8(cov, os + x, floor(v * 255 + 0.5)) writeu8(cov, os + x, floor(v * 255 + 0.5))
end end
end end
return { x = X0, y = Y0, width = W, height = H, coverage = cov } return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil
end end
-- ------------------------------------------------------------------------------------------------ filling -- ------------------------------------------------------------------------------------------------ filling
@@ -481,7 +481,7 @@ function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean,
if buffer.len(px) < iw * ih * 4 then if buffer.len(px) < iw * ih * 4 then
return false, "fill: image pixels too short" return false, "fill: image pixels too short"
end end
local o: Options = table.clone(opts or {}) local o: Options = table.clone(opts or {} :: Options)
local clip = o.clip local clip = o.clip
if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then
o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) } o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) }
@@ -533,7 +533,7 @@ function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean,
end end
end end
end end
return true return true, nil
end end
-- ------------------------------------------------------------------------------------------------ stroking -- ------------------------------------------------------------------------------------------------ stroking
@@ -572,7 +572,7 @@ local function polygon(out: Path, pts: { number })
table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) table.insert(out, { op = "lineTo", pts[i], pts[i + 1] })
end end
end end
table.insert(out, { op = "close" }) table.insert(out, { op = "close" } :: Cmd)
end end
local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number })
+3 -3
View File
@@ -296,7 +296,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
if layout and not hydra[sid] then if layout and not hydra[sid] then
local rs = RECSIZE[sid] local rs = RECSIZE[sid]
local n = sub:remaining() // rs local n = sub:remaining() // rs
local recs: { { number } } = table.create(n) local recs = table.create(n) :: { { number } }
for i = 1, n do for i = 1, n do
local rec = {} local rec = {}
for _, w in layout do for _, w in layout do
@@ -487,7 +487,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
for _, p in presets do for _, p in presets do
(p :: any)._order = nil (p :: any)._order = nil
end end
local headers: { { [string]: any } } = table.create(nShdr) local headers = table.create(nShdr) :: { { [string]: any } }
for i = 1, nShdr do for i = 1, nShdr do
local sh = shdr[i] local sh = shdr[i]
headers[i] = { headers[i] = {
@@ -503,7 +503,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
type = sh[10], type = sh[10],
} }
end end
local instruments: { { name: string, zones: number } } = table.create(nInst) local instruments = table.create(nInst) :: { { name: string, zones: number } }
for i = 1, nInst do for i = 1, nInst do
instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) }
end end
+9 -9
View File
@@ -54,7 +54,7 @@ function Glyf.range(f: Face, g: number): (number?, number)
if (g + 2) * 4 > f.locaLen then if (g + 2) * 4 > f.locaLen then
return nil, 0 return nil, 0
end end
a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4) a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4) :: number
else else
if (g + 2) * 2 > f.locaLen then if (g + 2) * 2 > f.locaLen then
return nil, 0 return nil, 0
@@ -84,7 +84,7 @@ local MAX_POINTS = 65536
local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?) local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?)
local e = o + len local e = o + len
local ends = table.create(nc) local ends = table.create(nc) :: { number }
local p = o + 10 local p = o + 10
if p + nc * 2 + 2 > e then if p + nc * 2 + 2 > e then
return nil, "glyph header past the end" return nil, "glyph header past the end"
@@ -175,7 +175,7 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour
end end
ys[k] = y ys[k] = y
end end
local out: { Contour } = table.create(nc) local out = table.create(nc) :: { Contour }
local s = 1 local s = 1
for c = 1, nc do for c = 1, nc do
local z = ends[c] + 1 local z = ends[c] + 1
@@ -212,9 +212,9 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con
return nil, "component past the end" return nil, "component past the end"
end end
if band(flags, 2) ~= 0 then if band(flags, 2) ~= 0 then
a1, a2 = i16(b, p), i16(b, p + 2) a1, a2 = i16(b, p), i16(b, p + 2) :: number
else else
a1, a2 = u16(b, p), u16(b, p + 2) a1, a2 = u16(b, p), u16(b, p + 2) :: number
end end
p += 4 p += 4
else else
@@ -222,9 +222,9 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con
return nil, "component past the end" return nil, "component past the end"
end end
if band(flags, 2) ~= 0 then if band(flags, 2) ~= 0 then
a1, a2 = readi8(b, p), readi8(b, p + 1) a1, a2 = readi8(b, p), readi8(b, p + 1) :: number
else else
a1, a2 = readu8(b, p), readu8(b, p + 1) a1, a2 = readu8(b, p), readu8(b, p + 1) :: number
end end
p += 2 p += 2
end end
@@ -248,9 +248,9 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con
return nil, err return nil, err
end end
-- transform the child's points -- transform the child's points
local tc: { Contour } = table.create(#child) local tc = table.create(#child) :: { Contour }
for i, c in child do for i, c in child do
local nx, ny = table.create(#c.x), table.create(#c.x) local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number }
for k = 1, #c.x do for k = 1, #c.x do
local x, y = c.x[k], c.y[k] local x, y = c.x[k], c.y[k]
nx[k] = m1 * x + m3 * y nx[k] = m1 * x + m3 * y
+2 -2
View File
@@ -452,7 +452,7 @@ local function macRoman(b: buffer, o: number, n: number): string
return table.concat(out) return table.concat(out)
end end
local NAME_IDS = { local NAME_IDS: { [number]: string } = {
[0] = "copyright", [0] = "copyright",
[1] = "family", [1] = "family",
[2] = "style", [2] = "style",
@@ -486,7 +486,7 @@ function Tables.names(b: buffer, o: number, n: number): { [string]: string }
local len, off = u16(b, r + 8), u16(b, r + 10) local len, off = u16(b, r + 8), u16(b, r + 10)
local key = NAME_IDS[nid] local key = NAME_IDS[nid]
if key and strings + off + len <= o + n then if key and strings + off + len <= o + n then
local rk, s = 0, nil local rk: number, s: string? = 0, nil
if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then
rk = if lang == 0x409 then 4 else 2 rk = if lang == 0x409 then 4 else 2
s = utf16be(b, strings + off, len) s = utf16be(b, strings + off, len)
+1 -1
View File
@@ -183,7 +183,7 @@ function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?):
if not cmds then if not cmds then
return nil return nil
end end
local o = opts or {} local o: RasterOptions = opts or {}
local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm
local sy = if type(o.scaleY) == "number" then o.scaleY else sx local sy = if type(o.scaleY) == "number" then o.scaleY else sx
local tx, ty = o.shiftX or 0, o.shiftY or 0 local tx, ty = o.shiftX or 0, o.shiftY or 0
+16 -16
View File
@@ -51,7 +51,7 @@ function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) ->
if q then if q then
return q[1], q[2], q[3] return q[1], q[2], q[3]
end end
return nil return nil, nil, nil
end end
function self.flush(_: any) end function self.flush(_: any) end
function self.reset(_: any) function self.reset(_: any)
@@ -95,7 +95,7 @@ local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: n
if pf == "gray" then if pf == "gray" then
u, v = 128, 128 u, v = 128, 128
elseif pf == "yuv420p" then elseif pf == "yuv420p" then
u, v = sample(uo + i * bps), sample(vo + i * bps) u, v = sample(uo + i * bps), sample(vo + i * bps) :: number
elseif pf == "yuv422p" then elseif pf == "yuv422p" then
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2 u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2
@@ -155,18 +155,18 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec
if pf == "yuv420p" and bits == 8 then if pf == "yuv420p" and bits == 8 then
local img = Types.Image.new(w, h, "yuv420p") local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, need) buffer.copy(img.pixels, 0, data, 0, need)
return img return img, nil
elseif pf == "yv12" then elseif pf == "yv12" then
local img = Types.Image.new(w, h, "yuv420p") local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, w * h) buffer.copy(img.pixels, 0, data, 0, w * h)
buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch) buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch)
buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch) buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch)
return img return img, nil
end end
return rawPlanar(data, pf, bits, w, h) return rawPlanar(data, pf, bits, w, h), nil
end end
local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3
local stride = if track.stride then track.stride else w * bpp local stride: number = track.stride or w * bpp
if n < stride * (h - 1) + w * bpp then if n < stride * (h - 1) + w * bpp then
return nil, Err.new(Err.TRUNCATED, "raw frame too short") return nil, Err.new(Err.TRUNCATED, "raw frame too short")
end end
@@ -185,8 +185,8 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec
buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000) buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000)
end end
end end
return img return img, nil
end) end), nil
end end
local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
@@ -210,21 +210,21 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec
else else
dec = Vp8.newDecoder() dec = Vp8.newDecoder()
end end
end) end), nil
end end
-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout -- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout
-- allows, else rgba8 -- allows, else rgba8
local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Jpeg = require("@formats/codecs/Jpeg") local Jpeg = require("@formats/codecs/Jpeg")
local o = { yuv = true, maxPixels = opts and opts.maxPixels } local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels }
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local img, err = Jpeg.decode(data, 0, buffer.len(data), o) local img, err = Jpeg.decode(data, 0, buffer.len(data), o)
if img and img.format == "yuv420p" then if img and img.format == "yuv420p" then
img.meta.yuv = { range = "full", matrix = "bt601" } img.meta.yuv = { range = "full", matrix = "bt601" }
end end
return img, err return img, err
end) end), nil
end end
-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first -- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first
@@ -269,7 +269,7 @@ local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecD
if q then if q then
return q[1], q[2], q[3] return q[1], q[2], q[3]
end end
return nil return nil, nil, nil
end end
function self.flush(_: any) function self.flush(_: any)
for _ = 1, 4 do for _ = 1, 4 do
@@ -331,7 +331,7 @@ function Video.register(entry: Entry): (boolean, Err.Err?)
for _, m in entry.matroska or {} do for _, m in entry.matroska or {} do
byMatroska[m] = entry.id byMatroska[m] = entry.id
end end
return true return true, nil
end end
for _, e in BUILTIN do for _, e in BUILTIN do
Video.register(e) Video.register(e)
@@ -451,7 +451,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
end end
local index, flushed, skipUntil = 0, false, -math.huge local index, flushed, skipUntil = 0, false, -math.huge
local tid = if track then track.id else -1 local tid = if track then track.id else -1
local scale = if track and track.timescale and track.timescale > 0 then track.timescale else 1000 local scale: number = if track and track.timescale and track.timescale > 0 then track.timescale else 1000
local start = demuxer.startTime or 0 local start = demuxer.startTime or 0
v.startTime = start v.startTime = start
local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0 local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0
@@ -468,8 +468,8 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
if t + 1e-9 >= skipUntil then if t + 1e-9 >= skipUntil then
index += 1 index += 1
local d = defaultDur local d = defaultDur
if lastPts and t > lastPts and defaultDur == 0 then if lastPts and t > (lastPts :: number) and defaultDur == 0 then
d = t - lastPts d = t - (lastPts :: number)
end end
lastPts = t lastPts = t
if o.rgba then if o.rgba then
+2 -2
View File
@@ -676,7 +676,7 @@ local function readCodes(d: State, xs: number, ys: number, cacheBits: number, le
end end
if numMax > 1000 or numMax > xs * ys then if numMax > 1000 or numMax > xs * ys then
-- remap the used groups to [0, numGroups); unused ones are read and checked but not kept -- remap the used groups to [0, numGroups); unused ones are read and checked but not kept
local map: { number } = table.create(numMax, -1) local map = table.create(numMax, -1) :: { number }
numGroups = 0 numGroups = 0
for k = 0, n - 1 do for k = 0, n - 1 do
local g = readu32(img, k * 4) local g = readu32(img, k * 4)
@@ -695,7 +695,7 @@ local function readCodes(d: State, xs: number, ys: number, cacheBits: number, le
if eos(d) then if eos(d) then
return nil, nil, 0, 0, "truncated: meta codes" return nil, nil, 0, 0, "truncated: meta codes"
end end
local groups: { number } = table.create(numGroups * 5, 0) local groups = table.create(numGroups * 5, 0) :: { number }
local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0
for i = 0, numMax - 1 do for i = 0, numMax - 1 do
local slot = if mapping then mapping[i + 1] else i local slot = if mapping then mapping[i + 1] else i
+7 -7
View File
@@ -283,33 +283,33 @@ function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any)
if kw == "SYSTEM" then if kw == "SYSTEM" then
local q = match(s, "^[ \t\n]+()", p + 6) :: any local q = match(s, "^[ \t\n]+()", p + 6) :: any
if not q then if not q then
return nil return nil, nil, nil
end end
local sys, e = literal(q) local sys, e = literal(q)
if not sys then if not sys then
return nil return nil, nil, nil
end end
return "", sys, e return "", sys, e
elseif kw == "PUBLIC" then elseif kw == "PUBLIC" then
local q = match(s, "^[ \t\n]+()", p + 6) :: any local q = match(s, "^[ \t\n]+()", p + 6) :: any
if not q then if not q then
return nil return nil, nil, nil
end end
local pub, e = literal(q) local pub, e = literal(q)
if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then
return nil return nil, nil, nil
end end
local r = match(s, "^[ \t\n]+()", e) :: any local r = match(s, "^[ \t\n]+()", e) :: any
if not r then if not r then
return nil return nil, nil, nil
end end
local sys, e2 = literal(r) local sys, e2 = literal(r)
if not sys then if not sys then
return nil return nil, nil, nil
end end
return pub, sys, e2 return pub, sys, e2
end end
return nil return nil, nil, nil
end end
-- check an entity value's references and expand its character references (the rest expand when used) -- check an entity value's references and expand its character references (the rest expand when used)
local function entityValue(v: string): string? local function entityValue(v: string): string?
+1 -1
View File
@@ -219,7 +219,7 @@ function Xml.descendants(node: Node, name: string?): { Node }
local function walk(n: Node) local function walk(n: Node)
for _, ch in n.children do for _, ch in n.children do
if type(ch) == "table" and string.byte(ch.name) ~= 35 then if type(ch) == "table" and string.byte(ch.name) ~= 35 then
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then if name == nil or ch.name == name or (not find(name :: string, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
table.insert(out, ch) table.insert(out, ch)
end end
walk(ch) walk(ch)
+1 -1
View File
@@ -20,7 +20,7 @@ local Yuv = {}
-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u -- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u
-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224 -- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224
local MATRIX = { local MATRIX: { [string]: { kr: number, kb: number } } = {
bt601 = { kr = 0.299, kb = 0.114 }, bt601 = { kr = 0.299, kb = 0.114 },
bt709 = { kr = 0.2126, kb = 0.0722 }, bt709 = { kr = 0.2126, kb = 0.0722 },
} }
+4 -4
View File
@@ -122,7 +122,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32) hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32)
while p + 8 <= e do while p + 8 <= e do
local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p)) local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p))
hh, hl = bxor(hh, kh), bxor(hl, kl) hh, hl = bxor(hh, kh), bxor(hl, kl) :: number
hh, hl = rotl(hh, hl, 27) hh, hl = rotl(hh, hl, 27)
hh, hl = mul(hh, hl, P1H, P1L) hh, hl = mul(hh, hl, P1H, P1L)
hh, hl = add(hh, hl, P4H, P4L) hh, hl = add(hh, hl, P4H, P4L)
@@ -130,7 +130,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
end end
if p + 4 <= e then if p + 4 <= e then
local kh, kl = mul(0, readu32(b, p), P1H, P1L) local kh, kl = mul(0, readu32(b, p), P1H, P1L)
hh, hl = bxor(hh, kh), bxor(hl, kl) hh, hl = bxor(hh, kh), bxor(hl, kl) :: number
hh, hl = rotl(hh, hl, 23) hh, hl = rotl(hh, hl, 23)
hh, hl = mul(hh, hl, P2H, P2L) hh, hl = mul(hh, hl, P2H, P2L)
hh, hl = add(hh, hl, P3H, P3L) hh, hl = add(hh, hl, P3H, P3L)
@@ -138,7 +138,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
end end
while p < e do while p < e do
local kh, kl = mul(0, readu8(b, p), P5H, P5L) local kh, kl = mul(0, readu8(b, p), P5H, P5L)
hh, hl = bxor(hh, kh), bxor(hl, kl) hh, hl = bxor(hh, kh), bxor(hl, kl) :: number
hh, hl = rotl(hh, hl, 11) hh, hl = rotl(hh, hl, 11)
hh, hl = mul(hh, hl, P1H, P1L) hh, hl = mul(hh, hl, P1H, P1L)
p += 1 p += 1
@@ -146,7 +146,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
-- avalanche -- avalanche
hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33 hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33
hh, hl = mul(hh, hl, P2H, P2L) hh, hl = mul(hh, hl, P2H, P2L)
hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) -- h ^= h >> 29 hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) :: number -- h ^= h >> 29
hh, hl = mul(hh, hl, P3H, P3L) hh, hl = mul(hh, hl, P3H, P3L)
hl = bxor(hl, hh) -- h ^= h >> 32 hl = bxor(hl, hh) -- h ^= h >> 32
return hh, hl return hh, hl
+5 -5
View File
@@ -45,7 +45,7 @@ local function public(e: Entry): Types.ArchiveEntry
end end
function Methods.list(self: any): { Types.ArchiveEntry } function Methods.list(self: any): { Types.ArchiveEntry }
local out = table.create(#self._entries) local out = table.create(#self._entries) :: { Types.ArchiveEntry }
for i, e in self._entries do for i, e in self._entries do
out[i] = public(e) out[i] = public(e)
end end
@@ -59,7 +59,7 @@ function Methods.read(self: any, name: string): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "no entry named " .. tostring(name)) return nil, Err.new(Err.ARG, "no entry named " .. tostring(name))
end end
if e.data then if e.data then
return e.data return e.data, nil
end end
if e.load then if e.load then
local ok, b, err = pcall(e.load) local ok, b, err = pcall(e.load)
@@ -69,9 +69,9 @@ function Methods.read(self: any, name: string): (buffer?, Err.Err?)
if not b then if not b then
return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed") return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed")
end end
return b return b, nil
end end
return buffer.create(0) return buffer.create(0), nil
end end
-- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name -- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name
@@ -91,7 +91,7 @@ end
-- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api) -- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api)
function Methods.write(self: any, opts: any?): (buffer?, Err.Err?) function Methods.write(self: any, opts: any?): (buffer?, Err.Err?)
local enc = self._encode local enc: Encoder? = self._encode
if not enc then if not enc then
return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only") return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only")
end end
+11 -6
View File
@@ -18,8 +18,13 @@ local Mux = require("@formats/containers/Ogg/Mux")
local AudioWrap = {} local AudioWrap = {}
local function allPackets(dmx: any, track: Types.Track): { Types.Packet } type PacketSource = {
local out = {} count: ((self: any, track: number) -> number)?,
get: ((self: any, track: number, k: number) -> Types.Packet?)?,
}
local function allPackets(dmx: PacketSource, track: Types.Track): { Types.Packet }
local out: { Types.Packet } = {}
local n = if dmx.count then dmx:count(track.id) else 0 local n = if dmx.count then dmx:count(track.id) else 0
if n > 0 and dmx.get then if n > 0 and dmx.get then
for k = 1, n do for k = 1, n do
@@ -242,7 +247,7 @@ end
local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?) local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?)
if buffer.len(id) < 30 or buffer.len(setup) < 8 then if buffer.len(id) < 30 or buffer.len(setup) < 8 then
return nil return nil, nil
end end
local bs = buffer.readu8(id, 28) local bs = buffer.readu8(id, 28)
local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) } local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) }
@@ -278,7 +283,7 @@ local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }
return sizes, out return sizes, out
end end
end end
return nil return nil, nil
end end
-- ------------------------------------------------------------------------------------------------ ADTS -- ------------------------------------------------------------------------------------------------ ADTS
@@ -437,11 +442,11 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er
return granule return granule
end end
local mb = 0 local mb = 0
while 2 ^ mb < #modes do while 2 ^ mb < #(modes :: { boolean }) do
mb += 1 mb += 1
end end
local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0 local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0
local cur = sizes[if modes[m + 1] then 2 else 1] local cur = sizes[if (modes :: { boolean })[m + 1] then 2 else 1]
if prev then if prev then
granule += (prev + cur) // 4 granule += (prev + cur) // 4
end end
+1 -1
View File
@@ -491,7 +491,7 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer
w:u32le(0) w:u32le(0)
local moviBase = w:tell() local moviBase = w:tell()
w:string("movi") w:string("movi")
local index = table.create(#chunks) local index = table.create(#chunks) :: { { any } }
for _, c in chunks do for _, c in chunks do
local si, data, key = c[1], c[2], c[3] local si, data, key = c[1], c[2], c[3]
local s = opts.streams[si] local s = opts.streams[si]
+1 -1
View File
@@ -239,7 +239,7 @@ function D.info(self: Demux, track: number, k: number): (number?, number?, numbe
local list = self.byTrack[track] local list = self.byTrack[track]
local i = list and list[k] local i = list and list[k]
if not i then if not i then
return nil return nil, nil, nil, nil, nil
end end
return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i]
end end
+9 -9
View File
@@ -21,11 +21,11 @@ Ebml.UNKNOWN = -1
-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1. -- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1.
function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?)
if pos >= limit then if pos >= limit then
return nil return nil, nil
end end
local b = readu8(buf, pos) local b = readu8(buf, pos)
if b == 0 then if b == 0 then
return nil return nil, nil
end end
local len = 1 local len = 1
local mask = 0x80 local mask = 0x80
@@ -34,7 +34,7 @@ function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?)
mask = mask // 2 mask = mask // 2
end end
if pos + len > limit then if pos + len > limit then
return nil return nil, nil
end end
local v = bit32.band(b, mask - 1) local v = bit32.band(b, mask - 1)
local allOnes = v == mask - 1 local allOnes = v == mask - 1
@@ -55,10 +55,10 @@ end
function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?) function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?)
local v, len = Ebml.vint(buf, pos, limit) local v, len = Ebml.vint(buf, pos, limit)
if v == nil or len == nil then if v == nil or len == nil then
return nil return nil, nil
end end
if v == -1 then if v == -1 then
return nil return nil, nil
end end
return v - (2 ^ (7 * len - 1) - 1), len return v - (2 ^ (7 * len - 1) - 1), len
end end
@@ -66,12 +66,12 @@ end
-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes) -- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes)
function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?) function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?)
if pos >= limit then if pos >= limit then
return nil return nil, nil
end end
local b = readu8(buf, pos) local b = readu8(buf, pos)
local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0 local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0
if len == 0 or pos + len > limit then if len == 0 or pos + len > limit then
return nil return nil, nil
end end
local v = b local v = b
for i = 1, len - 1 do for i = 1, len - 1 do
@@ -84,11 +84,11 @@ end
function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?) function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?)
local id, il = Ebml.id(buf, pos, limit) local id, il = Ebml.id(buf, pos, limit)
if not id or not il then if not id or not il then
return nil return nil, nil, nil
end end
local size, sl = Ebml.vint(buf, pos + il, limit) local size, sl = Ebml.vint(buf, pos + il, limit)
if not size or not sl then if not size or not sl then
return nil return nil, nil, nil
end end
return id, size, pos + il + sl return id, size, pos + il + sl
end end
+6 -6
View File
@@ -324,13 +324,13 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
r:skip(3) r:skip(3)
local n = r:u32be() local n = r:u32be()
if n <= (elst.stop - elst.data) // 12 then if n <= (elst.stop - elst.data) // 12 then
local edits = {} local edits: { Edit } = {}
for _ = 1, n do for _ = 1, n do
local dur, mt local dur: number, mt: number
if v == 1 then if v == 1 then
dur, mt = r:u64be(), r:i64be() dur, mt = r:u64be(), r:i64be() :: number
else else
dur, mt = r:u32be(), r:i32be() dur, mt = r:u32be(), r:i32be() :: number
end end
local rate = r:i32be() / 65536 local rate = r:i32be() / 65536
if r.err then if r.err then
@@ -522,7 +522,7 @@ local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [
if n * 12 > r:remaining() then if n * 12 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start) return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start)
end end
local first, per, desc = {}, {}, {} local first: { number }, per: { number }, desc: { number } = {}, {}, {}
for k = 1, n do for k = 1, n do
first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be() first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be()
end end
@@ -739,7 +739,7 @@ export type Movie = {
-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included) -- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included)
function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?) function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?)
local o = opts or {} local o: Options = opts or {}
local b = r.buf local b = r.buf
local top, terr = Box.list(b, r.base, r.limit) local top, terr = Box.list(b, r.base, r.limit)
if #top == 0 then if #top == 0 then
+2 -2
View File
@@ -187,7 +187,7 @@ function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?)
it = { it = {
id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {}, id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {},
properties = {}, essential = {}, refs = {}, properties = {}, essential = {}, refs = {},
} } :: Item
out.items[id] = it out.items[id] = it
table.insert(out.order, id) table.insert(out.order, id)
end end
@@ -498,7 +498,7 @@ function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: {
end end
if pictures and #pictures > 0 then if pictures and #pictures > 0 then
box(w, "covr", function() box(w, "covr", function()
for _, p in pictures do for _, p in pictures :: { Picture } do
dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data) dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data)
end end
end) end)
+1 -1
View File
@@ -193,7 +193,7 @@ function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
if ok and q <= stop then if ok and q <= stop then
local s = file.streams[id] local s = file.streams[id]
if not s then if not s then
s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } :: Stream
file.streams[id] = s file.streams[id] = s
table.insert(file.order, id) table.insert(file.order, id)
end end
+1 -1
View File
@@ -350,7 +350,7 @@ function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.
end end
local data = e.data or buffer.create(0) local data = e.data or buffer.create(0)
local typ = e.type or (if e.dir then "5" else "0") local typ = e.type or (if e.dir then "5" else "0")
local name = e.name local name: string = e.name
if typ == "5" and string.sub(name, -1) ~= "/" then if typ == "5" and string.sub(name, -1) ~= "/" then
name ..= "/" name ..= "/"
end end
+1 -1
View File
@@ -152,7 +152,7 @@ local function parse(b: buffer): (any, Err.Err?)
return nil, Err.new(Err.CORRUPT, "central directory not found") return nil, Err.new(Err.CORRUPT, "central directory not found")
end end
end end
local entries: { any } = table.create(math.min(count, 65536)) local entries = table.create(math.min(count, 65536)) :: { any }
local p = cdOff + delta local p = cdOff + delta
for i = 1, count do for i = 1, count do
if not sigAt(b, p, SIG_CD) or p + 46 > n then if not sigAt(b, p, SIG_CD) or p + 46 > n then
+5 -5
View File
@@ -60,7 +60,7 @@ local function bigText(s: string): string
end end
-- text + 1 for a decimal string -- text + 1 for a decimal string
local function incText(s: string): string local function incText(s: string): string
local digits = table.create(#s) local digits: { number } = table.create(#s) :: { number }
for i = 1, #s do for i = 1, #s do
digits[i] = string.byte(s, i) - 48 digits[i] = string.byte(s, i) - 48
end end
@@ -73,7 +73,7 @@ local function incText(s: string): string
digits[i] = 0 digits[i] = 0
i -= 1 i -= 1
end end
local out = table.create(#digits) local out: { string } = table.create(#digits) :: { string }
for k, d in digits do for k, d in digits do
out[k] = string.char(48 + d) out[k] = string.char(48 + d)
end end
@@ -296,11 +296,11 @@ function item(st: St, depth: number): (any, string?)
table.insert(t, v) table.insert(t, v)
end end
end end
if n > r:remaining() then if (n :: number) > r:remaining() then
return nil, "array count past the end" return nil, "array count past the end"
end end
local t = table.create(n) local t = table.create(n :: number)
for k = 1, n do for k = 1, n :: number do
local v, ve = item(st, depth + 1) local v, ve = item(st, depth + 1)
if ve then if ve then
return nil, ve return nil, ve
+1 -1
View File
@@ -57,7 +57,7 @@ function Csv.sniff(r: Bytes.Reader): number
end end
for _, d in { ",", "\t", ";" } do for _, d in { ",", "\t", ";" } do
local _, c1 = gsub(l1, d, "") local _, c1 = gsub(l1, d, "")
local _, c2 = gsub(l2, d, "") local _, c2 = gsub(l2 :: string, d, "")
if c1 > 0 and c1 == c2 then if c1 > 0 and c1 == c2 then
return 0.15 return 0.15
end end
+2 -2
View File
@@ -137,11 +137,11 @@ function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
seenKeys[cur] = seen seenKeys[cur] = seen
end end
if seen[key :: string] and o.strict then if seen[key :: string] and o.strict then
return nil, Err.new(Err.CORRUPT, "duplicate key " .. key, lineStart) return nil, Err.new(Err.CORRUPT, "duplicate key " .. (key :: string), lineStart)
end end
seen[key :: string] = true seen[key :: string] = true
if cur == root and type(root[key]) == "table" then if cur == root and type(root[key]) == "table" then
return nil, Err.new(Err.CORRUPT, "top-level key " .. key .. " has the name of a section", lineStart) return nil, Err.new(Err.CORRUPT, "top-level key " .. (key :: string) .. " has the name of a section", lineStart)
end end
Types.set(cur, key, value) Types.set(cur, key, value)
lastKey, lastIndent, lastTable = key, indent, cur lastKey, lastIndent, lastTable = key, indent, cur
+5 -5
View File
@@ -206,7 +206,7 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
-- a (dotted) key: { parts }, next | nil -- a (dotted) key: { parts }, next | nil
local function key(i: number): ({ string }?, number) local function key(i: number): ({ string }?, number)
local keys = {} local keys: { string } = {}
while true do while true do
i = ws(i) i = ws(i)
local c = byte(s, i) local c = byte(s, i)
@@ -232,7 +232,7 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
if k == nil then if k == nil then
return nil, 0 return nil, 0
end end
table.insert(keys, k) table.insert(keys, k :: string)
i = ws(i) i = ws(i)
if byte(s, i) == 46 then if byte(s, i) == 46 then
i += 1 i += 1
@@ -305,7 +305,7 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
end end
return if sign == "-" then -v else v, nexti return if sign == "-" then -v else v, nexti
end end
local text = sign .. digits local text: string = (sign :: string) .. digits
local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$") local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$")
if frac then if frac then
if not digitsOk(frac, "%d") then if not digitsOk(frac, "%d") then
@@ -316,10 +316,10 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
end end
if rest ~= "" then if rest ~= "" then
local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$") local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$")
if not es or not digitsOk(ed, "%d") then if not es or not digitsOk(ed :: string, "%d") then
return fail("bad float", i), 0 return fail("bad float", i), 0
end end
text ..= "e" .. es .. gsub(ed, "_", "") text ..= "e" .. es .. gsub(ed :: string, "_", "")
end end
local v = tonumber(text) local v = tonumber(text)
if v == nil then if v == nil then
+6 -6
View File
@@ -107,13 +107,13 @@ function Parse.text(s: string): (Desc?, string?)
local a: { [string]: string } = {} local a: { [string]: string } = {}
-- key=value, key="quoted value" -- key=value, key="quoted value"
local i = 1 local i = 1
while i <= #rest do while i <= #(rest :: string) do
local k, q, e = string.match(rest, '^%s*([%w_]+)="([^"]*)"()', i) local k, q, e = string.match(rest :: string, '^%s*([%w_]+)="([^"]*)"()', i)
if k then if k then
a[k] = q a[k] = q
i = e i = e
else else
local k2, v2, e2 = string.match(rest, "^%s*([%w_]+)=(%S*)()", i) local k2, v2, e2 = string.match(rest :: string, "^%s*([%w_]+)=(%S*)()", i)
if not k2 then if not k2 then
break break
end end
@@ -135,7 +135,7 @@ function Parse.text(s: string): (Desc?, string?)
end end
-- ------------------------------------------------------------------------------------------------ XML -- ------------------------------------------------------------------------------------------------ XML
local ENTITIES = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" } local ENTITIES: { [string]: string } = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" }
local function unescape(s: string): string local function unescape(s: string): string
return ( return (
string.gsub(s, "&(#?x?%w+);", function(e: string): string? string.gsub(s, "&(#?x?%w+);", function(e: string): string?
@@ -159,8 +159,8 @@ function Parse.xml(s: string): (Desc?, string?)
seenFont = true seenFont = true
end end
local a: { [string]: string } = {} local a: { [string]: string } = {}
for k, q, v in string.gmatch(attrs, "([%w_]+)%s*=%s*([\"'])(.-)%2") do for k, q, v in string.gmatch(attrs :: string, "([%w_]+)%s*=%s*([\"'])(.-)%2") do
a[k] = unescape(v) a[k] = unescape(v :: string)
local _ = q local _ = q
end end
local err = apply(d, tag, a) local err = apply(d, tag, a)
+9 -7
View File
@@ -93,7 +93,7 @@ function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?)
pages[i] = img pages[i] = img
end end
self.pages = pages self.pages = pages
return true return true, nil
end end
local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8
@@ -287,26 +287,28 @@ 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 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") return nil, Err.new(Err.ARG, "bake: expected an outline Font")
end end
local o = opts or {} local o: BakeOptions = opts or {}
local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32 local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32
local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1 local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1
local scale = px / font.unitsPerEm local scale = px / font.unitsPerEm
local glyphs = {} local glyphs: { { cp: number, g: number, img: Types.Image } } = {}
local area = 0 local area = 0
local seen = {} local seen = {}
for _, cp in codepoints(o.chars) do for _, cp in codepoints(o.chars) do
local g = font:glyphIndex(cp) local g = (font :: any):glyphIndex(cp)
if (g ~= 0 or cp == 0) and not seen[cp] then if (g ~= 0 or cp == 0) and not seen[cp] then
seen[cp] = true seen[cp] = true
local img = font:rasterize(g, px) local img: Types.Image? = (font :: any):rasterize(g, px)
if img then if img then
table.insert(glyphs, { cp = cp, g = g, img = img }) table.insert(glyphs, { cp = cp, g = g, img = img })
area += (img.width + pad) * (img.height + pad) area += (img.width + pad) * (img.height + pad)
end end
end end
end end
local size = o.pageSize local size: number
if type(size) ~= "number" then if type(o.pageSize) == "number" then
size = o.pageSize
else
size = 64 size = 64
while size * size < area * 1.3 and size < 4096 do while size * size < area * 1.3 and size < 4096 do
size *= 2 size *= 2
+9 -9
View File
@@ -34,7 +34,7 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s
local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
local base = r.base local base = r.base
if not r:match("wOFF") then if not r:match("wOFF") then
return nil, Err.new(Err.CORRUPT, "bad signature", base) return nil, Err.new(Err.CORRUPT, "bad signature", base), nil
end end
local flavor = r:string(4) local flavor = r:string(4)
local length = r:u32be() local length = r:u32be()
@@ -45,16 +45,16 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s
local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be() local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be()
r:skip(8) r:skip(8)
if r.err then if r.err then
return nil, r.err return nil, r.err, nil
end end
if flavor == "ttcf" then if flavor == "ttcf" then
return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4) return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4), nil
end end
if length > r:size() then if length > r:size() then
return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8) return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8), nil
end end
if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then
return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12) return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12), nil
end end
local dir = {} local dir = {}
for i = 1, numTables do for i = 1, numTables do
@@ -62,7 +62,7 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s
dir[i] = e dir[i] = e
end end
if r.err then if r.err then
return nil, r.err return nil, r.err, nil
end end
local out = buffer.create(total) local out = buffer.create(total)
local w = Bytes.writer(12) local w = Bytes.writer(12)
@@ -80,10 +80,10 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s
local p = 12 + 16 * numTables local p = 12 + 16 * numTables
for i, e in dir do for i, e in dir do
if e.offset + e.comp > r:size() or e.comp > e.orig then if e.offset + e.comp > r:size() or e.comp > e.orig then
return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20) return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20), nil
end end
if p + e.orig > total then if p + e.orig > total then
return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16) return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16), nil
end end
local d = 12 + (i - 1) * 16 local d = 12 + (i - 1) * 16
buffer.writestring(out, d, e.tag) buffer.writestring(out, d, e.tag)
@@ -93,7 +93,7 @@ function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, s
if e.comp < e.orig then if e.comp < e.orig then
local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig) local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig)
if not t then if not t then
return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset) return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset), nil
end end
buffer.copy(out, p, t, 0, e.orig) buffer.copy(out, p, t, 0, e.orig)
else else
+12 -5
View File
@@ -150,9 +150,11 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s
fl = band(fl, 0x7F) fl = band(fl, 0x7F)
local dx, dy local dx, dy
if fl < 10 then if fl < 10 then
dx, dy = 0, withSign(fl, band(fl, 14) * 128 + su8(glyphS)) dx = 0
dy = withSign(fl, band(fl, 14) * 128 + su8(glyphS))
elseif fl < 20 then elseif fl < 20 then
dx, dy = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)), 0 dx = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS))
dy = 0
elseif fl < 84 then elseif fl < 84 then
local b0 = fl - 20 local b0 = fl - 20
local b1 = su8(glyphS) local b1 = su8(glyphS)
@@ -181,12 +183,17 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s
end end
local x0, y0, x1, y1 local x0, y0, x1, y1
if hasBox(g) then if hasBox(g) then
x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS) x0 = si16(bboxS)
y0 = si16(bboxS)
x1 = si16(bboxS)
y1 = si16(bboxS)
else else
x0, y0, x1, y1 = 32767, 32767, -32768, -32768 x0, y0, x1, y1 = 32767, 32767, -32768, -32768
for k = 1, total do for k = 1, total do
x0, y0 = math.min(x0, xs[k]), math.min(y0, ys[k]) x0 = math.min(x0, xs[k])
x1, y1 = math.max(x1, xs[k]), math.max(y1, ys[k]) y0 = math.min(y0, ys[k])
x1 = math.max(x1, xs[k])
y1 = math.max(y1, ys[k])
end end
if total == 0 then if total == 0 then
x0, y0, x1, y1 = 0, 0, 0, 0 x0, y0, x1, y1 = 0, 0, 0, 0
+9 -9
View File
@@ -31,7 +31,7 @@ function Host.readFile(path: string): (buffer?, Err.Err?)
if type(s) ~= "string" then if type(s) ~= "string" then
return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg)) return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg))
end end
return buffer.fromstring(s) return buffer.fromstring(s), nil
end end
local f, msg = io().open(path, "rb") local f, msg = io().open(path, "rb")
if not f then if not f then
@@ -39,7 +39,7 @@ function Host.readFile(path: string): (buffer?, Err.Err?)
end end
local s = f:read("*a") local s = f:read("*a")
f:close() f:close()
return buffer.fromstring(s) return buffer.fromstring(s), nil
end end
-- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io -- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io
@@ -50,7 +50,7 @@ function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?)
if not ok then if not ok then
return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg)) return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg))
end end
return true return true, nil
end end
local f, msg = io().open(path, "wb") local f, msg = io().open(path, "wb")
if not f then if not f then
@@ -58,7 +58,7 @@ function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?)
end end
f:write(s) f:write(s)
f:close() f:close()
return true return true, nil
end end
function Host.exists(path: string): boolean function Host.exists(path: string): boolean
@@ -79,8 +79,8 @@ function Host.toImageData(img: any): (any, Err.Err?)
return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format))
end end
local n = img.width * img.height * 4 local n = img.width * img.height * 4
local F = ffi() local F: any = ffi()
local B = buffer :: any local B: { toffi: ((buffer) -> any)? } = buffer :: any
if F and B.toffi then if F and B.toffi then
local id = love().image.newImageData(img.width, img.height, "rgba8") local id = love().image.newImageData(img.width, img.height, "rgba8")
F.copy(id:getFFIPointer(), B.toffi(img.pixels), n) F.copy(id:getFFIPointer(), B.toffi(img.pixels), n)
@@ -94,8 +94,8 @@ end
function Host.fromImageData(id: any): Types.Image function Host.fromImageData(id: any): Types.Image
local w, h = id:getDimensions() local w, h = id:getDimensions()
local img = Types.Image.new(w, h, "rgba8") local img = Types.Image.new(w, h, "rgba8")
local F = ffi() local F: any = ffi()
local B = buffer :: any local B: { toffi: ((buffer) -> any)? } = buffer :: any
if F and B.toffi and id:getFormat() == "rgba8" then if F and B.toffi and id:getFormat() == "rgba8" then
F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4) F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4)
return img return img
@@ -131,7 +131,7 @@ function Host.toSoundData(a: any): (any, Err.Err?)
end end
local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels) local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels)
local count = frames * channels local count = frames * channels
local F = ffi() local F: any = ffi()
if F then if F then
local p = F.cast("int16_t*", sd:getFFIPointer()) local p = F.cast("int16_t*", sd:getFFIPointer())
for i = 0, count - 1 do for i = 0, count - 1 do
+4 -4
View File
@@ -31,13 +31,13 @@ end
local host: Host local host: Host
if name == "roblox" then if name == "roblox" then
host = require("@formats/host/Roblox") host = require("@formats/host/Roblox") :: any
elseif name == "love" then elseif name == "love" then
host = require("@formats/host/Love") host = require("@formats/host/Love") :: any
elseif name == "luajit" then elseif name == "luajit" then
host = require("@formats/host/LuaJIT") host = require("@formats/host/LuaJIT") :: any
else else
host = require("@formats/host/Luau") host = require("@formats/host/Luau") :: any
end end
-- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine -- 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 -- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only
+8 -3
View File
@@ -209,7 +209,9 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if comp == 3 or comp == 6 then if comp == 3 or comp == 6 then
hasMasks = true hasMasks = true
if hs >= 52 then if hs >= 52 then
rm, gm, bm = readu32(buf, 54), readu32(buf, 58), readu32(buf, 62) rm = readu32(buf, 54)
gm = readu32(buf, 58)
bm = readu32(buf, 62)
if hs >= 56 then if hs >= 56 then
am = readu32(buf, 66) am = readu32(buf, 66)
end end
@@ -218,7 +220,9 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if palStart + count * 4 > n then if palStart + count * 4 > n then
return nil, Err.new(Err.TRUNCATED, "truncated bit masks") return nil, Err.new(Err.TRUNCATED, "truncated bit masks")
end end
rm, gm, bm = readu32(buf, palStart), readu32(buf, palStart + 4), readu32(buf, palStart + 8) rm = readu32(buf, palStart)
gm = readu32(buf, palStart + 4)
bm = readu32(buf, palStart + 8)
if comp == 6 then if comp == 6 then
am = readu32(buf, palStart + 12) am = readu32(buf, palStart + 12)
end end
@@ -385,7 +389,8 @@ function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
local dpi = img.meta and img.meta.dpi local dpi = img.meta and img.meta.dpi
local xp: number, yp: number = 3780, 3780 -- 96 dpi, as Pillow local xp: number, yp: number = 3780, 3780 -- 96 dpi, as Pillow
if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then
xp, yp = math.floor((dpi.x :: number) * 39.3701 + 0.5), math.floor((dpi.y :: number) * 39.3701 + 0.5) xp = math.floor((dpi.x :: number) * 39.3701 + 0.5)
yp = math.floor((dpi.y :: number) * 39.3701 + 0.5)
end end
o:i32le(xp) o:i32le(xp)
o:i32le(yp) o:i32le(yp)
+3 -3
View File
@@ -50,7 +50,7 @@ export type EncodeOptions = {
-- ------------------------------------------------------------------------------------------------ constants -- ------------------------------------------------------------------------------------------------ constants
local readu8 = buffer.readu8 local readu8 = buffer.readu8
local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" } local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" }
local DISPOSE_CODE = { none = 1, background = 2, previous = 3 } local DISPOSE_CODE: { [string]: number } = { none = 1, background = 2, previous = 3 }
-- ------------------------------------------------------------------------------------------------ sniff -- ------------------------------------------------------------------------------------------------ sniff
function Gif.sniff(r: Bytes.Reader): number function Gif.sniff(r: Bytes.Reader): number
@@ -62,7 +62,7 @@ end
-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list -- 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 function colorTable(b: buffer, p: number, n: number): (buffer, { { number } })
local t = buffer.create(1024) local t = buffer.create(1024)
local list = table.create(n) local list: { { number } } = table.create(n) :: { { number } }
for i = 0, 255 do for i = 0, 255 do
buffer.writeu32(t, i * 4, 0xFF000000) buffer.writeu32(t, i * 4, 0xFF000000)
end end
@@ -404,7 +404,7 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
end end
-- palettes -- palettes
local shared = (opts and opts.globalPalette) or not animated local shared = (opts and opts.globalPalette) or not animated
local qopts = { method = method, dither = dither } local qopts: Quantize.PaletteOptions = { method = method, dither = dither }
local globalPal: { { number } }? = nil local globalPal: { { number } }? = nil
local globalTrans = false local globalTrans = false
if shared then if shared then
+2 -2
View File
@@ -106,7 +106,7 @@ function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
return nil, Err.new(Err.TRUNCATED, "no resolution line", p) return nil, Err.new(Err.TRUNCATED, "no resolution line", p)
end end
local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$") local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$")
if not s1 or a1 == a2 or #n1 > 9 or #n2 > 9 then if not s1 or a1 == a2 or #(n1 :: string) > 9 or #(n2 :: string) > 9 then
return nil, Err.new(Err.CORRUPT, "bad resolution line", p) return nil, Err.new(Err.CORRUPT, "bad resolution line", p)
end end
local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number
@@ -170,7 +170,7 @@ function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if truncated then if truncated then
img.meta.truncated = true img.meta.truncated = true
end end
img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1, s2, a2) } img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1 :: string, s2 :: string, a2 :: string) }
return img, nil return img, nil
end end
+1 -1
View File
@@ -175,7 +175,7 @@ function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if typ == 2 then if typ == 2 then
im.meta.hotspot = { x = f1, y = f2 } im.meta.hotspot = { x = f1, y = f2 }
end end
table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame)
local score = im.width * im.height * 64 + depth local score = im.width * im.height * 64 + depth
if score > bestScore then if score > bestScore then
best, bestScore = im, score best, bestScore = im, score
+5 -5
View File
@@ -123,7 +123,7 @@ function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: bo
r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3) r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3)
end end
if fmt == 0 then if fmt == 0 then
writeu32(dst, i * 4, r + g * 256 + b * 65536 + a * 16777216) writeu32(dst, i * 4, r + g * 256 + b * 65536 + (a :: number) * 16777216)
elseif fmt == 1 then elseif fmt == 1 then
writeu8(dst, i * 3, r) writeu8(dst, i * 3, r)
writeu8(dst, i * 3 + 1, g) writeu8(dst, i * 3 + 1, g)
@@ -132,12 +132,12 @@ function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: bo
writeu8(dst, i, r) writeu8(dst, i, r)
elseif fmt == 3 then elseif fmt == 3 then
writeu8(dst, i * 2, r) writeu8(dst, i * 2, r)
writeu8(dst, i * 2 + 1, a) writeu8(dst, i * 2 + 1, a :: number)
elseif fmt == 4 then elseif fmt == 4 then
writeu16(dst, i * 8, r) writeu16(dst, i * 8, r)
writeu16(dst, i * 8 + 2, g) writeu16(dst, i * 8 + 2, g)
writeu16(dst, i * 8 + 4, b) writeu16(dst, i * 8 + 4, b)
writeu16(dst, i * 8 + 6, a) writeu16(dst, i * 8 + 6, a :: number)
elseif fmt == 5 then elseif fmt == 5 then
writeu16(dst, i * 2, r) writeu16(dst, i * 2, r)
end end
@@ -217,9 +217,9 @@ function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boo
for c = 0, vals - 1 do for c = 0, vals - 1 do
local v local v
if ch <= 2 then if ch <= 2 then
v = if c == 0 then gray else a v = if c == 0 then gray else a :: number
else else
v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a :: number
end end
if wide and not w16 then if wide and not w16 then
v *= 257 v *= 257
+14 -13
View File
@@ -38,8 +38,8 @@ export type EncodeOptions = {
} }
-- ------------------------------------------------------------------------------------------------ constants -- ------------------------------------------------------------------------------------------------ constants
local FMT_CODE = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 } local FMT_CODE: { [string]: number } = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 }
local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 } local BPP: { [string]: number } = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 }
local readu8 = buffer.readu8 local readu8 = buffer.readu8
-- ------------------------------------------------------------------------------------------------ sniff -- ------------------------------------------------------------------------------------------------ sniff
@@ -106,7 +106,7 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end end
local kind = string.char(readu8(b, r.base + 1)) local kind = string.char(readu8(b, r.base + 1))
local p = r.base + 2 local p = r.base + 2
local w, h, maxval, ch, mode local w: number?, h: number?, maxval: number?, ch: number, mode: number
local bits = false -- PBM: 1 = black local bits = false -- PBM: 1 = black
local bw = false -- PAM BLACKANDWHITE: 1 = white local bw = false -- PAM BLACKANDWHITE: 1 = white
local tupl: string? = nil local tupl: string? = nil
@@ -137,9 +137,9 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end end
ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1 ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1
bits = kind == "1" or kind == "4" bits = kind == "1" or kind == "4"
mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif maxval > 255 then 2 else 1 mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif (maxval :: number) > 255 then 2 else 1
elseif kind == "7" then elseif kind == "7" then
local depth local depth: number?
while true do while true do
local key local key
key, p = token(b, p, limit) key, p = token(b, p, limit)
@@ -175,15 +175,16 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if w == nil or h == nil or depth == nil or maxval == nil then if w == nil or h == nil or depth == nil or maxval == nil then
return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p) return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p)
end end
if depth < 1 or depth > 4 then if (depth :: number) < 1 or (depth :: number) > 4 then
return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. depth) return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. (depth :: number))
end end
ch = depth ch = depth :: number
bw = tupl ~= nil and string.sub(tupl, 1, 13) == "BLACKANDWHITE" bw = tupl ~= nil and string.sub(tupl :: string, 1, 13) == "BLACKANDWHITE"
mode = if maxval > 255 then 2 else 1 mode = if (maxval :: number) > 255 then 2 else 1
else else
return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
end end
local w, h, maxval = w :: number, h :: number, maxval :: number -- each branch above returns when one is nil
if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then 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)) return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval))
end end
@@ -221,7 +222,7 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if not ok then if not ok then
return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e)) return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e))
end end
local fmt = "rgba8" local fmt: Types.PixelFormat = "rgba8"
if native then if native then
local wide = maxval > 255 local wide = maxval > 255
if bits or bw or ch == 1 then if bits or bw or ch == 1 then
@@ -260,7 +261,7 @@ function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if fc == nil then if fc == nil then
return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format))
end end
local w, h = img.width, img.height local w: number, h: number = img.width, img.height
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer") return nil, Err.new(Err.ARG, "bad image size or pixel buffer")
end end
@@ -301,7 +302,7 @@ function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
end end
local ascii = o.ascii == true local ascii = o.ascii == true
local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32" local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32"
local maxval = o.maxval or (if wideSrc then 65535 else 255) local maxval: number = o.maxval or (if wideSrc then 65535 else 255)
if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then
return nil, Err.new(Err.ARG, "maxval must be 1..65535") return nil, Err.new(Err.ARG, "maxval must be 1..65535")
end end
+11 -3
View File
@@ -26,19 +26,27 @@ function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: numbe
if p + 3 > limit then if p + 3 > limit then
return false, "truncated" return false, "truncated"
end end
r, g, bl = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2) r = readu8(b, p)
g = readu8(b, p + 1)
bl = readu8(b, p + 2)
p += 3 p += 3
elseif op == 0xFF then elseif op == 0xFF then
if p + 4 > limit then if p + 4 > limit then
return false, "truncated" return false, "truncated"
end end
r, g, bl, a = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) r = readu8(b, p)
g = readu8(b, p + 1)
bl = readu8(b, p + 2)
a = readu8(b, p + 3)
p += 4 p += 4
else else
local tag = op // 64 local tag = op // 64
if tag == 0 then if tag == 0 then
local q = op * 4 local q = op * 4
r, g, bl, a = readu8(index, q), readu8(index, q + 1), readu8(index, q + 2), readu8(index, q + 3) r = readu8(index, q)
g = readu8(index, q + 1)
bl = readu8(index, q + 2)
a = readu8(index, q + 3)
elseif tag == 1 then elseif tag == 1 then
r = (r + (op // 16) % 4 - 2) % 256 r = (r + (op // 16) % 4 - 2) % 256
g = (g + (op // 4) % 4 - 2) % 256 g = (g + (op // 4) % 4 - 2) % 256
+1 -1
View File
@@ -109,7 +109,7 @@ function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
buffer.writestring(out, 0, "qoif") buffer.writestring(out, 0, "qoif")
buffer.writeu32(out, 4, bit32.byteswap(w)) buffer.writeu32(out, 4, bit32.byteswap(w))
buffer.writeu32(out, 8, bit32.byteswap(h)) buffer.writeu32(out, 8, bit32.byteswap(h))
buffer.writeu8(out, 12, channels) buffer.writeu8(out, 12, channels :: number)
buffer.writeu8(out, 13, if linear then 1 else 0) buffer.writeu8(out, 13, if linear then 1 else 0)
local o = Codec.encode(img.pixels, n, bpp, out, 14) local o = Codec.encode(img.pixels, n, bpp, out, 14)
buffer.writestring(out, o, "\0\0\0\0\0\0\0\1") buffer.writestring(out, o, "\0\0\0\0\0\0\0\1")
+6 -2
View File
@@ -384,7 +384,9 @@ function Pixels.convert(P: Params)
r, g, bl = 0, 0, 0 r, g, bl = 0, 0, 0
end end
elseif photo == 2 then elseif photo == 2 then
r, g, bl = norm(0, x, y), norm(1, x, y), norm(2, x, y) r = norm(0, x, y)
g = norm(1, x, y)
bl = norm(2, x, y)
elseif photo == 5 then elseif photo == 5 then
local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y) local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y)
r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k) r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k)
@@ -399,7 +401,9 @@ function Pixels.convert(P: Params)
a = norm(alpha, x, y) a = norm(alpha, x, y)
if assoc then if assoc then
if a > 0 then if a > 0 then
r, g, bl = math.min(r / a, 1), math.min(g / a, 1), math.min(bl / a, 1) r = math.min(r / a, 1)
g = math.min(g / a, 1)
bl = math.min(bl / a, 1)
else else
r, g, bl = 0, 0, 0 r, g, bl = 0, 0, 0
end end
+9 -9
View File
@@ -208,7 +208,7 @@ local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: b
-- a chunk past the end: keep what exists (truncated files) -- a chunk past the end: keep what exists (truncated files)
len = math.max(0, math.min(len, c.limit - p)) len = math.max(0, math.min(len, c.limit - p))
if p < c.base or p >= c.limit then if p < c.base or p >= c.limit then
return 0 return 0, nil
end end
end end
local src, sp = c.b, p local src, sp = c.b, p
@@ -221,10 +221,10 @@ local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: b
if comp == 1 then if comp == 1 then
local n = math.min(len, size) local n = math.min(len, size)
buffer.copy(out, o, src, sp, n) buffer.copy(out, o, src, sp, n)
return n return n, nil
elseif comp == 5 then elseif comp == 5 then
local n = Lzw.decode(src, sp, len, out, o, size, "tiff") local n = Lzw.decode(src, sp, len, out, o, size, "tiff")
return n return n, nil
elseif comp == 8 or comp == 32946 then elseif comp == 8 or comp == 32946 then
local raw = Deflate.zlib(src, sp, len, size) local raw = Deflate.zlib(src, sp, len, size)
if not raw then if not raw then
@@ -235,9 +235,9 @@ local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: b
end end
local n = math.min(buffer.len(raw :: buffer), size) local n = math.min(buffer.len(raw :: buffer), size)
buffer.copy(out, o, raw :: buffer, 0, n) buffer.copy(out, o, raw :: buffer, 0, n)
return n return n, nil
elseif comp == 32773 then elseif comp == 32773 then
return Pixels.packbits(src, sp, len, out, o, size) return Pixels.packbits(src, sp, len, out, o, size), nil
end end
return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp) return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp)
end end
@@ -322,7 +322,7 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?):
if not offs or #offs < perPlane * nplanes then if not offs or #offs < perPlane * nplanes then
return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets") return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets")
end end
local planes = table.create(nplanes) local planes: { buffer } = table.create(nplanes) :: { buffer }
for i = 1, nplanes do for i = 1, nplanes do
planes[i] = buffer.create(rb * h + 8) planes[i] = buffer.create(rb * h + 8)
end end
@@ -583,7 +583,7 @@ function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
end end
local img, perr = decodePage(c, t, opts) local img, perr = decodePage(c, t, opts)
if img then if img then
img.meta.source.pages = #list (img.meta.source :: { [string]: any }).pages = #list
end end
return img, perr return img, perr
end end
@@ -608,7 +608,7 @@ function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
end end
local img = first :: Types.Image local img = first :: Types.Image
img.meta.source.pages = #frames (img.meta.source :: { [string]: any }).pages = #frames
if #frames > 1 then if #frames > 1 then
img.frames = frames :: any img.frames = frames :: any
end end
@@ -722,7 +722,7 @@ local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({
end end
local text = img.meta and img.meta.text local text = img.meta and img.meta.text
if type(text) == "table" then if type(text) == "table" then
for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } do for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } :: { [string]: number } do
if type(text[key]) == "string" then if type(text[key]) == "string" then
table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") }) table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") })
end end
+15 -15
View File
@@ -96,7 +96,7 @@ local function detect(buf: buffer, name: string?, category: string?, format: str
if not e then if not e then
return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else "")) return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else ""))
end end
return e return e, nil
end end
local ext = Input.extension(name) local ext = Input.extension(name)
local best: Registry.Entry? = nil local best: Registry.Entry? = nil
@@ -118,12 +118,12 @@ local function detect(buf: buffer, name: string?, category: string?, format: str
end end
end end
if best then if best then
return best return best, nil
end end
if ext then if ext then
local e = find(ext, category) local e = find(ext, category)
if e then if e then
return e return e, nil
end end
end end
return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else "")) return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else ""))
@@ -197,7 +197,7 @@ local function pageLoader(value: any, name: string?, o: Options)
if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then
return return
end end
local user = o.loadPage local user: any = o.loadPage
if value.pages or (value.meta.pageLoader and type(user) ~= "function") then if value.pages or (value.meta.pageLoader and type(user) ~= "function") then
return return
end end
@@ -208,7 +208,7 @@ local function pageLoader(value: any, name: string?, o: Options)
value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?) value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?)
local src: any local src: any
if type(user) == "function" then if type(user) == "function" then
src = user(file, page) src = (user :: any)(file, page)
else else
src = (dir :: string) .. file src = (dir :: string) .. file
end end
@@ -305,7 +305,7 @@ end
-- load(src, opts?) -> value | nil, Err -- load(src, opts?) -> value | nil, Err
function F.load(src: any, opts: Options?): (any, Err.Err?) function F.load(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {} local o: Options = opts or {}
local buf, ierr, name = Input.resolve(src, o, host) local buf, ierr, name = Input.resolve(src, o, host)
if not buf then if not buf then
return nil, ierr return nil, ierr
@@ -357,7 +357,7 @@ load = F.load
-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err -- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err
function F.open(src: any, opts: Options?): (any, Err.Err?) function F.open(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {} local o: Options = opts or {}
local buf, ierr, name = Input.resolve(src, o, host) local buf, ierr, name = Input.resolve(src, o, host)
if not buf then if not buf then
return nil, ierr return nil, ierr
@@ -454,7 +454,7 @@ end
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err -- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
local o = opts or {} local o: Options = opts or {}
local entry, m, err, key = encoderFor(value, dest, o) local entry, m, err, key = encoderFor(value, dest, o)
if not entry then if not entry then
return nil, err return nil, err
@@ -514,12 +514,12 @@ function F.saveString(value: any, opts: Options?): (string?, Err.Err?)
if not buf then if not buf then
return nil, err return nil, err
end end
return buffer.tostring(buf) return buffer.tostring(buf), nil
end end
-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. -- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save.
function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?) function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?)
local o = opts or {} local o: Options = opts or {}
local value, err = F.load(src, o) local value, err = F.load(src, o)
if value == nil then if value == nil then
return nil, err return nil, err
@@ -532,7 +532,7 @@ end
-- detect(src, opts?) -> format name | nil, Err -- detect(src, opts?) -> format name | nil, Err
function F.detect(src: any, opts: Options?): (string?, Err.Err?) function F.detect(src: any, opts: Options?): (string?, Err.Err?)
local o = opts or {} local o: Options = opts or {}
local buf, ierr, name = Input.resolve(src, o, host) local buf, ierr, name = Input.resolve(src, o, host)
if not buf then if not buf then
return nil, ierr return nil, ierr
@@ -541,7 +541,7 @@ function F.detect(src: any, opts: Options?): (string?, Err.Err?)
if not entry then if not entry then
return nil, err return nil, err
end end
return entry.name return entry.name, nil
end end
export type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } } export type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } }
@@ -569,7 +569,7 @@ end
-- ------------------------------------------------------------------------------------------------ category facades -- ------------------------------------------------------------------------------------------------ category facades
-- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category -- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category
local function with(opts: Options?, category: string): Options local function with(opts: Options?, category: string): Options
local o = if opts then table.clone(opts) else {} local o: Options = if opts then table.clone(opts) else {}
o.category = category o.category = category
return o return o
end end
@@ -598,7 +598,7 @@ F.data.null = Types.null
for _, fn in { "toBodies", "fromBodies", "tessellate" } do for _, fn in { "toBodies", "fromBodies", "tessellate" } do
local name: string = fn local name: string = fn
F.cad[name] = function(value: any, opts: Options?): (any, any) F.cad[name] = function(value: any, opts: Options?): (any, any)
local o = if opts then table.clone(opts) else {} local o: Options = if opts then table.clone(opts) else {}
if o.plugins == nil then if o.plugins == nil then
o.plugins = F.plugins o.plugins = F.plugins
end end
@@ -660,7 +660,7 @@ F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: E
if type(scene) ~= "table" or type(scene.textures) ~= "table" then if type(scene) ~= "table" or type(scene.textures) ~= "table" then
return scene, errs return scene, errs
end end
local resolve = opts and opts.resolve local resolve: ((any) -> any)? = opts and opts.resolve
for i, tex in scene.textures do for i, tex in scene.textures do
if type(tex) == "table" and tex.image == nil then if type(tex) == "table" and tex.image == nil then
local data = tex.data local data = tex.data
+7 -3
View File
@@ -57,7 +57,7 @@ function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number,
if rows < 0 or p + rows * size > limit then if rows < 0 or p + rows * size > limit then
return nil, p return nil, p
end end
local counts = table.create(rows) local counts: { number } = table.create(rows) :: { number }
for i = 1, rows do for i = 1, rows do
if psb then if psb then
counts[i] = byteswap(readu32(src, p)) counts[i] = byteswap(readu32(src, p))
@@ -247,11 +247,15 @@ function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth:
local mm = if c2 then sample8(c2, i, depth) else 255 local mm = if c2 then sample8(c2, i, depth) else 255
local yy = if c3 then sample8(c3, i, depth) else 255 local yy = if c3 then sample8(c3, i, depth) else 255
local kk = if c4 then sample8(c4, i, depth) else 255 local kk = if c4 then sample8(c4, i, depth) else 255
r, g, b = floor(cc * kk / 255 + 0.5), floor(mm * kk / 255 + 0.5), floor(yy * kk / 255 + 0.5) r = floor(cc * kk / 255 + 0.5)
g = floor(mm * kk / 255 + 0.5)
b = floor(yy * kk / 255 + 0.5)
elseif mode == 2 then elseif mode == 2 then
local k = if c1 then readu8(c1, i) else 0 local k = if c1 then readu8(c1, i) else 0
if palette and blen(palette) >= 768 then if palette and blen(palette) >= 768 then
r, g, b = readu8(palette, k), readu8(palette, 256 + k), readu8(palette, 512 + k) r = readu8(palette, k)
g = readu8(palette, 256 + k)
b = readu8(palette, 512 + k)
else else
r, g, b = k, k, k r, g, b = k, k, k
end end
+13 -13
View File
@@ -24,7 +24,7 @@ local children, child, text = Xml.children, Xml.child, Xml.text
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/tga", bmp = "image/bmp", gif = "image/gif", webp = "image/webp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", ktx2 = "image/ktx2", hdr = "image/vnd.radiance", exr = "image/x-exr", psd = "image/vnd.adobe.photoshop" } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/tga", bmp = "image/bmp", gif = "image/gif", webp = "image/webp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", ktx2 = "image/ktx2", hdr = "image/vnd.radiance", exr = "image/x-exr", psd = "image/vnd.adobe.photoshop" }
local WRAP = { WRAP = "repeat", MIRROR = "mirror", CLAMP = "clamp", BORDER = "clamp", MIRROR_ONCE = "mirror", NONE = "clamp" } local WRAP = { WRAP = "repeat", MIRROR = "mirror", CLAMP = "clamp", BORDER = "clamp", MIRROR_ONCE = "mirror", NONE = "clamp" }
local PARAM_SIZE = { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 } local PARAM_SIZE: { [string]: number } = { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 }
local MEMBER = { X = 1, Y = 2, Z = 3, ANGLE = 4, W = 4, R = 1, G = 2, B = 3, A = 4, S = 1, T = 2, U = 1, V = 2, P = 3, Q = 4 } local MEMBER = { X = 1, Y = 2, Z = 3, ANGLE = 4, W = 4, R = 1, G = 2, B = 3, A = 4, S = 1, T = 2, U = 1, V = 2, P = 3, Q = 4 }
-- ------------------------------------------------------------------------------------------------ helpers -- ------------------------------------------------------------------------------------------------ helpers
@@ -353,7 +353,7 @@ local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): n
local f = upper(match(text(mag), "[%w_]+") or "") local f = upper(match(text(mag), "[%w_]+") or "")
smp.filter = if f == "NEAREST" then "nearest" elseif f == "LINEAR" then "linear" else nil smp.filter = if f == "NEAREST" then "nearest" elseif f == "LINEAR" then "linear" else nil
end end
if next(smp) then if next(smp :: any) then
tex.sampler = smp tex.sampler = smp
end end
end end
@@ -728,7 +728,7 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil
local np = #p local np = #p
local keyOf: { [any]: number } = {} local keyOf: { [any]: number } = {}
local tuples: { number } = {} -- the first p index of each output vertex's tuple local tuples: { number } = {} -- the first p index of each output vertex's tuple
local corner = table.create(#starts) local corner = table.create(#starts) :: { number }
local count = 0 local count = 0
for ci, s in starts do for ci, s in starts do
local base = s * stride local base = s * stride
@@ -803,7 +803,7 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil
mode = "triangles" mode = "triangles"
elseif C.triangulate then elseif C.triangulate then
-- fan triangulation -- fan triangulation
local tri = {} local tri: { number } = {}
local at = 0 local at = 0
for _, f in faces do for _, f in faces do
for k = 1, f - 2 do for k = 1, f - 2 do
@@ -1067,13 +1067,13 @@ local function camera(C: Ctx, el: any): number?
local tx, ty = math.tan(math.rad(numText(xfov, 45)) / 2), math.tan(yf / 2) local tx, ty = math.tan(math.rad(numText(xfov, 45)) / 2), math.tan(yf / 2)
ar = if ty > 0 then tx / ty else nil ar = if ty > 0 then tx / ty else nil
end end
cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective", yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) } cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective" :: "perspective", yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) } :: Types.Camera
elseif ortho then elseif ortho then
local xm, ym = child(ortho, "xmag"), child(ortho, "ymag") local xm, ym = child(ortho, "xmag"), child(ortho, "ymag")
local ar = numText(child(ortho, "aspect_ratio"), 1) local ar = numText(child(ortho, "aspect_ratio"), 1)
local x = if xm then numText(xm, 1) else numText(ym, 1) * ar local x = if xm then numText(xm, 1) else numText(ym, 1) * ar
local y = if ym then numText(ym, 1) else numText(xm, 1) / ar local y = if ym then numText(ym, 1) else numText(xm, 1) / ar
cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic" :: "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } :: Types.Camera
else else
return nil return nil
end end
@@ -1091,7 +1091,7 @@ local function light(C: Ctx, el: any): (number?, { number }?)
if amb then if amb then
return nil, color(amb) or { 1, 1, 1, 1 } return nil, color(amb) or { 1, 1, 1, 1 }
end end
local kinds = { directional = "directional", point = "point", spot = "spot" } local kinds: { [string]: string } = { directional = "directional", point = "point", spot = "spot" }
for k, t in kinds do for k, t in kinds do
local l = child(tc, k) local l = child(tc, k)
if l then if l then
@@ -1518,7 +1518,7 @@ local function sample(c: Curve, t: number): { number }
local inp, out, st = c.input, c.output, c.stride local inp, out, st = c.input, c.output, c.stride
local n = #inp local n = #inp
local function at(i: number): { number } local function at(i: number): { number }
local r = table.create(st) local r = table.create(st) :: { number }
for k = 1, st do for k = 1, st do
r[k] = out[(i - 1) * st + k] or 0 r[k] = out[(i - 1) * st + k] or 0
end end
@@ -1561,7 +1561,7 @@ local function target(C: Ctx, s: string): ({ number }?, any, number?)
if not id then if not id then
return nil, nil, nil return nil, nil, nil
end end
local spath, rest = match(sids, "^([^%.%(]*)(.*)$") local spath, rest = match(sids :: string, "^([^%.%(]*)(.*)$")
if not spath then if not spath then
return nil, nil, nil return nil, nil, nil
end end
@@ -1734,9 +1734,9 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde
buffer.writef32(ib, (i - 1) * 4, t) buffer.writef32(ib, (i - 1) * 4, t)
end end
local input = Scene.accessor(ib, "f32", 1, n) local input = Scene.accessor(ib, "f32", 1, n)
table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" }) 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" }) 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" }) 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 -- the node is now TRS-driven
local node = C.scene.nodes[ni] local node = C.scene.nodes[ni]
if node.matrix then if node.matrix then
@@ -1829,7 +1829,7 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?
local asset = child(root, "asset") local asset = child(root, "asset")
local up = asset and child(asset, "up_axis") local up = asset and child(asset, "up_axis")
local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP" local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP"
scene.meta.up = if upAxis == "Z_UP" then "z" elseif upAxis == "X_UP" then "x" :: any else "y" scene.meta.up = if upAxis == "Z_UP" then "z" :: "z" elseif upAxis == "X_UP" then "x" :: any else "y" :: "y"
local unit = asset and child(asset, "unit") local unit = asset and child(asset, "unit")
local meter = unit and attr(unit, "meter") local meter = unit and attr(unit, "meter")
scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1 scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1
+2 -2
View File
@@ -157,7 +157,7 @@ function Write.build(scene: Types.Scene, opts: any?): string?
table.insert(out, s) table.insert(out, s)
end end
w('<?xml version="1.0" encoding="utf-8"?>\n<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\n') w('<?xml version="1.0" encoding="utf-8"?>\n<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\n')
local meta = scene.meta or {} 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" local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP"
w(format('<asset><contributor><authoring_tool>formats-luau</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up)) w(format('<asset><contributor><authoring_tool>formats-luau</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up))
-- images -- images
@@ -189,7 +189,7 @@ function Write.build(scene: Types.Scene, opts: any?): string?
w("<library_effects>\n") w("<library_effects>\n")
for i, mat in scene.materials do for i, mat in scene.materials do
local ph: any = mat.extras and mat.extras.phong or {} local ph: any = mat.extras and mat.extras.phong or {}
local params = {} local params: { [any]: any } = {} -- the newparam strings, and their sids as seen-keys
local function texParam(ref: Types.TextureRef?): (string?, number?) local function texParam(ref: Types.TextureRef?): (string?, number?)
if not ref or not imageId[ref.texture] then if not ref or not imageId[ref.texture] then
return nil, nil return nil, nil
+1 -1
View File
@@ -117,7 +117,7 @@ local function zae(r: Bytes.Reader): (any, string?, Err.Err?)
local manifest = zip:readString("manifest.xml") local manifest = zip:readString("manifest.xml")
if manifest then if manifest then
local d = Xml.decode(manifest) local d = Xml.decode(manifest)
local rootEl = d and d.root and Xml.child(d.root, "dae_root") local rootEl = d and d.root and Xml.child(d.root :: Xml.Node, "dae_root")
if rootEl then if rootEl then
main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$") main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$")
main = main and string.gsub(main, "^%./", "") main = main and string.gsub(main, "^%./", "")
+6 -6
View File
@@ -63,17 +63,17 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
-- the values of one node (after the ':'), up to a new name, '{' or '}' -- the values of one node (after the ':'), up to a new name, '{' or '}'
local function values(): ({ any }?, string?) local function values(): ({ any }?, string?)
local props = {} local props: { any } = {}
while true do while true do
skip() skip()
if i > n then if i > n then
return props return props, nil
end end
local c = sbyte(text, i) local c = sbyte(text, i)
if c == 44 then -- , if c == 44 then -- ,
i += 1 i += 1
elseif c == 123 or c == 125 then elseif c == 123 or c == 125 then
return props return props, nil
elseif c == 34 then -- " elseif c == 34 then -- "
local e = sfind(text, "\"", i + 1, true) local e = sfind(text, "\"", i + 1, true)
if not e then if not e then
@@ -117,7 +117,7 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
else else
local nm = nameAt() local nm = nameAt()
if nm then if nm then
return props return props, nil
end end
local s, e = sfind(text, "^[%w_]+", i) local s, e = sfind(text, "^[%w_]+", i)
if not s then if not s then
@@ -230,7 +230,7 @@ function Ascii.write(root: any, version: number?): string
table.insert(parts, string.sub(v, 2)) table.insert(parts, string.sub(v, 2))
else else
local nm, cls = string.match(v, "^(.-)%z\1(.*)$") local nm, cls = string.match(v, "^(.-)%z\1(.*)$")
local sv = if nm then cls .. "::" .. nm else v local sv = if nm then (cls :: string) .. "::" .. nm else v
table.insert(parts, "\"" .. string.gsub(sv, "\"", "&quot;") .. "\"") table.insert(parts, "\"" .. string.gsub(sv, "\"", "&quot;") .. "\"")
end end
elseif tv == "table" and v.array then elseif tv == "table" and v.array then
@@ -246,7 +246,7 @@ function Ascii.write(root: any, version: number?): string
end end
end end
if arr then if arr then
local vals = table.create(arr.count) local vals = table.create(arr.count) :: { string }
for k = 0, arr.count - 1 do for k = 0, arr.count - 1 do
vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8)) vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8))
end end
+2 -2
View File
@@ -38,7 +38,7 @@ local function i64(b: buffer, p: number, asString: boolean): any
end end
Binary.i64 = i64 Binary.i64 = i64
local ELEM = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } 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 -- 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 function toF64(t: string, src: buffer, p: number, n: number): buffer
@@ -170,7 +170,7 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes:
plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296 plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296
nlen = readu8(b, p + 24) nlen = readu8(b, p + 24)
else else
endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), readu8(b, p + 12) endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), (readu8(b, p + 12))
end end
if endOff == 0 then if endOff == 0 then
return false, p + head return false, p + head
+6 -6
View File
@@ -1058,7 +1058,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
local near, far = pnum(p, "NearPlane", 10), pnum(p, "FarPlane", 4000) local near, far = pnum(p, "NearPlane", 10), pnum(p, "FarPlane", 4000)
if ortho then if ortho then
local zoom = pnum(p, "OrthoZoom", 1) local zoom = pnum(p, "OrthoZoom", 1)
cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } :: Types.Camera
else else
local focal = pnum(p, "FocalLength", 0) local focal = pnum(p, "FocalLength", 0)
local hfov local hfov
@@ -1068,7 +1068,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
hfov = pnum(p, "FieldOfView", 40) * math.pi / 180 hfov = pnum(p, "FieldOfView", 40) * math.pi / 180
end end
local yfov = 2 * math.atan(math.tan(hfov / 2) / aspect) local yfov = 2 * math.atan(math.tan(hfov / 2) / aspect)
cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } :: Types.Camera
end end
table.insert(scene.cameras, cam) table.insert(scene.cameras, cam)
table.insert(scene.nodes, { name = o.name .. "_camera", children = {}, camera = #scene.cameras, rotation = { 0, -orient, 0, orient }, extras = { fbx = { orientation = "camera" } } }) table.insert(scene.nodes, { name = o.name .. "_camera", children = {}, camera = #scene.cameras, rotation = { 0, -orient, 0, orient }, extras = { fbx = { orientation = "camera" } } })
@@ -1317,13 +1317,13 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
return false return false
end end
if tr.curves.T or varies(T, 3, nd.translation or { 0, 0, 0 }) then if tr.curves.T or varies(T, 3, nd.translation or { 0, 0, 0 }) then
table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp }) table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp } :: Types.Channel)
end end
if tr.curves.R or varies(R, 4, nd.rotation or { 0, 0, 0, 1 }) then if tr.curves.R or varies(R, 4, nd.rotation or { 0, 0, 0, 1 }) then
table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp }) table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp } :: Types.Channel)
end end
if tr.curves.S or varies(S, 3, nd.scale or { 1, 1, 1 }) then if tr.curves.S or varies(S, 3, nd.scale or { 1, 1, 1 }) then
table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp }) table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp } :: Types.Channel)
end end
end end
end end
@@ -1348,7 +1348,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end end
end end
local acc = f32acc(out, 1) local acc = f32acc(out, 1)
table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = if allConstant(cs) then "STEP" else "LINEAR" }) table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = if allConstant(cs) then "STEP" else "LINEAR" } :: Types.Channel)
end end
end end
end end
+12 -12
View File
@@ -91,7 +91,7 @@ local function faces(prim: Types.Primitive): { { number } }?
if p + sz > count then if p + sz > count then
break break
end end
local poly = table.create(sz) local poly = table.create(sz) :: { number }
for q = 0, sz - 1 do for q = 0, sz - 1 do
poly[q + 1] = I(p + q) poly[q + 1] = I(p + q)
end end
@@ -148,9 +148,9 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
local nodes = scene.nodes or {} local nodes = scene.nodes or {}
-- ------------------------------------------------------------------------------------------ textures -- ------------------------------------------------------------------------------------------ textures
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" } local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" }
local texIds: { [number]: number } = {} local texIds: { [number]: number } = {}
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" local base: string = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
for ti, tex in scene.textures or {} do for ti, tex in scene.textures or {} do
local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png")) local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png"))
local tname = tex.name or ("Texture" .. ti) local tname = tex.name or ("Texture" .. ti)
@@ -295,14 +295,14 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
end end
visiting[i] = true visiting[i] = true
local nd = nodes[i] local nd = nodes[i]
local l = if nd.matrix and #nd.matrix == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale) local l = if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale)
local p = parentOf[i] local p = parentOf[i]
local w = if p then Xform.mul(world(p), l) else l local w = if p then Xform.mul(world(p), l) else l
worldM[i] = w worldM[i] = w
return w return w
end end
local function trs(nd: Types.Node): ({ number }, { number }, { number }) local function trs(nd: Types.Node): ({ number }, { number }, { number })
if nd.matrix and #nd.matrix == 16 then if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then
return Xform.decompose(nd.matrix) return Xform.decompose(nd.matrix)
end end
return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 }
@@ -505,7 +505,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
for v = 0, n - 1 do for v = 0, n - 1 do
local u, w = 0, 0 local u, w = 0, 0
if T then if T then
u, w = T(v, 0), T(v, 1) u, w = T(v, 0), (T(v, 1))
end end
table.insert(UV[k], u) table.insert(UV[k], u)
table.insert(UV[k], if flipV then 1 - w else w) table.insert(UV[k], if flipV then 1 - w else w)
@@ -647,8 +647,8 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
end end
for _, l in layout do for _, l in layout do
local tg = l.prim.targets and (l.prim.targets :: any)[t] local tg = l.prim.targets and (l.prim.targets :: any)[t]
local TP = tg and accessorReader(tg.POSITION) local TP: ((i: number, c: number) -> number)? = tg and accessorReader(tg.POSITION)
local TN = tg and accessorReader(tg.NORMAL) local TN: ((i: number, c: number) -> number)? = tg and accessorReader(tg.NORMAL)
if TP then if TP then
for v = 0, l.prim.attributes.POSITION.count - 1 do for v = 0, l.prim.attributes.POSITION.count - 1 do
local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2) local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2)
@@ -822,7 +822,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } } local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } }
for ai, anim in scene.animations or {} do for ai, anim in scene.animations or {} do
local stid, lid = id(), id() local stid, lid = id(), id()
local astart, astop = math.huge, -math.huge local astart: number, astop: number = math.huge, -math.huge
local layerNodes = {} local layerNodes = {}
for _, ch in anim.channels do for _, ch in anim.channels do
local mid = modelIds[ch.node] local mid = modelIds[ch.node]
@@ -834,7 +834,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
local times = table.create(n, 0) local times = table.create(n, 0)
for k = 0, n - 1 do for k = 0, n - 1 do
times[k + 1] = IN(k, 0) times[k + 1] = IN(k, 0)
astart, astop = math.min(astart, times[k + 1]), math.max(astop, times[k + 1]) astart, astop = math.min(astart, times[k + 1]), (math.max(astop, times[k + 1]))
end end
local cubic = ch.interpolation == "CUBICSPLINE" local cubic = ch.interpolation == "CUBICSPLINE"
local step = ch.interpolation == "STEP" local step = ch.interpolation == "STEP"
@@ -919,8 +919,8 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
end end
-- ------------------------------------------------------------------------------------------ document -- ------------------------------------------------------------------------------------------ document
local meta = scene.meta or {} local meta: { [string]: any } = scene.meta or {}
local src = type(meta.source) == "table" and meta.source or {} local src: { [string]: any } = type(meta.source) == "table" and meta.source or {}
local up = if meta.up == "z" then 2 else 1 local up = if meta.up == "z" then 2 else 1
local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1 local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1
if up == 2 then if up == 2 then
+1 -1
View File
@@ -148,7 +148,7 @@ function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if not scene then if not scene then
return nil, err return nil, err
end end
scene.meta.source.binary = binary (scene.meta.source :: { [string]: any }).binary = binary
return scene, nil return scene, nil
end end
+6 -6
View File
@@ -24,7 +24,7 @@ local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126
local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 } local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 }
local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } 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 MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" }
local WRAP = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } 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" } 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 (everything else that is required -> UNSUPPORTED)
local KNOWN = { local KNOWN = {
@@ -78,7 +78,7 @@ local function numbers(v: any, n: number): { number }?
return nil return nil
end end
end end
return table.move(v, 1, n, 1, {}) return table.move(v, 1, n, 1, {} :: { number })
end end
-- extras.gltf: the JSON extras and the extensions not turned into Scene fields -- extras.gltf: the JSON extras and the extensions not turned into Scene fields
@@ -449,13 +449,13 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc
return nil, Err.new(Err.CORRUPT, "bad indices accessor") return nil, Err.new(Err.CORRUPT, "bad indices accessor")
end end
-- indices must reference existing vertices -- indices must reference existing vertices
local get = Types.Scene.reader(ind) :: any local get = Types.Scene.reader(ind :: Types.Accessor) :: any
for q = 0, ind.count - 1 do for q = 0, ind.count - 1 do
if get(q, 0) >= count then if get(q, 0) >= count then
return nil, Err.new(Err.CORRUPT, "index out of range") return nil, Err.new(Err.CORRUPT, "index out of range")
end end
end end
prim.indices = ind prim.indices = ind :: Types.Accessor
end end
if type(p.targets) == "table" then if type(p.targets) == "table" then
local targets = {} local targets = {}
@@ -484,10 +484,10 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc
end end
if c.type == "orthographic" and type(c.orthographic) == "table" then if c.type == "orthographic" and type(c.orthographic) == "table" then
local o = c.orthographic local o = c.orthographic
table.insert(scene.cameras, { name = str(c.name), type = "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) }) table.insert(scene.cameras, { name = str(c.name), type = "orthographic" :: "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) } :: Types.Camera)
else else
local p = if type(c.perspective) == "table" then c.perspective else {} local p = if type(c.perspective) == "table" then c.perspective else {}
table.insert(scene.cameras, { name = str(c.name), type = "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil }) table.insert(scene.cameras, { name = str(c.name), type = "perspective" :: "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil } :: Types.Camera)
end end
end end
local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual
+2 -2
View File
@@ -385,7 +385,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?)
end end
local gp = object() local gp = object()
gp.attributes = object() gp.attributes = object()
local names = {} local names: { string } = {}
for name in p.attributes do for name in p.attributes do
table.insert(names, name) table.insert(names, name)
end end
@@ -603,7 +603,7 @@ function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?)
return nil, failure return nil, failure
end end
-- scenes: the original list (meta.gltf.scenes) when it is there, else the roots -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots
local meta = if type(scene.meta) == "table" then scene.meta else {} local meta: { [string]: any } = if type(scene.meta) == "table" then scene.meta else {}
local mg = type(meta.gltf) == "table" and meta.gltf or {} local mg = type(meta.gltf) == "table" and meta.gltf or {}
local scenes = {} local scenes = {}
if type(mg.scenes) == "table" and #mg.scenes > 0 then if type(mg.scenes) == "table" and #mg.scenes > 0 then
+1 -1
View File
@@ -158,7 +158,7 @@ function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.
end end
-- ------------------------------------------------------------------------------------------------ encode -- ------------------------------------------------------------------------------------------------ encode
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" } local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" }
function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" then if type(scene) ~= "table" or scene.kind ~= "scene" then
+2 -2
View File
@@ -104,7 +104,7 @@ function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material
if kd and #kd >= 3 then if kd and #kd >= 3 then
m.baseColor = { kd[1], kd[2], kd[3], 1 } m.baseColor = { kd[1], kd[2], kd[3], 1 }
end end
local d = if v.d then v.d[1] elseif v.Tr then 1 - v.Tr[1] else 1 local d = if v.d then (v.d :: { number })[1] elseif v.Tr then 1 - (v.Tr :: { number })[1] else 1
m.baseColor[4] = d m.baseColor[4] = d
if d < 1 then if d < 1 then
m.alphaMode = "blend" m.alphaMode = "blend"
@@ -113,7 +113,7 @@ function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material
if ke and #ke >= 3 then if ke and #ke >= 3 then
m.emissive = { ke[1], ke[2], ke[3] } m.emissive = { ke[1], ke[2], ke[3] }
end end
m.metallic = if v.Pm then v.Pm[1] else 0 m.metallic = if v.Pm then (v.Pm :: { number })[1] else 0
if v.Pr then if v.Pr then
m.roughness = v.Pr[1] m.roughness = v.Pr[1]
elseif v.Ns then elseif v.Ns then
+8 -7
View File
@@ -192,6 +192,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if key == nil or string.sub(key, 1, 1) == "#" then if key == nil or string.sub(key, 1, 1) == "#" then
continue continue
end end
local rest: string = rest :: string -- both captures match together
local hash = string.find(rest, "#", 1, true) local hash = string.find(rest, "#", 1, true)
if hash then if hash then
rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "")
@@ -513,14 +514,14 @@ local function nameOk(s: string): string
return t return t
end end
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" } local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" }
function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene") return nil, Err.new(Err.ARG, "needs a Scene")
end end
local flipV = not (opts and opts.flipV == false) local flipV = not (opts and opts.flipV == false)
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" local base: string = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
local mtlName = opts and opts.mtlName or (base .. ".mtl") local mtlName = opts and opts.mtlName or (base .. ".mtl")
local files = opts and opts.files local files = opts and opts.files
local placed = Types.Scene.flatten(scene) local placed = Types.Scene.flatten(scene)
@@ -586,9 +587,9 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node))) table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node)))
end end
local n = pos.count local n = pos.count
local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0) else nil local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0 :: Types.Accessor) else nil
local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0) else nil local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0 :: Types.Accessor) else nil
local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL) else nil local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL :: Types.Accessor) else nil
for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do
if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then
return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION")
@@ -692,7 +693,7 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
if o + k > count then if o + k > count then
return nil, Err.new(Err.ARG, "faces run past the indices") return nil, Err.new(Err.ARG, "faces run past the indices")
end end
local list = table.create(k) local list = table.create(k) :: { number }
for j = 0, k - 1 do for j = 0, k - 1 do
list[j + 1] = at(o + j) list[j + 1] = at(o + j)
end end
@@ -747,7 +748,7 @@ function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.
if type(scene) ~= "table" or type(scene.materials) ~= "table" then if type(scene) ~= "table" or type(scene.materials) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene") return nil, Err.new(Err.ARG, "needs a Scene")
end end
local files = {} local files: { [string]: string } = {}
local o: any = table.clone(opts or {}) local o: any = table.clone(opts or {})
o.files = files o.files = files
o.mtlName = "x.mtl" o.mtlName = "x.mtl"
+5 -5
View File
@@ -153,13 +153,13 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
local rest = kw local rest = kw
local st, hasC, hasN = false, false, false local st, hasC, hasN = false, false, false
if string.sub(rest, 1, 2) == "ST" then if string.sub(rest, 1, 2) == "ST" then
st, rest = true, string.sub(rest, 3) st, rest = true, (string.sub(rest, 3))
end end
if string.sub(rest, 1, 1) == "C" then if string.sub(rest, 1, 1) == "C" then
hasC, rest = true, string.sub(rest, 2) hasC, rest = true, (string.sub(rest, 2))
end end
if string.sub(rest, 1, 1) == "N" then if string.sub(rest, 1, 1) == "N" then
hasN, rest = true, string.sub(rest, 2) hasN, rest = true, (string.sub(rest, 2))
end end
if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then
return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)") return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)")
@@ -442,7 +442,7 @@ function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals } local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals }
if acc.count == nf then if acc.count == nf then
fc = a fc = a
elseif ex.faceOfTriangle then elseif (ex :: { [string]: any }).faceOfTriangle then
local fot = Flatten.numbers(ex.faceOfTriangle, true) local fot = Flatten.numbers(ex.faceOfTriangle, true)
if fot and #fot == nf then if fot and #fot == nf then
fc, fcMap = a, fot fc, fcMap = a, fot
@@ -468,7 +468,7 @@ function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
end end
p += s p += s
if fc then if fc then
local src = if fcMap then fcMap[f] else f - 1 local src = if fcMap then (fcMap :: { number })[f] else f - 1
table.insert(line, colorText(fc, fc.values, fc.components, src)) table.insert(line, colorText(fc, fc.values, fc.components, src))
end end
table.insert(out, table.concat(line, " ")) table.insert(out, table.concat(line, " "))
+19 -19
View File
@@ -127,8 +127,8 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?)
if not enc or not ENCODINGS[enc] then if not enc or not ENCODINGS[enc] then
return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt)
end end
if string.sub(ver, 1, 1) ~= "1" then if string.sub(ver :: string, 1, 1) ~= "1" then
return nil, Err.new(Err.UNSUPPORTED, "version " .. ver, lineAt) return nil, Err.new(Err.UNSUPPORTED, "version " .. (ver :: string), lineAt)
end end
h.encoding = enc h.encoding = enc
elseif kw == "element" then elseif kw == "element" then
@@ -143,7 +143,7 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?)
if not el then if not el then
return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) return nil, Err.new(Err.CORRUPT, "property before any element", lineAt)
end end
local words = {} local words: { string } = {}
for w in string.gmatch(line, "%S+") do for w in string.gmatch(line, "%S+") do
table.insert(words, w) table.insert(words, w)
end end
@@ -153,9 +153,9 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?)
if not cc or not ic then if not cc or not ic then
return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt)
end end
p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } :: Prop
elseif #words == 3 and CODES[words[2]] then elseif #words == 3 and CODES[words[2]] then
p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } :: Prop
else else
return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt)
end end
@@ -195,11 +195,11 @@ local function newPlan(e: Elem): Plan
code = table.create(np, 0), code = table.create(np, 0),
isList = table.create(np, false), isList = table.create(np, false),
countCode = table.create(np, 2), countCode = table.create(np, 2),
dst = table.create(np), dst = table.create(np) :: { buffer },
dOff = table.create(np, 0), dOff = table.create(np, 0),
dStride = table.create(np, 0), dStride = table.create(np, 0),
dCode = table.create(np, 0), dCode = table.create(np, 0),
sizes = table.create(np), sizes = table.create(np) :: { buffer },
bound = table.create(np, -1), bound = table.create(np, -1),
totals = table.create(np, 0), totals = table.create(np, 0),
} }
@@ -291,7 +291,7 @@ local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err?
local listItems: { [number]: { number } } = {} local listItems: { [number]: { number } } = {}
for k, p in e.props do for k, p in e.props do
if p.list then if p.list then
listSizes[k] = table.create(n) listSizes[k] = table.create(n) :: { number }
listItems[k] = {} listItems[k] = {}
end end
end end
@@ -485,7 +485,7 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if not h then if not h then
return nil, herr return nil, herr
end end
local vi, fi, idxK local vi: number?, fi: number?, idxK: number
for i, e in h.elems do for i, e in h.elems do
if e.name == "vertex" and vi == nil then if e.name == "vertex" and vi == nil then
vi = i vi = i
@@ -767,7 +767,7 @@ local function bufNumbers(b: any, code: number, count: number): { number }?
if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then
return nil return nil
end end
local out = table.create(count) local out = table.create(count) :: { number }
for i = 0, count - 1 do for i = 0, count - 1 do
out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) out[i + 1] = Binary.rd(b, i * SIZE[code], code, false)
end end
@@ -940,7 +940,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
if count == nf then if count == nf then
return vals return vals
elseif fot and #fot == nf then elseif fot and #fot == nf then
local out = table.create(nf) local out = table.create(nf) :: { number }
for i = 1, nf do for i = 1, nf do
local v = vals[fot[i] + 1] local v = vals[fot[i] + 1]
if v == nil then if v == nil then
@@ -954,19 +954,19 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
end end
local extraRows: { [string]: Row } = {} local extraRows: { [string]: Row } = {}
if type(ex) == "table" and type(ex.faceAttributes) == "table" then if type(ex) == "table" and type(ex.faceAttributes) == "table" then
for name, acc in ex.faceAttributes do for name: string, acc: any in ex.faceAttributes do
local vals = Flatten.numbers(acc, true) local vals = Flatten.numbers(acc, true)
local code = CODE_OF_ACC[acc.type] local code = CODE_OF_ACC[acc.type]
if vals and code and acc.components == 1 then if vals and code and acc.components == 1 then
local pv = perFace(vals, acc.count) local pv = perFace(vals, acc.count)
if pv then if pv then
extraRows[name] = { kind = "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } extraRows[name] = { kind = "s" :: "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } }
end end
end end
end end
end end
if type(ex) == "table" and type(ex.faceLists) == "table" then if type(ex) == "table" and type(ex.faceLists) == "table" then
for name, fl in ex.faceLists do for name: string, fl: any in ex.faceLists do
local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true)
local items = type(fl) == "table" and Flatten.numbers(fl.items, true) local items = type(fl) == "table" and Flatten.numbers(fl.items, true)
local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""])
@@ -980,7 +980,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then
lcc = scc lcc = scc
end end
extraRows[name] = { kind = "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } extraRows[name] = { kind = "l" :: "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } }
end end
end end
end end
@@ -1025,7 +1025,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
continue continue
end end
local rows: { Row } = {} local rows: { Row } = {}
for _, pr in el.properties do for _, pr: any in el.properties do
local code = CODES[pr.type or ""] local code = CODES[pr.type or ""]
if not code then if not code then
return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type")
@@ -1043,13 +1043,13 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
if not (cc and sz and items) then if not (cc and sz and items) then
return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name))
end end
table.insert(rows, { kind = "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) table.insert(rows, { kind = "l" :: "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } })
else else
local vals = bufNumbers(pr.values, code, el.count) local vals = bufNumbers(pr.values, code, el.count)
if not vals then if not vals then
return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name))
end end
table.insert(rows, { kind = "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) table.insert(rows, { kind = "s" :: "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } })
end end
end end
raws[el.name] = { name = el.name, count = el.count, rows = rows } raws[el.name] = { name = el.name, count = el.count, rows = rows }
@@ -1084,7 +1084,7 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
-- header -- header
local vrows: { Row } = {} local vrows: { Row } = {}
for _, c in cols do for _, c in cols do
table.insert(vrows, { kind = "s", col = c }) table.insert(vrows, { kind = "s" :: "s", col = c })
end end
local lines = { "ply", "format " .. enc .. " 1.0" } local lines = { "ply", "format " .. enc .. " 1.0" }
local function noNewline(s: any): string local function noNewline(s: any): string
+1 -1
View File
@@ -337,7 +337,7 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
return nil, Err.new(Err.ARG, tostring(merr)) return nil, Err.new(Err.ARG, tostring(merr))
end end
local P = m.attrs.POSITION.values local P = m.attrs.POSITION.values
local N = if o.normals == "attribute" and m.attrs.NORMAL then m.attrs.NORMAL.values else nil local N = if o.normals == "attribute" and m.attrs.NORMAL then (m.attrs.NORMAL :: Flatten.Attr).values else nil
local C = m.attrs.COLOR_0 local C = m.attrs.COLOR_0
local corners = m.corners local corners = m.corners
local nf = #corners // 3 local nf = #corners // 3
+6 -6
View File
@@ -579,7 +579,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
end end
local textureIndex: { [string]: number } = {} local textureIndex: { [string]: number } = {}
local WRAP = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } local WRAP: { [string]: string } = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" }
-- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform)
local function textureRef(shader: Prim): Types.TextureRef? local function textureRef(shader: Prim): Types.TextureRef?
if shaderId(shader) ~= "UsdUVTexture" then if shaderId(shader) ~= "UsdUVTexture" then
@@ -1012,7 +1012,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
local cnt0 = counts[f + 1] local cnt0 = counts[f + 1]
if cnt0 >= 3 and not hole[f] then if cnt0 >= 3 and not hole[f] then
local base = faceStart[f + 1] local base = faceStart[f + 1]
local verts = table.create(cnt0) local verts = table.create(cnt0) :: { number }
for k = 0, cnt0 - 1 do for k = 0, cnt0 - 1 do
local corner = base + k local corner = base + k
local point = indices[corner + 1] local point = indices[corner + 1]
@@ -1027,7 +1027,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
verts[k + 1] = v verts[k + 1] = v
end end
if leftHanded then if leftHanded then
local r = table.create(cnt0) local r = table.create(cnt0) :: { number }
for k = 1, cnt0 do for k = 1, cnt0 do
r[k] = verts[cnt0 - k + 1] r[k] = verts[cnt0 - k + 1]
end end
@@ -1267,9 +1267,9 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
buffer.writef32(ro.data, ((k - 1) * 4 + c) * 4, R[c + 1]) buffer.writef32(ro.data, ((k - 1) * 4 + c) * 4, R[c + 1])
end end
end end
table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" }) table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" } :: Types.Channel)
table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" }) table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" } :: Types.Channel)
table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" }) table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" } :: Types.Channel)
local T, R, S = decompose(localMatrix(ops, times[1])) local T, R, S = decompose(localMatrix(ops, times[1]))
n.translation, n.rotation, n.scale = T, R, S n.translation, n.rotation, n.scale = T, R, S
elseif #ops > 0 then elseif #ops > 0 then
+5 -5
View File
@@ -501,7 +501,7 @@ local function parser(s: string, maxBytes: number)
-- time samples: { time: value, ... } -- time samples: { time: value, ... }
local function samples(i: number): ({ times: { number }, values: { Value } }, number) local function samples(i: number): ({ times: { number }, values: { Value } }, number)
local times, values = {}, {} local times: { number }, values: { Value } = {}, {}
i = expect(i, "{") i = expect(i, "{")
while true do while true do
i = ws(i) i = ws(i)
@@ -523,7 +523,7 @@ local function parser(s: string, maxBytes: number)
i = expect(i, ":") i = expect(i, ":")
local v local v
v, i = value(i) v, i = value(i)
table.insert(times, t) table.insert(times, t :: number) -- fail() threw on nil
table.insert(values, v) table.insert(values, v)
end end
return { times = times, values = values }, i return { times = times, values = values }, i
@@ -664,7 +664,7 @@ local function parser(s: string, maxBytes: number)
end end
local prop = p.props[name :: string] local prop = p.props[name :: string]
if not prop then if not prop then
prop = { name = name :: string, rel = isRel } prop = { name = name :: string, rel = isRel } :: Prop
p.props[name :: string] = prop p.props[name :: string] = prop
table.insert(p.order, name :: string) table.insert(p.order, name :: string)
end end
@@ -806,8 +806,8 @@ function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?
if ok then if ok then
return res, nil, nil return res, nil, nil
end end
if type(res) == "table" and res.usda then if type(res) == "table" and (res :: any).usda then
return nil, res.usda, math.max((res.at or 1) - 1, 0) return nil, (res :: any).usda, math.max(((res :: any).at or 1) - 1, 0)
end end
return nil, "parse error: " .. tostring(res), nil return nil, "parse error: " .. tostring(res), nil
end end
+14 -14
View File
@@ -14,7 +14,7 @@ local Types = require("@formats/Types")
local Write = {} local Write = {}
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" } local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" }
local RAD = 180 / math.pi local RAD = 180 / math.pi
export type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? } export type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? }
@@ -79,7 +79,7 @@ local function values(acc: Types.Accessor?): ({ number }?, number)
return nil, 0 return nil, 0
end end
local n, c = acc.count, acc.components local n, c = acc.count, acc.components
local out = table.create(n * c) local out = table.create(n * c) :: { number }
for i = 0, n - 1 do for i = 0, n - 1 do
for k = 0, c - 1 do for k = 0, c - 1 do
out[i * c + k + 1] = get(i, k) out[i * c + k + 1] = get(i, k)
@@ -123,14 +123,14 @@ type Merged = {
local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?)
local idx: { number } local idx: { number }
if p.indices then if p.indices then
idx = (values(p.indices)) or {} idx = (values(p.indices)) or {} :: { number }
else else
idx = table.create(nverts) idx = table.create(nverts) :: { number }
for i = 1, nverts do for i = 1, nverts do
idx[i] = i - 1 idx[i] = i - 1
end end
end end
local counts, out = {}, {} local counts: { number }, out: { number } = {}, {}
local mode = p.mode local mode = p.mode
if mode == "triangles" or mode == nil then if mode == "triangles" or mode == nil then
for k = 1, #idx - 2, 3 do for k = 1, #idx - 2, 3 do
@@ -180,7 +180,7 @@ end
local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged?
local prims: { Types.Primitive } = {} local prims: { Types.Primitive } = {}
for _, p in mesh.primitives do for _, p in mesh.primitives do
if p.attributes and p.attributes.POSITION and p.attributes.POSITION.components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then if p.attributes and p.attributes.POSITION and (p.attributes.POSITION :: Types.Accessor).components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then
table.insert(prims, p) table.insert(prims, p)
else else
notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1 notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1
@@ -318,7 +318,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root")
-- texture files -- texture files
local base = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" local base: string = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model"
local texFile: { [number]: string } = {} local texFile: { [number]: string } = {}
for i, tex in scene.textures or {} do for i, tex in scene.textures or {} do
local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil
@@ -340,7 +340,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
-- animation: per node, per path -> { times, values (components) } -- animation: per node, per path -> { times, values (components) }
type Track = { times: { number }, vals: { number }, comps: number } type Track = { times: { number }, vals: { number }, comps: number }
local tracks: { [number]: { [string]: Track } } = {} local tracks: { [number]: { [string]: Track? } } = {}
local tcps = 24 local tcps = 24
local tMin, tMax = math.huge, -math.huge local tMin, tMax = math.huge, -math.huge
for _, anim in scene.animations or {} do for _, anim in scene.animations or {} do
@@ -399,7 +399,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
-- xform ops of a node (+ its animation) -- xform ops of a node (+ its animation)
local function xform(depth: number, ni: number, n: Types.Node) local function xform(depth: number, ni: number, n: Types.Node)
local tr = tracks[ni] local tr: { [string]: Track? }? = tracks[ni]
local order: { string } = {} local order: { string } = {}
local function samples(track: Track, f: (vals: { number }, at: number) -> string): string local function samples(track: Track, f: (vals: { number }, at: number) -> string): string
local parts = {} local parts = {}
@@ -438,7 +438,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 })) line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 }))
end end
if tr and tr.translation then if tr and tr.translation then
line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation, vec3)) line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation :: Track, vec3))
end end
table.insert(order, '"xformOp:translate"') table.insert(order, '"xformOp:translate"')
end end
@@ -447,7 +447,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
line(depth, "quatf xformOp:orient = " .. quat(r, 0)) line(depth, "quatf xformOp:orient = " .. quat(r, 0))
end end
if tr and tr.rotation then if tr and tr.rotation then
line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation, quat)) line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation :: Track, quat))
end end
table.insert(order, '"xformOp:orient"') table.insert(order, '"xformOp:orient"')
end end
@@ -456,7 +456,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 })) line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 }))
end end
if tr and tr.scale then if tr and tr.scale then
line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale, vec3)) line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale :: Track, vec3))
end end
table.insert(order, '"xformOp:scale"') table.insert(order, '"xformOp:scale"')
end end
@@ -570,7 +570,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
line(depth, "float verticalAperture = " .. fmt(vap)) line(depth, "float verticalAperture = " .. fmt(vap))
end end
local LIGHT_TYPE = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" } local LIGHT_TYPE: { [string]: string } = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" }
local function lightBody(depth: number, l: Types.Light) local function lightBody(depth: number, l: Types.Light)
local c = l.color or { 1, 1, 1 } local c = l.color or { 1, 1, 1 }
line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 })) line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 }))
@@ -808,7 +808,7 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat
stSource = path .. "/" .. tn.name .. "_Transform.outputs:result" stSource = path .. "/" .. tn.name .. "_Transform.outputs:result"
end end
local tex = scene.textures[ref.texture] local tex = scene.textures[ref.texture]
local sampler = tex and tex.sampler or {} local sampler: Types.Sampler = tex and tex.sampler or {}
table.insert(out, "") table.insert(out, "")
line(d, 'def Shader "' .. tn.name .. '"') line(d, 'def Shader "' .. tn.name .. '"')
line(d, "{") line(d, "{")
+4 -4
View File
@@ -107,11 +107,11 @@ local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buf
end end
end end
local v: any = nil local v: any = nil
if opts and type(opts.files) == "table" then if opts and type((opts :: DecodeOptions).files) == "table" then
v = opts.files[u] v = ((opts :: DecodeOptions).files :: { [string]: any })[u]
end end
if v == nil and opts and type(opts.resolve) == "function" then if v == nil and opts and type((opts :: DecodeOptions).resolve) == "function" then
local ok, res = pcall(opts.resolve, u) local ok, res = pcall((opts :: DecodeOptions).resolve :: (uri: string) -> any, u)
v = if ok then res else nil v = if ok then res else nil
end end
if type(v) == "string" then if type(v) == "string" then
+4 -4
View File
@@ -275,7 +275,7 @@ local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?)
if n < 1024 then if n < 1024 then
return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at) return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at)
end end
local pal = table.create(255) local pal = table.create(255) :: { { number } }
for i = 1, 255 do for i = 1, 255 do
pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() } pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() }
end end
@@ -310,7 +310,7 @@ local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?)
if c.err or nc < 0 or nc * 4 > c:remaining() then if c.err or nc < 0 or nc * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at) return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at)
end end
local children = table.create(nc) local children = table.create(nc) :: { number }
for k = 1, nc do for k = 1, nc do
children[k] = c:i32le() children[k] = c:i32le()
end end
@@ -625,7 +625,7 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid") return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid")
end end
end end
local meta = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {} local meta: any = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {}
local w = Bytes.writer(65536) local w = Bytes.writer(65536)
w:string("VOX ") w:string("VOX ")
w:u32le(version) w:u32le(version)
@@ -675,7 +675,7 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local failure: string? = nil local failure: string? = nil
local function shape(model: number, vx: any?): number local function shape(model: number, vx: any?): number
local id = alloc() local id = alloc()
local ms = {} local ms: { { model: number, attributes: Dict? } } = {}
local saved = vx and vx.shape local saved = vx and vx.shape
if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then
for _, sm in saved.models do for _, sm in saved.models do
+2 -2
View File
@@ -153,7 +153,7 @@ function Render.timeline(midi: Types.Midi): Timeline
end end
return a[3] < b[3] return a[3] < b[3]
end) end)
local tl: Timeline = { time = table.create(#items), status = table.create(#items), d1 = table.create(#items), d2 = table.create(#items), length = Render.length(midi) } local tl: Timeline = { time = table.create(#items) :: { number }, status = table.create(#items) :: { number }, d1 = table.create(#items) :: { number }, d2 = table.create(#items) :: { number }, length = Render.length(midi) }
for i, it in items do for i, it in items do
tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128
end end
@@ -192,7 +192,7 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?
local tail = o.tail or 1 local tail = o.tail or 1
local frames = math.max(0, math.ceil((tl.length + tail) * rate)) local frames = math.max(0, math.ceil((tl.length + tail) * rate))
local nev = #tl.time local nev = #tl.time
local evFrame = table.create(nev) local evFrame: { number } = table.create(nev) :: { number }
for i = 1, nev do for i = 1, nev do
evFrame[i] = math.floor(tl.time[i] * rate + 0.5) evFrame[i] = math.floor(tl.time[i] * rate + 0.5)
end end
+2 -2
View File
@@ -25,7 +25,7 @@ export type WriteOptions = {
} }
local function bytesOf(b: buffer, p: number, n: number): { number } local function bytesOf(b: buffer, p: number, n: number): { number }
local t: { number } = table.create(n) local t: { number } = table.create(n) :: { number }
for i = 0, n - 1 do for i = 0, n - 1 do
t[i + 1] = readu8(b, p + i) t[i + 1] = readu8(b, p + i)
end end
@@ -309,7 +309,7 @@ function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?)
end end
last = ev.tick last = ev.tick
end end
local list = events local list: { any } = events
if not sorted then if not sorted then
list = table.clone(events) list = table.clone(events)
local order: { [any]: number } = {} local order: { [any]: number } = {}
+2 -1
View File
@@ -204,7 +204,8 @@ function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
vol = math.min(pr:u8(), 64) + 1 vol = math.min(pr:u8(), 64) + 1
end end
if bit32.band(what, 0x80) ~= 0 then if bit32.band(what, 0x80) ~= 0 then
cmd, info = pr:u8(), pr:u8() cmd = pr:u8()
info = pr:u8()
if cmd > 26 then if cmd > 26 then
cmd, info = 0, 0 cmd, info = 0, 0
end end
+5 -1
View File
@@ -149,7 +149,11 @@ function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
param = pr:u8() param = pr:u8()
end end
else else
note, ins, vol, fx, param = b, pr:u8(), pr:u8(), pr:u8(), pr:u8() note = b
ins = pr:u8()
vol = pr:u8()
fx = pr:u8()
param = pr:u8()
end end
if pr.err then if pr.err then
break -- a short pattern: the rest stays empty break -- a short pattern: the rest stays empty
+12 -12
View File
@@ -13,9 +13,9 @@ local floor, clamp = math.floor, math.clamp
local K = {} local K = {}
-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8 -- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8
K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } :: { [string]: number }
K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } :: { [string]: number }
K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } :: { [string]: number }
local function rd(b: buffer, o: number, kind: number): number local function rd(b: buffer, o: number, kind: number): number
if kind == 1 then if kind == 1 then
@@ -74,20 +74,20 @@ local function luma(r: number, g: number, b: number, depth: number): number
end end
function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number)
local sd, dd = DEPTH[sf], DEPTH[df] local sd, dd = DEPTH[sf] :: number, DEPTH[df] :: number
local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1 local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1
local toGray = df == 5 or df == 6 or df == 7 local toGray = df == 5 or df == 6 or df == 7
for i = 0, n - 1 do for i = 0, n - 1 do
local r, g, b, a local r: number, g: number, b: number, a: number
if sf == 1 then if sf == 1 then
local o = i * 4 local o = i * 4
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) :: number
elseif sf == 2 then elseif sf == 2 then
local o = i * 8 local o = i * 8
r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6) r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6) :: number
elseif sf == 3 then elseif sf == 3 then
local o = i * 16 local o = i * 16
r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12) r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12) :: number
elseif sf == 4 then elseif sf == 4 then
local o = i * 3 local o = i * 3
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255 r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255
@@ -99,7 +99,7 @@ function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number)
r, g, b, a = v, v, v, 65535 r, g, b, a = v, v, v, 65535
elseif sf == 7 then elseif sf == 7 then
local v = readu8(src, i * 2) local v = readu8(src, i * 2)
r, g, b, a = v, v, v, readu8(src, i * 2 + 1) r, g, b, a = v, v, v, readu8(src, i * 2 + 1) :: number
else else
r, g, b, a = 255, 255, 255, readu8(src, i) r, g, b, a = 255, 255, 255, readu8(src, i)
end end
@@ -118,7 +118,7 @@ function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number)
elseif df == 8 then elseif df == 8 then
writeu8(dst, i, depthConv(a, sd, 8)) writeu8(dst, i, depthConv(a, sd, 8))
else else
r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd) r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd) :: number
if df == 1 then if df == 1 then
local o = i * 4 local o = i * 4
writeu8(dst, o, r) writeu8(dst, o, r)
@@ -281,7 +281,7 @@ function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs
local filterscale = math.max(scale, 1) local filterscale = math.max(scale, 1)
local support = support0 * filterscale local support = support0 * filterscale
local ss = 1 / filterscale local ss = 1 / filterscale
local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize) local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize) :: { { number } }
for xx = 0, outSize - 1 do for xx = 0, outSize - 1 do
local center = (xx + 0.5) * scale local center = (xx + 0.5) * scale
local xmin = math.max(0, trunc(center - support + 0.5)) local xmin = math.max(0, trunc(center - support + 0.5))
@@ -311,7 +311,7 @@ function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: num
-- 8-bit: Pillow's 22-bit fixed-point coefficients -- 8-bit: Pillow's 22-bit fixed-point coefficients
local iw: { { number } } = weights local iw: { { number } } = weights
if fixed then if fixed then
iw = table.create(outN) iw = table.create(outN) :: { { number } }
for i = 1, outN do for i = 1, outN do
local src0 = weights[i] local src0 = weights[i]
local t = table.create(#src0, 0) local t = table.create(#src0, 0)
+27 -27
View File
@@ -57,16 +57,16 @@ local function check(img: any): (boolean?, Err.Err?)
if buffer.len(img.pixels) < need then if buffer.len(img.pixels) < need then
return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format) return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format)
end end
return true return true, nil
end end
ImageOps.check = check ImageOps.check = check
local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?) local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?)
local max = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS local max: number = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS
if w * h > max then if w * h > max then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max)) return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max))
end end
return true return true, nil
end end
-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames -- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames
@@ -93,7 +93,7 @@ function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?)
if not ok then if not ok then
return nil, e return nil, e
end end
return Types.Image.new(w, h, fmt :: any) return Types.Image.new(w, h, fmt :: any), nil
end end
-- copy(img) -> a deep copy of the pixels (frames are shared) -- copy(img) -> a deep copy of the pixels (frames are shared)
@@ -105,7 +105,7 @@ function ImageOps.copy(img: Image): (Image?, Err.Err?)
local out = like(img, img.width, img.height) local out = like(img, img.width, img.height)
buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels)) buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels))
out.frames = img.frames out.frames = img.frames
return out return out, nil
end end
-- ------------------------------------------------------------------------------------------------ convert -- ------------------------------------------------------------------------------------------------ convert
@@ -127,7 +127,7 @@ function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?)
local rgba = like(img, w, h, "rgba8") local rgba = like(img, w, h, "rgba8")
K.yuvToRgba(img.pixels, w, h, rgba.pixels) K.yuvToRgba(img.pixels, w, h, rgba.pixels)
if format == "rgba8" then if format == "rgba8" then
return rgba return rgba, nil
end end
src = rgba src = rgba
end end
@@ -139,10 +139,10 @@ function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?)
K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h) K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h)
end end
K.rgbaToYuv(rgba.pixels, w, h, out.pixels) K.rgbaToYuv(rgba.pixels, w, h, out.pixels)
return out return out, nil
end end
K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h) K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h)
return out return out, nil
end end
-- ops on yuv420p run on rgba8 and convert back -- ops on yuv420p run on rgba8 and convert back
@@ -159,7 +159,7 @@ local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, E
end end
-- ------------------------------------------------------------------------------------------------ geometry -- ------------------------------------------------------------------------------------------------ geometry
local ALPHA_CH = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } local ALPHA_CH: { [string]: number } = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 }
-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty) -- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty)
function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?) function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?)
@@ -179,7 +179,7 @@ function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number):
local bpp = Types.BPP[im.format] :: number local bpp = Types.BPP[im.format] :: number
local out = like(im, x1 - x0, y1 - y0) local out = like(im, x1 - x0, y1 - y0)
K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp) K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp)
return out return out, nil
end) end)
end end
@@ -195,7 +195,7 @@ function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?)
return viaRgba(img, function(im: Image): (Image?, Err.Err?) return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local out = like(im, im.width, im.height) local out = like(im, im.width, im.height)
K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h") K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h")
return out return out, nil
end) end)
end end
@@ -216,7 +216,7 @@ function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?)
local swap = t ~= 2 local swap = t ~= 2
local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height) local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height)
K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t) K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t)
return out return out, nil
end) end)
end end
@@ -245,7 +245,7 @@ function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts
local out = like(im, w, h) local out = like(im, w, h)
if f == "nearest" then if f == "nearest" then
K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h) K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h)
return out return out, nil
end end
local kind, ch = K.KIND[fmt], K.CHANNELS[fmt] local kind, ch = K.KIND[fmt], K.CHANNELS[fmt]
local src, sw, sh = im.pixels, im.width, im.height local src, sw, sh = im.pixels, im.width, im.height
@@ -264,14 +264,14 @@ function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts
K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false) K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false)
elseif src == im.pixels or (w == im.width and alpha) then elseif src == im.pixels or (w == im.width and alpha) then
buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp) buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp)
return out return out, nil
else else
out.pixels = src out.pixels = src
end end
if alpha then if alpha then
K.premultiply(out.pixels, w * h, alpha, kind, true) K.premultiply(out.pixels, w * h, alpha, kind, true)
end end
return out return out, nil
end) end)
end end
@@ -333,12 +333,12 @@ function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?,
if alpha then if alpha then
K.premultiply(out.pixels, nw * nh, alpha, kind, true) K.premultiply(out.pixels, nw * nh, alpha, kind, true)
end end
return out return out, nil
end) end)
end end
-- ------------------------------------------------------------------------------------------------ compositing -- ------------------------------------------------------------------------------------------------ compositing
local RGBA = { rgba8 = true, rgba16 = true, rgbaf32 = true } local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true }
export type BlitOptions = { blend: ("over" | "source")?, opacity: number? } export type BlitOptions = { blend: ("over" | "source")?, opacity: number? }
@@ -371,7 +371,7 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO
local w = math.min(src.width - sx, dst.width - dx) local w = math.min(src.width - sx, dst.width - dx)
local h = math.min(src.height - sy, dst.height - dy) local h = math.min(src.height - sy, dst.height - dy)
if w <= 0 or h <= 0 then if w <= 0 or h <= 0 then
return dst return dst, nil
end end
if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then
-- work on an rgba copy of the region, then write it back in dst's format -- work on an rgba copy of the region, then write it back in dst's format
@@ -387,7 +387,7 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO
local back = ImageOps.convert(work, dst.format) :: Image local back = ImageOps.convert(work, dst.format) :: Image
K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number) K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number)
end end
return dst return dst, nil
end end
local s = src local s = src
if src.format ~= dst.format then if src.format ~= dst.format then
@@ -400,7 +400,7 @@ function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitO
else else
K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format]) K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format])
end end
return dst return dst, nil
end end
-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it -- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it
@@ -423,7 +423,7 @@ local function premul(img: Image, un: boolean): (Image?, Err.Err?)
if ch then if ch then
K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un) K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un)
end end
return out return out, nil
end end
-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged) -- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged)
@@ -435,7 +435,7 @@ function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?)
end end
-- ------------------------------------------------------------------------------------------------ pixels -- ------------------------------------------------------------------------------------------------ pixels
local MAXV = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } local MAXV: { [string]: number } = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 }
-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b; -- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b;
-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range. -- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range.
@@ -543,7 +543,7 @@ function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: numbe
else else
wu8(px, i, q(al)) wu8(px, i, q(al))
end end
return true return true, nil
end end
-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel) -- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel)
@@ -567,7 +567,7 @@ function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?):
buffer.copy(img.pixels, filled, img.pixels, 0, c) buffer.copy(img.pixels, filled, img.pixels, 0, c)
filled += c filled += c
end end
return img return img, nil
end end
-- ------------------------------------------------------------------------------------------------ animation -- ------------------------------------------------------------------------------------------------ animation
@@ -602,7 +602,7 @@ function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
end end
local frames = img.frames local frames = img.frames
if type(frames) ~= "table" or #frames == 0 then if type(frames) ~= "table" or #frames == 0 then
return { img } return { img }, nil
end end
local fmt = if RGBA[img.format] then img.format else "rgba8" local fmt = if RGBA[img.format] then img.format else "rgba8"
local canvas = Types.Image.new(img.width, img.height, fmt :: any) local canvas = Types.Image.new(img.width, img.height, fmt :: any)
@@ -647,7 +647,7 @@ function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
canvas.pixels = saved canvas.pixels = saved
end end
end end
return out return out, nil
end end
-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0, -- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0,
@@ -683,7 +683,7 @@ function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?):
buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels)) buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels))
out.frames = frames :: any out.frames = frames :: any
out.loops = 0 out.loops = 0
return out return out, nil
end end
return ImageOps return ImageOps
+1 -1
View File
@@ -97,7 +97,7 @@ function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number
buffer.copy(nb, 0, b, 0, cap * per) buffer.copy(nb, 0, b, 0, cap * per)
return nb return nb
end end
pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) :: buffer
cap = ncap cap = ncap
end end
corner[d + 1] = slice + 1 corner[d + 1] = slice + 1
+3 -3
View File
@@ -272,7 +272,7 @@ function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Prim
table.insert(out, readu32(ib, (at + a + 1) * 4)) table.insert(out, readu32(ib, (at + a + 1) * 4))
end end
else else
local poly = table.create(k) local poly = table.create(k) :: { number }
for a = 0, k - 1 do for a = 0, k - 1 do
poly[a + 1] = readu32(ib, (at + a) * 4) poly[a + 1] = readu32(ib, (at + a) * 4)
end end
@@ -856,7 +856,7 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string?
end end
return out, nil return out, nil
end end
local all = groups[0] or {} local all: { Primitive } = groups[0] or {}
local first = all[1] local first = all[1]
return concat(all, first and first.material), nil return concat(all, first and first.material), nil
end end
@@ -1025,7 +1025,7 @@ function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scal
local col = buffer.create(nv * (if srgb then 4 else 16)) local col = buffer.create(nv * (if srgb then 4 else 16))
local lut: { { number } } = {} local lut: { { number } } = {}
for i = 1, 255 do for i = 1, 255 do
local c = pal[i] or { 255, 255, 255, 255 } local c: { number } = pal[i] or { 255, 255, 255, 255 }
if srgb then if srgb then
lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 } lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 }
else else
+1 -1
View File
@@ -86,7 +86,7 @@ end
-- ------------------------------------------------------------------------------------------------ decode -- ------------------------------------------------------------------------------------------------ decode
local function parsePls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result local function parsePls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result
local res: Result = { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} } local res: Result = { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} }
local files, titles, lengths = {}, {}, {} local files: { [number]: string }, titles: { [number]: string }, lengths: { [number]: string } = {}, {}, {}
local declared = nil local declared = nil
for _, line in ls do for _, line in ls do
local l = Text.trim(line) local l = Text.trim(line)
+1 -1
View File
@@ -121,7 +121,7 @@ function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, E
for _, list in elements(root, "trackList") do for _, list in elements(root, "trackList") do
for i, track in elements(list, "track") do for i, track in elements(list, "track") do
local tbase, tscheme = withXmlBase(track, pbase, pscheme) local tbase, tscheme = withXmlBase(track, pbase, pscheme)
local locs = {} local locs: { string } = {}
for _, l in elements(track, "location") do for _, l in elements(track, "location") do
local s = trim(Xml.text(l)) local s = trim(Xml.text(l))
if s ~= "" then if s ~= "" then
+1 -1
View File
@@ -190,7 +190,7 @@ function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, E
stylesName = name stylesName = name
section = "styles" section = "styles"
elseif section ~= "script info" and section ~= "events" then elseif section ~= "script info" and section ~= "events" then
table.insert(sections, { name = name, lines = {} }) table.insert(sections, { name = name, lines = {} :: { string } })
end end
continue continue
end end
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more