ws-tex: image/xbm + image/xpm (read + write)
XBM: X11 / X10 arrays, hex / decimal / octal, hotspot; xbmtopbm reference (netpbm, ImageMagick, Pillow files). XPM: XPM 3 + XPM 2, c / g / g4 / m keys, hex depths, None, CSS / X11 names + grey0..100 (image/xpm/Names); ImageMagick reference.
This commit is contained in:
1 parent
403a4d6f31
commit
ef460955d4
10 files changed
+707
No files matched your search
@@ -22,6 +22,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` |
|
||||
| image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` |
|
||||
| image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` |
|
||||
| image | xbm | .xbm .bm | yes | yes | depths: 1 | `tests/image/xbm.luau` |
|
||||
| image | xpm | .xpm .pm | yes | yes | alpha: true, palette: true, depths: 8 | `tests/image/xpm.luau` |
|
||||
| audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` |
|
||||
| audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` |
|
||||
| audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` |
|
||||
|
||||
@@ -218,6 +218,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/webp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xbm",
|
||||
category = "image",
|
||||
path = "image/xbm",
|
||||
extensions = { "xbm", "bm" },
|
||||
mime = { "image/x-xbitmap", "image/x-xbm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, depths = { 1 } },
|
||||
load = function()
|
||||
return require("@formats/image/xbm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xpm",
|
||||
category = "image",
|
||||
path = "image/xpm",
|
||||
extensions = { "xpm", "pm" },
|
||||
mime = { "image/x-xpixmap", "image/x-xpm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } },
|
||||
load = function()
|
||||
return require("@formats/image/xpm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "aac",
|
||||
category = "audio",
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
--!strict
|
||||
-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height
|
||||
-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black,
|
||||
-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below
|
||||
-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image").
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xbm = {
|
||||
name = "xbm",
|
||||
category = "image",
|
||||
extensions = { "xbm", "bm" },
|
||||
mime = { "image/x-xbitmap", "image/x-xbm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, depths = { 1 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
transparent: boolean?, -- clear bits transparent (default false: white)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
name: string?, -- the C identifier prefix (default "image")
|
||||
threshold: number?, -- luminance below this is black (default 128)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xbm.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 256, true)
|
||||
if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then
|
||||
return 0.9
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Xbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local n = r.limit - r.base
|
||||
if n > 2 ^ 26 then
|
||||
return nil, Err.new(Err.LIMIT, "file too large")
|
||||
end
|
||||
local s = buffer.readstring(r.buf, r.base, n)
|
||||
local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)"))
|
||||
local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)"))
|
||||
if not w or not h or w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "missing width / height defines")
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local brace = string.find(s, "{", 1, true)
|
||||
if not brace then
|
||||
return nil, Err.new(Err.CORRUPT, "missing bits array")
|
||||
end
|
||||
local decl = string.sub(s, 1, brace)
|
||||
local short = string.find(decl, "short", 1, true) ~= nil
|
||||
local unit = if short then 16 else 8
|
||||
local per = (w + unit - 1) // unit
|
||||
local want = per * h
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local clear = if opts and opts.transparent then 0x00FFFFFF else 0xFFFFFFFF
|
||||
local got = 0
|
||||
local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ")
|
||||
for tok in string.gmatch(body, "[%w]+") do
|
||||
if got >= want then
|
||||
break
|
||||
end
|
||||
local v
|
||||
if string.match(tok, "^0[xX]%x+$") then
|
||||
v = tonumber(string.sub(tok, 3), 16)
|
||||
elseif string.match(tok, "^0%d+$") then
|
||||
v = tonumber(tok, 8)
|
||||
elseif string.match(tok, "^%d+$") then
|
||||
v = tonumber(tok)
|
||||
end
|
||||
if v then
|
||||
local y, cx = got // per, (got % per) * unit
|
||||
for k = 0, unit - 1 do
|
||||
local x = cx + k
|
||||
if x < w then
|
||||
buffer.writeu32(px, (y * w + x) * 4, if bit32.band(bit32.rshift(v, k), 1) == 1 then 0xFF000000 else clear)
|
||||
end
|
||||
end
|
||||
got += 1
|
||||
end
|
||||
end
|
||||
if got < want then
|
||||
for i = got * unit, want * unit - 1 do
|
||||
local y, x = i // (per * unit), i % (per * unit)
|
||||
if x < w then
|
||||
buffer.writeu32(px, (y * w + x) * 4, clear)
|
||||
end
|
||||
end
|
||||
img.meta.truncated = true
|
||||
end
|
||||
local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)"))
|
||||
local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)"))
|
||||
if hx and hy then
|
||||
img.meta.hotspot = { x = hx, y = hy }
|
||||
end
|
||||
local name = string.match(s, "#define%s+([%w_]-)_?width%s")
|
||||
img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
local name = opts and opts.name or "image"
|
||||
if not string.match(name, "^[%a_][%w_]*$") then
|
||||
return nil, Err.new(Err.ARG, "name must be a C identifier")
|
||||
end
|
||||
local th = opts and opts.threshold or 128
|
||||
local px = img.pixels
|
||||
local parts = {
|
||||
string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h),
|
||||
}
|
||||
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
|
||||
if hs then
|
||||
table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y))
|
||||
end
|
||||
table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name))
|
||||
local per = (w + 7) // 8
|
||||
local bytes = {}
|
||||
for y = 0, h - 1 do
|
||||
for bx = 0, per - 1 do
|
||||
local v = 0
|
||||
for k = 0, 7 do
|
||||
local x = bx * 8 + k
|
||||
if x < w then
|
||||
local o = (y * w + x) * 4
|
||||
local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2)
|
||||
if lum < th and buffer.readu8(px, o + 3) >= 128 then
|
||||
v += bit32.lshift(1, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.insert(bytes, string.format("0x%02x", v))
|
||||
end
|
||||
end
|
||||
for i = 1, #bytes, 12 do
|
||||
table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (if i + 11 < #bytes then ",\n" else " };\n"))
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
return Xbm
|
||||
@@ -0,0 +1,57 @@
|
||||
--!strict
|
||||
-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's
|
||||
-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100.
|
||||
-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil.
|
||||
local Names = {}
|
||||
|
||||
local HEX: { [string]: number } = {
|
||||
aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF,
|
||||
beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF,
|
||||
blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00,
|
||||
chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C,
|
||||
cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9,
|
||||
darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F,
|
||||
darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F,
|
||||
darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1,
|
||||
darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969,
|
||||
dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF,
|
||||
gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE,
|
||||
green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4,
|
||||
indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA,
|
||||
lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080,
|
||||
lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90,
|
||||
lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA,
|
||||
lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0,
|
||||
lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060,
|
||||
mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB,
|
||||
mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC,
|
||||
mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5,
|
||||
navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23,
|
||||
orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98,
|
||||
paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F,
|
||||
pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000,
|
||||
rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460,
|
||||
seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB,
|
||||
slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F,
|
||||
steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0,
|
||||
violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32,
|
||||
}
|
||||
|
||||
-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces)
|
||||
function Names.lookup(name: string): number?
|
||||
local v = HEX[name]
|
||||
if v then
|
||||
return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536
|
||||
end
|
||||
local n = string.match(name, "^gr[ae]y(%d+)$")
|
||||
if n then
|
||||
local k = tonumber(n) :: number
|
||||
if k <= 100 then
|
||||
local g = math.floor(k * 255 / 100 + 0.49)
|
||||
return g * 0x10101
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return Names
|
||||
@@ -0,0 +1,271 @@
|
||||
--!strict
|
||||
-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode:
|
||||
-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 /
|
||||
-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour
|
||||
-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in
|
||||
-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None,
|
||||
-- the fewest chars per pixel; opts.name (default "image").
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Names = require("@formats/image/xpm/Names")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xpm = {
|
||||
name = "xpm",
|
||||
category = "image",
|
||||
extensions = { "xpm", "pm" },
|
||||
mime = { "image/x-xpixmap", "image/x-xpm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
name: string?, -- the C identifier (default "image")
|
||||
}
|
||||
|
||||
-- the characters of pixel codes (printable ASCII without '"' and '\')
|
||||
local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xpm.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 64, true)
|
||||
if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- colour value -> rgba8 u32, or nil for an unknown name
|
||||
local function colour(v: string): number?
|
||||
local l = string.lower(v)
|
||||
if l == "none" or l == "transparent" then
|
||||
return 0
|
||||
end
|
||||
if string.sub(v, 1, 1) == "#" then
|
||||
local hex = string.sub(v, 2)
|
||||
local n = #hex
|
||||
if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then
|
||||
return nil
|
||||
end
|
||||
local k = n // 3
|
||||
local mx = 16 ^ k - 1
|
||||
local c = 0
|
||||
for i = 0, 2 do
|
||||
local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number
|
||||
c += math.floor(x * 255 / mx + 0.5) * 256 ^ i
|
||||
end
|
||||
return c + 0xFF000000
|
||||
end
|
||||
local rgb = Names.lookup(l)
|
||||
return if rgb then rgb + 0xFF000000 else nil
|
||||
end
|
||||
|
||||
-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2)
|
||||
local function strings(s: string): { string }
|
||||
local out = {}
|
||||
if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then
|
||||
local first = true
|
||||
for line in string.gmatch(s, "[^\n]+") do
|
||||
if first then
|
||||
first = false
|
||||
else
|
||||
table.insert(out, (string.gsub(line, "\r$", "")))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
local i, n = 1, #s
|
||||
while i <= n do
|
||||
local c = string.sub(s, i, i)
|
||||
if c == "/" and string.sub(s, i + 1, i + 1) == "*" then
|
||||
local e = string.find(s, "*/", i + 2, true)
|
||||
i = if e then e + 2 else n + 1
|
||||
elseif c == '"' then
|
||||
local parts = {}
|
||||
local j = i + 1
|
||||
while j <= n do
|
||||
local d = string.sub(s, j, j)
|
||||
if d == "\\" then
|
||||
table.insert(parts, string.sub(s, j + 1, j + 1))
|
||||
j += 2
|
||||
elseif d == '"' then
|
||||
break
|
||||
else
|
||||
local e = string.find(s, '["\\]', j)
|
||||
local stop = (e or n + 1) - 1
|
||||
table.insert(parts, string.sub(s, j, stop))
|
||||
j = stop + 1
|
||||
end
|
||||
end
|
||||
table.insert(out, table.concat(parts))
|
||||
i = j + 1
|
||||
else
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local KEYS = { c = true, m = true, g4 = true, g = true, s = true }
|
||||
|
||||
function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local n = r.limit - r.base
|
||||
if n > 2 ^ 27 then
|
||||
return nil, Err.new(Err.LIMIT, "file too large")
|
||||
end
|
||||
local list = strings(buffer.readstring(r.buf, r.base, n))
|
||||
if #list == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no XPM strings")
|
||||
end
|
||||
local vals: { number } = {}
|
||||
for tok in string.gmatch(list[1], "%S+") do
|
||||
table.insert(vals, tonumber(tok) or -1)
|
||||
end
|
||||
local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1
|
||||
if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad values line")
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels or nc > 2 ^ 24 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
if #list < 1 + nc then
|
||||
return nil, Err.new(Err.TRUNCATED, "colour table runs past the end")
|
||||
end
|
||||
local map: { [string]: number } = {}
|
||||
local unknown: { string } = {}
|
||||
local palette: { { number } } = {}
|
||||
for i = 1, nc do
|
||||
local line = list[1 + i]
|
||||
local code = string.sub(line, 1, cpp)
|
||||
local rest = string.sub(line, cpp + 1)
|
||||
local found: { [string]: string } = {}
|
||||
local key: string? = nil
|
||||
local acc = {}
|
||||
for tok in string.gmatch(rest, "%S+") do
|
||||
if KEYS[tok] and (key == nil or #acc > 0) then
|
||||
if key then
|
||||
found[key] = table.concat(acc, " ")
|
||||
end
|
||||
key, acc = tok, {}
|
||||
else
|
||||
table.insert(acc, tok)
|
||||
end
|
||||
end
|
||||
if key then
|
||||
found[key] = table.concat(acc, " ")
|
||||
end
|
||||
local v = found.c or found.g or found.g4 or found.m
|
||||
local c = if v then colour(v) else nil
|
||||
if v and not c then
|
||||
c = colour((string.gsub(v, " ", "")))
|
||||
end
|
||||
local cv: number = c or 0xFF000000
|
||||
if not c then
|
||||
table.insert(unknown, v or "")
|
||||
end
|
||||
c = cv
|
||||
map[code] = cv
|
||||
palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) }
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local truncated = false
|
||||
for y = 0, h - 1 do
|
||||
local row = list[2 + nc + y]
|
||||
if not row then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)]
|
||||
buffer.writeu32(px, (y * w + x) * 4, c or 0)
|
||||
end
|
||||
end
|
||||
if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then
|
||||
img.meta.hotspot = { x = vals[5], y = vals[6] }
|
||||
end
|
||||
if #unknown > 0 then
|
||||
img.meta.unknownColours = unknown
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.palette = palette
|
||||
img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
local name = opts and opts.name or "image"
|
||||
if not string.match(name, "^[%a_][%w_]*$") then
|
||||
return nil, Err.new(Err.ARG, "name must be a C identifier")
|
||||
end
|
||||
local px = img.pixels
|
||||
local index: { [number]: number } = {}
|
||||
local order: { number } = {}
|
||||
local keys = table.create(w * h, 0)
|
||||
for i = 0, w * h - 1 do
|
||||
local v = buffer.readu32(px, i * 4)
|
||||
local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF)
|
||||
if not index[k] then
|
||||
table.insert(order, k)
|
||||
index[k] = #order
|
||||
end
|
||||
keys[i + 1] = index[k]
|
||||
end
|
||||
local nchars = #CODE_CHARS
|
||||
local cpp = 1
|
||||
while nchars ^ cpp < #order do
|
||||
cpp += 1
|
||||
end
|
||||
local codes: { string } = {}
|
||||
for i = 1, #order do
|
||||
local v, s = i - 1, ""
|
||||
for _ = 1, cpp do
|
||||
local d = v % nchars
|
||||
s ..= string.sub(CODE_CHARS, d + 1, d + 1)
|
||||
v //= nchars
|
||||
end
|
||||
codes[i] = s
|
||||
end
|
||||
local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) }
|
||||
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
|
||||
if hs then
|
||||
table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y))
|
||||
else
|
||||
table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp))
|
||||
end
|
||||
for i, k in order do
|
||||
local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16))
|
||||
table.insert(parts, string.format('"%s c %s",\n', codes[i], col))
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local row = table.create(w, "")
|
||||
for x = 0, w - 1 do
|
||||
row[x + 1] = codes[keys[y * w + x + 1]]
|
||||
end
|
||||
table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n"))
|
||||
end
|
||||
table.insert(parts, "};\n")
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
return Xpm
|
||||
@@ -0,0 +1,43 @@
|
||||
-- image/xbm tests: files from netpbm / ImageMagick / Pillow and hand-written ones against the reference decode
|
||||
-- (xbmtopbm), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/xbm.py.
|
||||
local T = require("@tests/T")
|
||||
local Xbm = require("@formats/image/xbm")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/xbm")
|
||||
|
||||
local t = T.suite("xbm")
|
||||
t:eq(Xbm.name, "xbm", "name")
|
||||
t:check(Xbm.caps.decode and Xbm.caps.encode, "caps")
|
||||
|
||||
t:note("%d files match the reference", R.decodes(t, Xbm, Fx.cases))
|
||||
t:note("%d of our files read back by it", R.decodes(t, Xbm, Fx.ours))
|
||||
for _, c in Fx.cases do
|
||||
R.roundTrip(t, Xbm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
if c.hotspot then
|
||||
local img = Xbm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
|
||||
end
|
||||
end
|
||||
do
|
||||
-- decimal and octal values, the X10 short arrays
|
||||
local img = Xbm.decode(Bytes.reader(buffer.fromstring("#define a_width 9\n#define a_height 1\nstatic char a_bits[] = { 1, 0400 };"))) :: any
|
||||
t:eq(buffer.readu32(img.pixels, 0), 0xFF000000, "decimal: pixel 0 black")
|
||||
t:eq(buffer.readu32(img.pixels, 4), 0xFFFFFFFF, "decimal: pixel 1 white")
|
||||
local x10 = Xbm.decode(Bytes.reader(buffer.fromstring("#define b_width 17\n#define b_height 1\nstatic short b_bits[] = { 0x8001, 0x0001 };"))) :: any
|
||||
t:eq(buffer.readu32(x10.pixels, 15 * 4), 0xFF000000, "x10: bit 15")
|
||||
t:eq(buffer.readu32(x10.pixels, 16 * 4), 0xFF000000, "x10: second short")
|
||||
local tr = Xbm.decode(Bytes.reader(buffer.fromstring("#define c_width 2\n#define c_height 1\nstatic char c_bits[] = { 0x01 };")), { transparent = true }) :: any
|
||||
t:eq(buffer.readu32(tr.pixels, 4), 0x00FFFFFF, "transparent clear bits")
|
||||
t:eq(Xbm.sniff(Bytes.reader(buffer.fromstring("#define c_width 2\n"))), 0.9, "sniff")
|
||||
local _, e = Xbm.decode(Bytes.reader(buffer.fromstring("static char x[] = {};")))
|
||||
t:check(e and e.code == Err.CORRUPT, "no defines")
|
||||
local _, e2 = Xbm.encode(R.image(1, 1, "\0\0\0\255"), { name = "1bad" })
|
||||
t:check(e2 and e2.code == Err.ARG, "bad name")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Xbm.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,44 @@
|
||||
-- image/xpm tests: files from netpbm / ImageMagick and hand-written ones against the reference decode
|
||||
-- (ImageMagick), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/xpm.py.
|
||||
local T = require("@tests/T")
|
||||
local Xpm = require("@formats/image/xpm")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/xpm")
|
||||
|
||||
local t = T.suite("xpm")
|
||||
t:eq(Xpm.name, "xpm", "name")
|
||||
t:check(Xpm.caps.decode and Xpm.caps.encode, "caps")
|
||||
|
||||
t:note("%d files match the reference", R.decodes(t, Xpm, Fx.cases))
|
||||
t:note("%d of our files read back by it", R.decodes(t, Xpm, Fx.ours))
|
||||
for _, c in Fx.cases do
|
||||
R.roundTrip(t, Xpm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
if c.hotspot then
|
||||
local img = Xpm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
|
||||
end
|
||||
end
|
||||
do
|
||||
local img = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */\nstatic char *x[] = {"2 1 2 1 0 0", "a c gray50", "b c Unknownish", "ab"};'))) :: any
|
||||
t:eq(buffer.readu32(img.pixels, 0), 0xFF7F7F7F, "gray50")
|
||||
t:check(img.meta.unknownColours and img.meta.unknownColours[1] == "Unknownish", "unknown colour listed")
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == 0, "hotspot")
|
||||
t:eq(Xpm.sniff(Bytes.reader(buffer.fromstring("/* XPM */\n"))), 1, "sniff")
|
||||
local _, e = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */ static char *x[] = {"2 1 5 1", "a c red"};')))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short colour table")
|
||||
-- many colours: two chars per pixel
|
||||
local big = R.image(300, 1, "")
|
||||
big.pixels = buffer.create(1200)
|
||||
for i = 0, 299 do
|
||||
buffer.writeu32(big.pixels, i * 4, i * 997 + 0xFF000000)
|
||||
end
|
||||
local enc = R.roundTrip(t, Xpm, big, nil, "300 colours") :: buffer
|
||||
t:check(string.find(buffer.tostring(enc), '"300 1 300 2"', 1, true) ~= nil, "two chars per pixel")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Xpm.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -136,6 +136,10 @@ local function simple(): any
|
||||
return require("@formats/image/sgi")
|
||||
elseif which == "sunras" then
|
||||
return require("@formats/image/sunras")
|
||||
elseif which == "xbm" then
|
||||
return require("@formats/image/xbm")
|
||||
elseif which == "xpm" then
|
||||
return require("@formats/image/xpm")
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# XBM fixtures (tools/fixtures.py): files from netpbm (pbmtoxbm X11 and -x10), ImageMagick and Pillow (with a hotspot),
|
||||
# a hand-written one (comments, odd spacing); the reference is xbmtopbm (netpbm); our encoder's files
|
||||
# (tools/fixtures/_tex_encode.luau -a xbm) read by xbmtopbm.
|
||||
# tests/gen/xbm.luau { cases = { { name, data, w, h, rgba, hotspot? } }, ours = { ... } }
|
||||
import importlib.util, os
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S = _load("_raster_ref"), _load("_simple")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xbm"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
mono = bytes(v for i in range(29 * 13) for v in ((0,) * 3 if (i * 7 + i // 29) % 5 < 2 else (255,) * 3) + (255,))
|
||||
w.png("mono.png", 29, 13, mono)
|
||||
w.png("mono2.png", 16, 9, bytes(v for i in range(16 * 9) for v in ((0,) * 3 if (i % 3 == 0) else (255,) * 3) + (255,)))
|
||||
w.sh("netpbm", ["pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm -threshold > mono.pbm", "pbmtoxbm mono.pbm > nb_x11.xbm",
|
||||
"pbmtoxbm -x10 mono.pbm > nb_x10.xbm"])
|
||||
w.sh("imagemagick", ["magick mono2.png im.xbm"])
|
||||
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('mono.png').convert('1').save('pil.xbm', hotspot=(3, 4))\n" % w.dir)
|
||||
w.write("hand.xbm", b"/* a comment */\n#define hand_width 10\n#define hand_height 2\nstatic unsigned char hand_bits[] = {\n 0xff,0x03, /* row 0 */\n 0x00, 0x01 };\n")
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xbm"))
|
||||
mine = S.ours(ctx, "xbm")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
allnames = names + sorted(mine)
|
||||
w.sh("netpbm", ["xbmtopbm %s > %s.pbm" % (n, n) for n in allnames])
|
||||
out = {"cases": [], "ours": []}
|
||||
for n in allnames:
|
||||
ww, hh, rgba = R.pnm_rgba(w.read(n + ".pbm"))
|
||||
c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}
|
||||
if n == "pil.xbm":
|
||||
c["hotspot"] = [3, 4]
|
||||
out["ours" if n.startswith("ours_") else "cases"].append(c)
|
||||
ctx.emit("xbm", out)
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,58 @@
|
||||
# XPM fixtures (tools/fixtures.py): files from netpbm (ppmtoxpm -hexonly), ImageMagick (with alpha: None) and
|
||||
# hand-written ones (colour names, #RGB / #RRRRGGGGBBBB, g / m keys, two chars per pixel, XPM 2); the reference is
|
||||
# ImageMagick's decode (the XPM 2 file's values are written here: ImageMagick does not read XPM 2); our encoder's files (tools/fixtures/_tex_encode.luau -a xpm) read by ImageMagick.
|
||||
# tests/gen/xpm.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
|
||||
import importlib.util, os
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S = _load("_raster_ref"), _load("_simple")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xpm"]
|
||||
|
||||
HAND = b'''/* XPM */
|
||||
static char * hand_xpm[] = {
|
||||
/* width height ncolors cpp */
|
||||
"6 4 6 2",
|
||||
" c None",
|
||||
".. c red",
|
||||
"XX g4 #888 c LightBlue m white",
|
||||
"oo c #FFFF00000000",
|
||||
"++ s mine c navy",
|
||||
"@@ c Gold",
|
||||
" ..XXoo++@@",
|
||||
"..XXoo++@@ ",
|
||||
"XXoo++@@ ..",
|
||||
"oo++@@ ..XX"};
|
||||
'''
|
||||
XPM2 = b"! XPM2\n3 2 2 1\na c #102030\nb c white\nabb\nbab\n"
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
|
||||
w.png("alpha.png", 20, 11, bytes(v for i in range(20 * 11) for v in (((i * 40) % 256, 80, 200, 255 if i % 3 else 0))))
|
||||
w.sh("netpbm", ["pngtopam pal.png | pamtopnm > pal.ppm", "ppmtoxpm -hexonly pal.ppm > nb.xpm"])
|
||||
w.sh("imagemagick", ["magick pal.png -alpha off im.xpm", "magick alpha.png im_alpha.xpm"])
|
||||
w.write("hand.xpm", HAND)
|
||||
w.write("hand2.xpm", XPM2)
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xpm") and f != "hand2.xpm")
|
||||
mine = S.ours(ctx, "xpm")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
ref = S.magick_cases(R, w, names + sorted(mine), "xpm")
|
||||
out = {"cases": [], "ours": []}
|
||||
for n in names + sorted(mine):
|
||||
ww, hh, rgba = ref[n]
|
||||
# ImageMagick keeps the colour of transparent pixels; we decode None as transparent black
|
||||
rgba = bytes(0 if rgba[i - i % 4 + 3] == 0 else v for i, v in enumerate(rgba))
|
||||
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
|
||||
a, b = bytes((0x10, 0x20, 0x30, 255)), b"\xff" * 4
|
||||
out["cases"].append({"name": "hand2.xpm (XPM 2)", "data": XPM2, "w": 3, "h": 2, "rgba": a + b + b + b + a + b})
|
||||
ctx.emit("xpm", out)
|
||||
finally:
|
||||
w.close()
|
||||
Reference in new issue
Block a user