ws-docs: guide pages cad, font, layered, music, playlist, subtitles, tilemap, video; runnable examples per category; README converting note

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 13:25:10 -05:00
1 parent 66cf0c4a6b
commit fd9684b903
23 files changed
+2503 -5

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
-- examples/archive.luau: builds a zip, lists and reads it, edits it, converts it to a .tar.gz and back, and gzips a
-- single file. Run from the repository root: luau examples/archive.luau (docs/guide/archive.md explains the API).
local F = require("@formats")
-- a new zip: a directory, a text file, an incompressible file stored as is
local zip = F.format("zip").create()
zip:add("game/", nil)
zip:add("game/readme.txt", string.rep("formats-luau reads and writes archives. ", 20), { level = 9 })
local noise = buffer.create(2048)
local seed = 7
for i = 0, 2047 do
seed = (seed * 1103515245 + 12345) % 2147483648
buffer.writeu8(noise, i, seed // 65536 % 256)
end
zip:add("game/noise.bin", noise, { method = "store" })
local zipBytes = assert(F.save(zip, nil, { format = "zip", comment = "example" }))
print(string.format("zip: %d bytes", buffer.len(zipBytes)))
-- list and read
local loaded = assert(F.archive.load(zipBytes))
for _, e in loaded:list() do
print(string.format(" %-18s %6d -> %6s %s", e.name, e.size, tostring(e.compressedSize), e.method or (if e.dir then "dir" else "")))
end
local readme = assert(loaded:read("game/readme.txt"))
assert(buffer.len(readme) == 800)
-- edit: replace one entry, drop another, save (unchanged entries are copied without recompressing)
loaded:add("game/readme.txt", "short now")
assert(loaded:remove("game/noise.bin"))
local edited = assert(F.save(loaded))
assert(#F.archive.load(edited):list() == 2)
-- convert to .tar.gz: it loads back as the tar inside, with meta.compression = "gzip"
local tgz = assert(F.convert(edited, "tgz"))
local tar = assert(F.archive.load(tgz))
assert(tar.format == "tar" and tar.meta.compression == "gzip")
print(string.format("tar.gz: %d bytes, %d entries, read back as %s inside %s", buffer.len(tgz), #tar:list(), tar.format, tar.meta.compression))
assert(buffer.tostring(assert(tar:read("game/readme.txt"))) == "short now")
-- one file through gzip
local gz = assert(F.save(readme, nil, { format = "gzip", name = "readme.txt" }))
local single = assert(F.archive.load(gz))
assert(single.meta.stream and single:list()[1].name == "readme.txt")
print(string.format("gzip: %d -> %d bytes", buffer.len(readme), buffer.len(gz)))
print("archive example: ok")
+48
View File
@@ -0,0 +1,48 @@
-- Audio example (formats-luau): build a sound, edit it with F.ops.audio, encode it to several formats, then stream it
-- back with a Decoder. Run from the repository root: luau examples/audio.luau (docs/guide/audio.md explains the API).
local F = require("@formats")
local A = F.ops.audio
-- 1. one second of a stereo chord: interleaved f32 samples, frame i / channel c at byte (i * channels + c) * 4
local rate = 22050
local tone = F.Types.Audio.new(rate, 2, rate)
for i = 0, tone.frames - 1 do
local t = i / rate
buffer.writef32(tone.samples, (i * 2) * 4, 0.3 * math.sin(2 * math.pi * 261.63 * t)) -- left: C4
buffer.writef32(tone.samples, (i * 2 + 1) * 4, 0.3 * math.sin(2 * math.pi * 329.63 * t)) -- right: E4
end
tone.tags = { title = "Example chord", artist = "formats-luau" }
-- 2. edit: fade, normalize, a mono copy at 16 kHz, then the two one after the other
local shaped = assert(A.normalize(assert(A.fade(tone, 0.05, 0.2)), 0.8))
local mono = assert(A.resample(assert(A.downmix(shaped, 1)), 16000))
local both = assert(A.concat({ shaped, mono })) -- mono is converted to stereo 22.05 kHz
print(string.format("edited: %d frames, %.2f s, peak %.2f", both.frames, both.frames / both.sampleRate, (A.peak(both))))
-- 3. encode: lossless and lossy
for _, fmt in { "wav", "flac", "mp3", "vorbis", "opus" } do
local opts = { format = fmt }
if fmt == "mp3" then opts.bitrate = 128 end -- kbit/s
if fmt == "opus" then opts.bitrate = 64000 end -- bit/s
local bytes = assert(F.save(both, nil, opts))
local dec = assert(F.audio.open(bytes))
print(string.format("%-6s %6d bytes %5d Hz %d ch %.2f s title=%s", fmt, buffer.len(bytes), dec.sampleRate, dec.channels,
dec.duration, tostring(dec.tags.title)))
assert(math.abs(dec.duration - 2) < 0.1)
end
-- 4. stream a FLAC back in blocks, reusing one buffer, and measure its level
local dec = assert(F.audio.open(assert(F.save(both, nil, { format = "flac" }))))
local block = buffer.create(512 * dec.channels * 4)
local frames, sumSquares = 0, 0
while true do
local out, n = dec:read(512, block)
if n == 0 then break end
for k = 0, n * dec.channels - 1 do
local s = buffer.readf32(out, k * 4)
sumSquares += s * s
end
frames += n
end
assert(frames == both.frames)
print(string.format("streamed %d frames, rms %.3f", frames, math.sqrt(sumSquares / (frames * dec.channels))))
+72
View File
@@ -0,0 +1,72 @@
-- examples/cad.luau: reads a small STEP file, walks its entity graph (references, complex instances), adds an entity
-- and writes it back under another schema. Run from the repository root: luau examples/cad.luau
-- Solid geometry (B-rep bodies, meshes) needs a kernel plug-in, F.plugins.brep: see docs/guide/cad.md.
local F = require("@formats")
local STEP = [[
ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('example'),'2;1');
FILE_NAME('bracket.step','2026-10-31T12:00:00',('me'),(''),'formats-luau','','');
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
ENDSEC;
DATA;
#10=CARTESIAN_POINT('',(0.,0.,0.));
#11=DIRECTION('',(0.,0.,1.));
#12=DIRECTION('',(1.,0.,0.));
#13=AXIS2_PLACEMENT_3D('',#10,#11,#12);
#14=PLANE('',#13);
#20=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));
#21=PRODUCT('bracket','Bracket','',(#22));
#22=PRODUCT_CONTEXT('',#23,'mechanical');
#23=APPLICATION_CONTEXT('automotive design');
ENDSEC;
END-ISO-10303-21;
]]
local cad = assert(F.cad.load(STEP))
local step = assert(F.format("step"))
print(string.format("schema %s, %d instances, file %s", cad.schema, cad.meta.count, cad.header.FILE_NAME[1]))
-- count instances per type
local counts = {}
for _, id in step.ids(cad) do
local t = cad.entities[id].type
counts[t] = (counts[t] or 0) + 1
end
local types = {}
for t in counts do
table.insert(types, t)
end
table.sort(types)
for _, t in types do
print(string.format(" %-22s %d", t, counts[t]))
end
-- follow references: PLANE -> AXIS2_PLACEMENT_3D -> its location point
local plane = cad.entities[step.byType(cad, "PLANE")[1]]
local placement = assert(step.get(cad, plane.args[2]))
local location = assert(step.get(cad, placement.args[2]))
print("plane origin:", table.concat(location.args[2], ", "))
-- the length unit is a complex instance
local si = assert(step.part(cad.entities[20], "SI_UNIT"))
print("length unit:", si[1].enum, si[2].enum) -- MILLI METRE
assert(si[1].enum == "MILLI")
-- the product name
local product = cad.entities[step.byType(cad, "PRODUCT")[1]]
print("product:", product.args[1], product.args[2])
-- add a point and write the file as AP242
local p = step.add(cad, "CARTESIAN_POINT", { "tip", step.real(step.real(step.real({ 40, 0, 8 }, 1), 2), 3) })
local text = assert(F.saveString(cad, { schema = "AP242" }))
assert(string.find(text, "#" .. p .. "=CARTESIAN_POINT('tip',(40.,0.,8.));", 1, true))
local back = assert(F.cad.load(text))
assert(back.schema == "AP242" and #step.ids(back) == 10) -- add() also updates meta.count
print(string.format("wrote %d bytes of AP242 with #%d added", #text, p))
-- without a kernel plug-in the B-rep calls say so
local _, err = F.cad.tessellate(cad)
print("tessellate without a plug-in:", err.code)
print("cad example: ok")
+64
View File
@@ -0,0 +1,64 @@
-- examples/data.luau: one record through JSON, YAML, TOML, MessagePack and CBOR, plus CSV rows, an INI file and an
-- XML document. Run from the repository root: luau examples/data.luau (docs/guide/data.md explains the values).
local F = require("@formats")
local Types = F.Types
-- an ordered record with a null, an empty object and a date
local save = Types.object()
Types.set(save, "player", "ada")
Types.set(save, "level", 7)
Types.set(save, "items", { "sword", "lamp" })
Types.set(save, "guild", F.data.null)
Types.set(save, "flags", Types.object()) -- stays {} (a plain {} would be written as [])
Types.set(save, "saved", Types.Date.parse("2026-10-31T12:00:00Z"))
local json = assert(F.saveString(save, { format = "json", indent = 2 }))
print(json)
local back = assert(F.data.load(json, { format = "json", ordered = true }))
assert(back.guild == F.data.null and Types.isObject(back.flags) and back.items[2] == "lamp")
assert(table.concat(Types.keys(back), ",") == "player,level,items,guild,flags,saved")
for _, fmt in { "yaml", "toml", "msgpack", "cbor" } do
local v = save
if fmt == "toml" then -- TOML has no null
v = Types.object()
for _, k in Types.keys(save) do
if save[k] ~= F.data.null then
Types.set(v, k, save[k])
end
end
end
local bytes = assert(F.save(v, nil, { format = fmt }))
local again = assert(F.data.load(bytes, { format = fmt }))
assert(again.player == "ada" and again.level == 7)
if fmt ~= "yaml" then
assert(Types.Date.is(again.saved) and Types.Date.toUnix(again.saved) == Types.Date.toUnix(save.saved))
end
print(string.format("%-8s %4d bytes", fmt, buffer.len(bytes)))
end
-- CSV: records with a header row
local csv = "name,score\nada,1200\n\"lee, jr\",400\n"
local recs = assert(F.data.load(csv, { format = "csv", header = true, numbers = true }))
local total = 0
for _, r in recs do
total += r.score
end
print(string.format("csv: %d records, total score %d", #recs, total))
assert(total == 1600 and recs[2].name == "lee, jr")
-- INI with typed values
local ini = assert(F.data.load("[window]\nwidth = 800\nfullscreen = no\n", { format = "ini", types = true }))
assert(ini.window.width == 800 and ini.window.fullscreen == false)
-- XML: find elements by name
local doc = assert(F.data.load('<scores><s who="ada">1200</s><s who="bob">950</s></scores>', { format = "xml" }))
local who = {}
for _, c in doc.root.children do
if type(c) == "table" and c.name == "s" then
table.insert(who, c.attrs.who .. "=" .. c.children[1])
end
end
print("xml: " .. table.concat(who, " "))
assert(#who == 2)
print("data example: ok")
+64
View File
@@ -0,0 +1,64 @@
-- examples/font.luau: loads a TrueType font, prints its metrics, renders a line of text into a PNG and bakes the font
-- into a BMFont (descriptor + page images). Run from the repository root: luau examples/font.luau
-- It needs a .ttf: from the repo it uses the docs test font (generate it first with python3 -I tools/fixtures.py docs),
-- elsewhere set TTF_BYTES below to the bytes of any font (the luau CLI cannot read files). docs/guide/font.md explains.
local F = require("@formats")
local TTF_BYTES: buffer? = nil
if not TTF_BYTES then
local ok, IN = pcall(function()
return require("@tests/docs/snippets/_inputs")
end)
if ok then
TTF_BYTES = IN.ttfBytes
end
end
if not TTF_BYTES then
print("font example: no font. Run `python3 -I tools/fixtures.py docs` in the repository, or set TTF_BYTES.")
return
end
local font = assert(F.font.load(TTF_BYTES))
print(string.format("%s %s: %d glyphs, %d units per em, ascent %d, descent %d", font.info.family or "?",
font.info.style or "", font.numGlyphs, font.unitsPerEm, font.ascent, font.descent))
-- render "Hello, fonts!" at 32 px into a white-on-dark rgba8 image
local px, text = 32, "Hello, fonts!"
local scale = px / font.unitsPerEm
local width, prev = 0, nil
for _, cp in utf8.codes(text) do
local g = font:glyphIndex(cp)
width += font:advance(g) + (if prev then font:kern(prev, g) else 0)
prev = g
end
local canvas = assert(F.ops.image.new(math.ceil(width * scale) + 8, math.ceil((font.ascent - font.descent) * scale) + 8))
F.ops.image.fill(canvas, 24, 28, 40, 255)
local baseline = 4 + math.ceil(font.ascent * scale)
local pen = 4
prev = nil
for _, cp in utf8.codes(text) do
local g = font:glyphIndex(cp)
if prev then
pen += font:kern(prev, g) * scale
end
local glyph = assert(font:rasterize(g, px)) -- alpha8, placed by meta.left / meta.top
if glyph.width > 0 then
F.ops.image.blit(canvas, glyph, math.floor(pen + glyph.meta.left + 0.5), baseline - glyph.meta.top)
end
pen += glyph.meta.advance
prev = g
end
local png = assert(F.save(canvas, nil, { format = "png" }))
print(string.format("rendered %q: %d x %d, %d bytes of PNG", text, canvas.width, canvas.height, buffer.len(png)))
-- bake printable ASCII at 20 px into a BMFont for a game's text renderer
local baked = assert(F.format("bmfont").bake(font, { px = 20, file = "ui" }))
local fnt = assert(F.saveString(baked))
for i, page in baked.pages do
local bytes = assert(F.save(page, nil, { format = "png" }))
print(string.format("bmfont page %s: %d x %d, %d bytes", baked.meta.pageFiles[i], page.width, page.height, buffer.len(bytes)))
end
print(string.format("bmfont descriptor: %d bytes, %d characters", #fnt, #baked.meta.bmfont.chars))
local again = assert(F.font.load(fnt, { pages = baked.pages }))
assert(again:rasterize(again:glyphIndex(string.byte("A"))))
print("font example: ok")
+50
View File
@@ -0,0 +1,50 @@
-- examples/image.luau: build an image, edit it with F.ops.image, save it in several formats, make an animated GIF and
-- read it back. Run from the repository root: luau examples/image.luau (the .luaurc alias @formats points at src/).
-- On LuaJIT / LÖVE, the same calls work with local F = require("formats") (docs/guide/image.md).
local F = require("@formats")
local I = F.ops.image
-- a 64 x 48 rgba8 gradient: 4 bytes per pixel, rows top to bottom, pixel (x, y) at byte (y * width + x) * 4
local img = F.Types.Image.new(64, 48)
for y = 0, 47 do
for x = 0, 63 do
local o = (y * 64 + x) * 4
buffer.writeu8(img.pixels, o, x * 4)
buffer.writeu8(img.pixels, o + 1, y * 5)
buffer.writeu8(img.pixels, o + 2, 128)
buffer.writeu8(img.pixels, o + 3, 255)
end
end
-- edit: a white square blitted on, then a thumbnail, a crop, a rotation and a grey copy
local square = assert(I.new(16, 16))
I.fill(square, 255, 255, 255, 200)
assert(I.blit(img, square, 24, 16))
local thumb = assert(I.resize(img, 32, 24, "lanczos"))
local corner = assert(I.crop(img, 0, 0, 16, 16))
local turned = assert(I.rotate90(img, 1))
local grey = assert(I.convert(img, "gray8"))
assert(thumb.width == 32 and corner.width == 16 and turned.width == 48 and grey.format == "gray8")
print(string.format("pixel (30, 20) after the blit: %d %d %d %d", I.getPixel(img, 30, 20)))
-- save in several formats and load each back
for _, fmt in { "png", "jpeg", "webp", "qoi", "bmp", "tga", "gif" } do
local bytes = assert(F.save(img, nil, { format = fmt }))
local back = assert(F.load(bytes))
assert(back.width == 64 and back.height == 48 and F.detect(bytes) == fmt)
print(string.format("%-5s %6d bytes", fmt, buffer.len(bytes)))
end
-- an animation: four frames, 0.1 s each, looping forever
local frames = {}
for i = 1, 4 do
frames[i] = assert(I.rotate90(thumb, (i - 1) * 2)) -- every frame the same size: 0 or 2 quarter turns
local marker = assert(I.new(4, 4))
I.fill(marker, 255, 0, 0)
I.blit(frames[i], marker, (i - 1) * 8, 0) -- a red marker that moves right
end
local anim = assert(I.fromFrames(frames, 0.1))
local gif = assert(F.save(anim, nil, { format = "gif" }))
local back = assert(F.load(gif))
assert(I.frameCount(back) == 4 and back.loops == 0)
print(string.format("animated gif: %d frames, %.1f s", I.frameCount(back), I.durations(back)[1] * 4))
+55
View File
@@ -0,0 +1,55 @@
-- examples/layered.luau: build a layered document (a group, a clipping layer, a blend mode), flatten it, save it as
-- PSD and Aseprite, and make a small Aseprite animation exported as a GIF. Run from the repository root:
-- luau examples/layered.luau (docs/guide/layered.md explains the type).
local F = require("@formats")
local I, L = F.ops.image, F.Types.Layered
local function solid(w, h, r, g, b, a)
local img = assert(I.new(w, h))
I.fill(img, r, g, b, a)
return img
end
local doc = L.new(64, 64)
local shadow = L.layer("Shadow", solid(64, 64, 0, 0, 80, 255))
shadow.clip = true -- only where Card has alpha
shadow.blend = "multiply"
local card = L.layer("Card", solid(40, 40, 250, 200, 60, 255), 12, 12)
doc.layers = {
L.layer("Paper", solid(64, 64, 245, 245, 240, 255)), -- bottom
L.group("Art", { card, shadow }),
L.layer("Glass", solid(64, 20, 255, 255, 255, 255), 0, 0), -- top
}
doc.layers[3].opacity = 0.25
local flat = assert(F.ops.layers.flatten(doc))
print(string.format("flattened %dx%d, pixel (32, 40) = %d %d %d %d", flat.width, flat.height, I.getPixel(flat, 32, 40)))
for layer, depth in F.ops.layers.leaves(doc.layers) do
print(string.rep(" ", depth) .. layer.name .. " (" .. layer.blend .. ")")
end
-- save and reload in both layered formats
for _, fmt in { "psd", "aseprite" } do
local bytes = assert(F.save(doc, nil, { format = fmt }))
local back = assert(F.load(bytes))
assert(back.kind == "layered" and back.width == 64)
local again = assert(F.ops.layers.flatten(back))
local r1 = I.getPixel(again, 32, 40)
local r2 = I.getPixel(flat, 32, 40)
assert(math.abs(r1 - r2) <= 2)
print(string.format("%-8s %6d bytes, %d top-level layers", fmt, buffer.len(bytes), #back.layers))
end
-- an animation: a dot moving across four frames
local anim = L.new(16, 16)
local dot = solid(4, 4, 255, 60, 60, 255)
anim.frames = {}
for i = 1, 4 do
anim.frames[i] = { layers = { L.layer("Back", solid(16, 16, 20, 20, 30, 255)), L.layer("Dot", dot, i * 3 - 2, 6) }, delay = 0.15 }
end
anim.layers = anim.frames[1].layers
local ase = assert(F.save(anim, nil, { format = "aseprite" }))
local gifImage = assert(F.ops.layers.flattenFrames(assert(F.load(ase))))
local gif = assert(F.save(gifImage, nil, { format = "gif" }))
assert(I.frameCount(assert(F.load(gif))) == 4)
print("aseprite animation -> gif: 4 frames, " .. buffer.len(gif) .. " bytes")
+34
View File
@@ -0,0 +1,34 @@
-- Music example (formats-luau): write a MIDI file from scratch, read it back, and render it to audio with the built-in
-- waveforms (pass a SoundFont as { soundfont = sf2Bytes } for real instruments). Run from the repository root:
-- luau examples/music.luau (docs/guide/music.md explains the API).
local F = require("@formats")
-- 1. a Midi: 480 ticks per quarter note, absolute ticks, a tempo, a track name and a little melody
local midi = F.Types.Midi.new(480)
local events = {
{ tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- 500000 us per beat = 120 BPM
{ tick = 0, type = "meta", meta = 0x03, data = { string.byte("Melody", 1, -1) } }, -- the track name
{ tick = 0, type = "program", channel = 0, data = { 0 } },
}
local tick = 0
for _, note in { 60, 62, 64, 65, 67, 67, 69, 67 } do
table.insert(events, { tick = tick, type = "noteOn", channel = 0, data = { note, 96 } })
tick += 240 -- an eighth note
table.insert(events, { tick = tick, type = "noteOff", channel = 0, data = { note, 0 } })
end
table.insert(midi.tracks, { events = events })
-- 2. save as .mid and read it back
local bytes = assert(F.save(midi, nil, { format = "midi" }))
local song = assert(F.music.load(bytes))
print(string.format("midi: %d bytes, type %d, %d track(s), \"%s\", %.1f s at %d BPM", buffer.len(bytes), song.format,
#song.tracks, tostring(song.tracks[1].name), song.meta.length, song.meta.tempos[1].bpm))
assert(song.meta.length == 2)
-- 3. render: a Decoder (stereo f32), turned into an Audio, then saved as WAV
local dec = song:render({ sampleRate = 22050, tail = 0.5 })
local audio = assert(F.ops.audio.toAudio(dec))
local peak = F.ops.audio.peak(audio)
local wav = assert(F.save(audio, nil, { format = "wav" }))
print(string.format("rendered: %.2f s, peak %.2f, %d bytes of WAV", audio.frames / audio.sampleRate, peak, buffer.len(wav)))
assert(audio.frames == 2.5 * 22050 and peak > 0)
+47
View File
@@ -0,0 +1,47 @@
-- examples/playlist.luau: reads an M3U with a base URL, inspects an HLS master playlist, and converts a playlist to
-- PLS and XSPF. Run from the repository root: luau examples/playlist.luau (docs/guide/playlist.md explains the type).
local F = require("@formats")
local M3U = "#EXTM3U\n#PLAYLIST:Road Trip\n#EXTINF:215,Ada - First Song\nmusic/first.mp3\n"
.. "#EXTINF:187,Bob - Second Song\nhttps://cdn.example/second.ogg\n#EXTINF:-1,Live\nhttp://radio.example/live\n"
.. "C:\\Music\\local.flac\n"
local pl = assert(F.playlist.load(M3U, { baseUrl = "https://example.com/lists/trip.m3u" }))
print(string.format("%s (%s): %d entries", pl.title, pl.format, #pl.entries))
local total = 0
for i, e in pl.entries do
print(string.format(" %d. %-32s %-18s %s", i, e.url, e.title or "", if e.playable then "ok" else "skip: " .. tostring(e.reason)))
total += e.duration or 0
end
assert(pl.entries[1].url == "https://example.com/lists/music/first.mp3")
assert(not pl.entries[4].playable and pl.entries[4].reason == "local path")
print(string.format("known length: %d s", total))
-- keep only what a player can fetch, then convert
local keep = {}
for _, e in pl.entries do
if e.playable then
table.insert(keep, e)
end
end
pl.entries = keep
local pls = assert(F.saveString(pl, { format = "pls" }))
local xspf = assert(F.saveString(pl, { format = "xspf" }))
assert(F.playlist.load(pls).entries[2].duration == 187)
assert(F.playlist.load(xspf).entries[1].title == "Ada - First Song")
print(string.format("pls %d bytes, xspf %d bytes", #pls, #xspf))
-- an HLS master playlist: pick the variant that fits a bandwidth
local MASTER = "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360\nlow.m3u8\n"
.. "#EXT-X-STREAM-INF:BANDWIDTH=2400000,RESOLUTION=1280x720\nhigh.m3u8\n"
local hls = assert(F.playlist.load(MASTER, { baseUrl = "https://cdn.example/show/master.m3u8" }))
assert(hls.format == "hls" and hls.hls.master)
local best = nil
for _, v in hls.entries do
if v.bandwidth <= 1500000 and (not best or v.bandwidth > best.bandwidth) then
best = v
end
end
print("variant for 1.5 Mbit/s: " .. best.attributes.RESOLUTION .. " " .. best.url)
assert(best.url == "https://cdn.example/show/low.m3u8")
print("playlist example: ok")
+81
View File
@@ -0,0 +1,81 @@
-- examples/scene.luau: builds a 3D scene from scratch (a cube with a material, plus a voxel grid), edits it with
-- F.ops.mesh and saves it as GLB, OBJ + MTL and STL. Run from the repository root: luau examples/scene.luau
-- (docs/guide/scene.md explains the Scene type).
local F = require("@formats")
local S = F.Types.Scene
-- a unit cube: 8 corners, 12 triangles (indices are 0-based vertex numbers, as in glTF)
local corners = {
{ -0.5, -0.5, -0.5 }, { 0.5, -0.5, -0.5 }, { 0.5, 0.5, -0.5 }, { -0.5, 0.5, -0.5 },
{ -0.5, -0.5, 0.5 }, { 0.5, -0.5, 0.5 }, { 0.5, 0.5, 0.5 }, { -0.5, 0.5, 0.5 },
}
local tris = {
0, 2, 1, 0, 3, 2, -- back (-z)
4, 5, 6, 4, 6, 7, -- front (+z)
0, 1, 5, 0, 5, 4, -- bottom
3, 7, 6, 3, 6, 2, -- top
0, 4, 7, 0, 7, 3, -- left
1, 2, 6, 1, 6, 5, -- right
}
local pos = S.accessor(nil, "f32", 3, #corners) -- tightly packed: x, y, z per vertex
for i, c in corners do
for k = 1, 3 do
buffer.writef32(pos.data, ((i - 1) * 3 + k - 1) * 4, c[k])
end
end
local idx = S.accessor(nil, "u32", 1, #tris)
for i, v in tris do
buffer.writeu32(idx.data, (i - 1) * 4, v)
end
local scene = S.fromPrimitive({ attributes = { POSITION = pos }, indices = idx, mode = "triangles", material = 1 }, "cube")
local red = S.material("red")
red.baseColor = { 0.8, 0.05, 0.05, 1 } -- linear RGBA
red.metallic, red.roughness = 0, 0.6
scene.materials[1] = red
scene.nodes[1].translation = { 0, 0.5, 0 } -- sit on the ground (y up)
scene.meta.up = "y"
-- flat normals: split the corners so each face has its own normal
local prim = scene.meshes[1].primitives[1]
prim = assert(F.ops.mesh.computeNormals(prim, { flat = true }))
scene.meshes[1].primitives[1] = prim
assert(prim.attributes.NORMAL.count == 36)
local lo, hi = F.ops.mesh.bounds(scene) -- world space: the node's translation applies
print(string.format("cube bounds: (%g, %g, %g) .. (%g, %g, %g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]))
assert(lo[2] == 0 and hi[2] == 1)
-- save: GLB (one buffer), OBJ (+ the .mtl in opts.files), STL (geometry only)
local glb = assert(F.save(scene, nil, { format = "glb" }))
local files = {}
local obj = assert(F.save(scene, nil, { format = "obj", name = "cube.obj", files = files }))
local stl = assert(F.save(scene, nil, { format = "stl" }))
for name, data in files do
print("obj writes " .. name .. " too (" .. (if type(data) == "string" then #data else buffer.len(data)) .. " bytes)")
end
print(string.format("glb %d bytes, obj %d bytes, stl %d bytes", buffer.len(glb), buffer.len(obj), buffer.len(stl)))
local back = assert(F.model.load(glb))
assert(#back.meshes == 1 and back.materials[1].name == "red")
-- voxels: a 4 x 4 x 4 grid with a staircase, greedy-meshed into triangles
local V = F.Types.Voxels
local grid = V.new(4, 4, 4)
grid.palette[1] = { 90, 160, 60, 255 }
local cells = 0
for x = 0, 3 do
for y = 0, 3 do
for z = 0, x do
V.set(grid, x, y, z, 1) -- cell (x, y, z) = palette entry 1 (stored at x + 4 * (y + 4 * z))
cells += 1
end
end
end
local vprim = assert(F.ops.mesh.voxelsToPrimitive(grid))
print(string.format("voxels: %d cells set, greedy mesh with %d triangles", cells, vprim.indices.count // 3))
local vox = S.fromPrimitive(vprim, "stairs")
vox.materials[1] = S.material("voxels")
vprim.material = 1
assert(F.save(vox, nil, { format = "glb" }))
print("scene example: ok")
+57
View File
@@ -0,0 +1,57 @@
-- examples/tilemap.luau: read a Tiled map (TMX), walk its tile layer with the flip flags, find an object, edit the map
-- and convert it to TMJ. Run from the repository root: luau examples/tilemap.luau (docs/guide/tilemap.md).
local F = require("@formats")
local tmx = [[<?xml version="1.0" encoding="UTF-8"?>
<map version="1.10" orientation="orthogonal" renderorder="right-down" width="5" height="3" tilewidth="16"
tileheight="16" infinite="0" nextlayerid="3" nextobjectid="2">
<tileset firstgid="1" name="terrain" tilewidth="16" tileheight="16" tilecount="16" columns="4">
<image source="terrain.png" width="64" height="64"/>
</tileset>
<layer id="1" name="ground" width="5" height="3">
<data encoding="csv">
1,2,2,2,3,
5,0,0,0,7,
9,10,2147483658,10,11
</data>
</layer>
<objectgroup id="2" name="things">
<object id="1" name="door" type="Door" x="32" y="16" width="16" height="16">
<properties><property name="locked" type="bool" value="true"/></properties>
</object>
</objectgroup>
</map>]]
local map = assert(F.load(tmx))
print(string.format("%dx%d tiles of %dx%d px, %d layers", map.width, map.height, map.tileWidth, map.tileHeight, #map.layers))
local FLIP_H, FLAGS = 0x80000000, 0xF0000000
local ground = map.layers[1]
for y = 0, ground.height - 1 do
local row = {}
for x = 0, ground.width - 1 do
local raw = ground.data[1 + x + y * ground.width]
local gid = bit32.band(raw, bit32.bnot(FLAGS))
row[#row + 1] = if gid == 0 then " ." elseif bit32.btest(raw, FLIP_H) then string.format("%2dh", gid) else string.format("%2d", gid)
end
print(table.concat(row, " "))
end
local door
for _, o in map.layers[2].objects do
if o.class == "Door" then
door = o
end
end
assert(door and door.properties.locked == true)
print(string.format("door at tile (%d, %d), locked", door.x // map.tileWidth, door.y // map.tileHeight))
-- edit: fill the hole in the middle row, then write TMJ and read it back
for x = 1, 3 do
ground.data[1 + x + 1 * ground.width] = 6
end
local tmj = assert(F.saveString(map, { format = "tmj" }))
local back = assert(F.load(tmj, { format = "tiled" }))
assert(back.layers[1].data[8] == 6 and back.layers[1].data[13] == 0x8000000A)
assert(back.layers[2].objects[1].properties.locked == true)
print("as TMJ: " .. #tmj .. " characters; tileset image " .. back.tilesets[1].imageSource)
+41
View File
@@ -0,0 +1,41 @@
-- examples/vector.luau: parse an SVG, inspect its paths, rasterize it at two sizes, build a Vector from scratch and
-- write it as SVG. Run from the repository root: luau examples/vector.luau (docs/guide/vector.md explains the type).
local F = require("@formats")
local svg = [[<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24">
<rect x="1" y="1" width="22" height="22" rx="4" fill="#2d6cdf"/>
<path d="M6 12 L10 16 L18 8" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round"
stroke-linejoin="round"/>
</svg>]]
local icon = assert(F.vector.load(svg))
print(string.format("%dx%d, viewBox %s, %d paths", icon.width, icon.height, table.concat(icon.viewBox, " "), #icon.paths))
for i, p in icon.paths do
print(i, p.fill and p.fill.type or "no fill", p.stroke and "stroke " .. p.strokeWidth or "no stroke", #p.d .. " commands")
end
-- rasterize: the default size, and a larger one (the viewBox scales to fit)
local small = assert(F.ops.vector.rasterize(icon))
local big = assert(F.ops.vector.rasterize(icon, 256, 256))
assert(small.width == 48 and big.width == 256)
local r, _, b, a = F.ops.image.getPixel(big, 128, 20)
assert(a == 255 and b > r, "the blue background")
local png = assert(F.save(big, nil, { format = "png" }))
print("rasterized to a 256x256 PNG of " .. buffer.len(png) .. " bytes")
-- a Vector from scratch: a red triangle, written as SVG and read back
local v = F.Types.Vector.new(32, 32)
table.insert(v.paths, {
d = { { op = "M", 4, 28 }, { op = "L", 16, 4 }, { op = "L", 28, 28 }, { op = "Z" } },
fill = { type = "color", color = { 220, 40, 40, 255 } },
fillRule = "nonzero",
strokeWidth = 0,
opacity = 1,
})
local text = assert(F.saveString(v, { format = "svg" }))
local again = assert(F.vector.load(text))
assert(#again.paths == 1)
local tri = assert(F.ops.vector.rasterize(again))
local tr = F.ops.image.getPixel(tri, 16, 20)
assert(tr == 220)
print("triangle SVG: " .. #text .. " characters")
+52
View File
@@ -0,0 +1,52 @@
-- Video example (formats-luau): make frames with F.ops.image, write them as an AVI (Motion-JPEG), then open the
-- video, walk its packets and frames, seek, and turn it into an animated GIF. Run from the repository root:
-- luau examples/video.luau (docs/guide/video.md explains the API).
local F = require("@formats")
local I = F.ops.image
-- 1. twelve 64 x 48 frames: a square moving across a dark background
local frames = {}
for i = 0, 11 do
local img = assert(I.new(64, 48))
I.fill(img, 20, 24, 40, 255)
local square = assert(I.new(12, 12))
I.fill(square, 255, 200, 40, 255)
I.blit(img, square, i * 4, 18)
frames[i + 1] = img
end
local clip = assert(F.video.fromFrames(frames, 1 / 12)) -- 12 fps
local avi = assert(F.save(clip, nil, { format = "avi", quality = 85 }))
print(string.format("avi: %d bytes", buffer.len(avi)))
-- 2. open it: the decoder, its demuxer and the video track
local v = assert(F.video.open(avi))
local track = v.track :: any
print(string.format("%s / %s %dx%d %.1f fps %d frames %.2f s", v.format, v.codec, v.width, v.height, v.frameRate,
v.frames, v.duration))
local packets = 0
for p in v.demuxer:packets(track.id) do
packets += 1
assert(p.keyframe) -- every MJPEG frame is a keyframe
end
v:reset()
-- 3. decode every frame (yuv420p), keep rgba8 copies, and check where the square ended up
local decoded = {}
while true do
local f = v:nextFrame()
if not f then break end
table.insert(decoded, v:toRGBA(f))
end
local last = decoded[#decoded]
local r, g = I.getPixel(last, 44 + 6, 18 + 6) -- the centre of the last square
print(string.format("%d packets, last frame centre pixel r=%d g=%d", packets, r, g))
assert(packets == 12 and r > 200 and g > 150)
-- 4. seek, then turn the decoded frames into an animated GIF (a video does not save to an image format directly)
v:seek(0.5)
local f = assert(v:nextFrame())
print(string.format("after seek(0.5): pts %.3f", f.pts))
local gif = assert(F.save(assert(I.fromFrames(decoded, 1 / v.frameRate)), nil, { format = "gif" }))
local anim = assert(F.image.load(gif))
print(string.format("gif: %d bytes, %d frames", buffer.len(gif), I.frameCount(anim)))
assert(I.frameCount(anim) == 12)