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

This commit is contained in:
4DBug committed 2026-10-31 13:25:10 -05:00
1 parent db81f73acf
commit fca79bd858
23 files changed
+2503 -5

No files matched your search

+3 -3
View File
@@ -263,9 +263,9 @@ local a = assert(F.load("out/tone.flac"))
assert(a.sampleRate == 44100 and a.channels == 2)
```
Conversions cross categories where it makes sense: an animated GIF converts to a video (`F.convert(gifBytes,
"avi")`), a music module renders to audio, and a single-stream archive such as `.tar.gz` loads as the archive inside.
The type pages show these.
Some conversions cross categories: an animated GIF converts to a video (`F.convert(gifBytes, "avi")`), and a
single-stream archive such as `.tar.gz` loads as the archive inside. A music file renders to audio through
`F.save(song:render(), nil, { format = "wav" })` ([Music](music.md)). The type pages show these.
## Hosts
+203
View File
@@ -0,0 +1,203 @@
# CAD (STEP)
STEP files (ISO 10303-21, "Part 21": AP203, AP214, AP242 and any other schema) load as a `Cad`: the file's header and
its *entity graph*, every `#id = TYPE(...)` instance with its arguments, exactly as written. Reading and writing the
graph is built in and lossless (parse, write, parse gives the same entities).
Turning the graph into solid geometry needs a B-rep kernel, which formats-luau does not include: B-rep bodies and
tessellated meshes come from a plug-in you inject as `F.plugins.brep` (for example
brep-luau's modules). Without it, `F.cad.toBodies` / `fromBodies` / `tessellate` return
`UNSUPPORTED` and everything else on this page still works.
```luau
local cad = assert(F.cad.load(stepText))
print(cad.schema, cad.meta.count) -- AP214 6
local step = assert(F.format("step")) -- the helpers below live on the format module
for _, id in step.byType(cad, "CARTESIAN_POINT") do
local e = cad.entities[id]
print(id, e.args[1], e.args[2][1], e.args[2][2], e.args[2][3]) -- 1 origin 0 0 0 / 5 tip 10 20 5.5
end
```
## The type
`Cad`:
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"cad"` | |
| `schema` | string | `"AP203"`, `"AP214"`, `"AP242"`, or the `FILE_SCHEMA` name as written |
| `header` | table | header entities by name: `FILE_DESCRIPTION`, `FILE_NAME`, `FILE_SCHEMA` (and any other), each a list of its arguments |
| `entities` | `{ [id]: StepEntity }` | the DATA instances by their `#id` (a sparse table: ids need not be contiguous) |
| `meta` | table | `source.format`, `count` (number of instances), `headerOrder` |
`StepEntity`:
| Field | Type | Meaning |
|---|---|---|
| `id` | number | the instance number (`#12` -> 12) |
| `type` | string | the entity type in upper case (`"CARTESIAN_POINT"`), or `"COMPLEX"` |
| `args` | `{ any }` | the parameters (below); empty for a complex instance |
| `parts` | `{ { type, args } }?` | complex instances `#6 = (A() B(*) C(...))`: one part per type, in file order |
| `section` | number? | the DATA section, in files with several (edition 3) |
Parameters map to Luau values:
| STEP | Luau |
|---|---|
| `12`, `1.5`, `0.` | a number (integral reals keep their real-ness when written back) |
| `'text'` | a string (Part 21 escapes `\X2\...` decoded to UTF-8) |
| `.T.`, `.MILLI.` | `{ enum = "T" }`, `{ enum = "MILLI" }` |
| `#4` | `{ ref = 4 }` |
| `(1., 2., 3.)` | a list |
| `LENGTH_MEASURE(2.5)` | `{ typed = "LENGTH_MEASURE", value = 2.5 }` |
| `"0FF"` | `{ binary = "0FF" }` |
| `$` / `*` | `step.NULL` / `step.DERIVED` (sentinels on the format module) |
## Inspect
`F.format("step")` has helpers for walking the graph:
| Function | Returns |
|---|---|
| `get(cad, id | { ref = id })` | the entity (follows a reference) |
| `ids(cad)` | every instance id, ascending |
| `byType(cad, "TYPE")` | the ids of instances of a type (complex instances with such a part too), ascending |
| `part(entity, "TYPE")` | the args of that type: the entity's own, or one part of a complex instance |
| `add(cad, type, args)` | adds an instance after the highest id and returns its id |
| `real(list, index)` | marks `list[index]` as a real, so an integral value is written `3.` rather than `3` |
| `new(schema?)` | an empty Cad (`"AP214"` by default) |
| `NULL`, `DERIVED`, `SCHEMAS` | `$`, `*`, and the full `FILE_SCHEMA` names of AP203 / AP214 / AP242 |
```luau
local cad = assert(F.cad.load(stepText))
local step = assert(F.format("step"))
local placement = cad.entities[step.byType(cad, "AXIS2_PLACEMENT_3D")[1]]
local origin = assert(step.get(cad, placement.args[2])) -- args[2] is { ref = 1 }
assert(origin.type == "CARTESIAN_POINT" and origin.args[1] == "origin")
local axis = step.get(cad, placement.args[3])
assert(axis.args[2][3] == 1) -- DIRECTION('z', (0., 0., 1.))
local unit = cad.entities[6] -- (LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI., .METRE.))
assert(unit.type == "COMPLEX" and #unit.parts == 3)
local si = assert(step.part(unit, "SI_UNIT"))
assert(si[1].enum == "MILLI" and si[2].enum == "METRE")
assert(step.part(unit, "NAMED_UNIT")[1] == step.DERIVED)
local name = cad.header.FILE_NAME -- name, time stamp, authors, organisations, ...
assert(name[1] == "part.step")
```
## Edit and save
Edit `entities` / `header` directly, or add instances with `add`. `F.save` writes Part 21 text, one instance per line
in id order.
| Encode option | Meaning |
|---|---|
| `schema` | `"AP203"`, `"AP214"`, `"AP242"` or a schema name: replaces `FILE_SCHEMA` |
| `name` | the `FILE_NAME` name (default: the header's, else `"model"`) |
| `timestamp` | the `FILE_NAME` time stamp when the header has none |
| `crlf` | CRLF line ends (default LF) |
```luau
local cad = assert(F.cad.load(stepText))
local step = assert(F.format("step"))
local coords = step.real(step.real(step.real({ 1, 2, 3 }, 1), 2), 3) -- written (1.,2.,3.)
local id = step.add(cad, "CARTESIAN_POINT", { "corner", coords })
assert(id == 7)
local text = assert(F.saveString(cad, { schema = "AP242" }))
assert(string.find(text, "#7=CARTESIAN_POINT('corner',(1.,2.,3.));", 1, true))
assert(string.find(text, "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF", 1, true))
local back = assert(F.cad.load(text))
assert(back.schema == "AP242" and back.meta.count == 7)
```
A new file from scratch:
```luau
local step = assert(F.format("step"))
local cad = step.new("AP203")
local p = step.add(cad, "CARTESIAN_POINT", { "p", step.real(step.real(step.real({ 0, 0, 0 }, 1), 2), 3) })
step.add(cad, "VERTEX_POINT", { "", { ref = p } })
local text = assert(F.saveString(cad, { format = "step", name = "vertex.step" })) -- built here: no source format
assert(string.find(text, "CONFIG_CONTROL_DESIGN", 1, true) and string.find(text, "#2=VERTEX_POINT('',#1);", 1, true))
```
## B-rep and meshes: the plug-in
STEP stores solids as boundary representations (faces on surfaces, trimmed by edges on curves). Evaluating them takes
a geometry kernel, which you inject:
<!-- doc:display needs the brep-luau plug-in -->
```luau
F.plugins.brep = { -- brep-luau's modules as they are
Step = require(path.to.brep.Step),
StepBrep = require(path.to.brep.StepBrep),
StepWrite = require(path.to.brep.StepWrite),
Tess = require(path.to.brep.Tess),
}
local cad = assert(F.cad.load(stepBytes))
local scene = assert(F.cad.tessellate(cad, { chord = 0.05 })) -- a Scene: one node + mesh per solid
local glb = assert(F.save(scene, nil, { format = "glb" }))
local bodies = assert(F.cad.toBodies(cad)) -- the kernel's own body objects
local copy = assert(F.cad.fromBodies(bodies)) -- a Cad written by the kernel
```
| Function | Returns |
|---|---|
| `F.cad.toBodies(cad, opts?)` | `bodies, result`: the kernel's bodies, and its whole read result (stats, warnings) |
| `F.cad.fromBodies(bodies, opts?)` | a `Cad` (the kernel writes STEP text, parsed back) |
| `F.cad.tessellate(cad | bodies, opts?)` | a `Scene`: one node and mesh per body, one primitive per face colour, **z up, millimetres** (`meta.unit = 0.001`) |
Options: `brep` (a plug-in for this call instead of `F.plugins.brep`), `chord` (the tessellation sag in millimetres,
default 0.05) or `tess` (the kernel's own tessellation options).
Any kernel works if it has this shape (every function may throw; the library catches it and returns `nil, err`):
| Function | Contract |
|---|---|
| `read(text, opts)` | STEP text -> `{ bodies = { body }, stats = ...? }`; a body may have `name` and `color` (`{ r, g, b }` 0..1) |
| `write(bodies, opts)` | bodies -> STEP text |
| `tessellate(body, opts)` | -> `{ positions = { {x, y, z} }, normals = { ... }?, indices = { 1-based, three per triangle }, faceOf = { [triangle] = face }? }` (a face may have `color`) |
A minimal stand-in kernel shows the contract (and is handy in tests): every file is one triangle.
```luau
local fake = {
read = function(text, opts)
return { bodies = { { name = "plate", color = { 1, 0, 0 } } }, stats = { bytes = #text } }
end,
tessellate = function(body, opts)
return { positions = { { 0, 0, 0 }, { 10, 0, 0 }, { 0, 10, 0 } }, indices = { 1, 2, 3 } }
end,
}
local cad = assert(F.cad.load(stepText))
local none, err = F.cad.tessellate(cad) -- no plug-in installed
assert(none == nil and err.code == F.Err.UNSUPPORTED)
local scene = assert(F.cad.tessellate(cad, { brep = fake }))
assert(scene.kind == "scene" and scene.meta.up == "z" and scene.meta.unit == 0.001)
assert(scene.meshes[1].name == "plate" and scene.meshes[1].primitives[1].indices.count == 3)
assert(scene.materials[1].extras.color[1] == 1) -- the body colour (baseColor is linear)
local _, werr = F.cad.fromBodies({}, { brep = fake }) -- this kernel cannot write
assert(werr.code == F.Err.UNSUPPORTED)
```
## Formats
| Format | Read | Write | Notes |
|---|---|---|---|
| step (`.step .stp .p21`) | yes | yes | editions 1 to 3, complex instances, several DATA sections; B-rep and tessellation through the plug-in |
STEP-XML (ISO 10303-28) and compressed `.stpZ` are not supported. See [FORMATS.md](../FORMATS.md).
## Gotchas
- **Ids are sparse.** `#entities` is meaningless; iterate `step.ids(cad)` (ordered) or `pairs(cad.entities)`.
- **References are tables.** `{ ref = 4 }` is not the entity; resolve it with `step.get(cad, ref)`.
- **Reals vs integers.** Luau has one number type. Values read as reals stay reals when written back; for new
values, mark integral reals with `step.real(list, index)`, or the file will contain `3` where the schema wants `3.`.
- **Complex instances** have `type = "COMPLEX"` and empty `args`; use `step.part(e, "TYPE")` or `e.parts`.
- **Tessellated scenes are z up in millimetres.** Convert for y-up engines with `F.ops.mesh.setUp(scene, "y")` and
`F.ops.mesh.setUnit(scene, 1)` (see [Scene](scene.md)).
+246
View File
@@ -0,0 +1,246 @@
# Fonts
Every font format loads as one `Font`: metrics, a character map, advances, kerning and glyph images. Outline fonts
(TrueType / OpenType `.ttf` / `.otf` / `.ttc`, WOFF, WOFF2) also give glyph outlines and rasterize at any size.
Bitmap fonts (AngelCode BMFont `.fnt`) crop their glyphs from page images. Fonts are read-only except BMFont, which is
also how an outline font is *baked* into a texture atlas for a game.
```luau
local font = assert(F.font.load(ttfBytes))
print(font.info.family, font.unitsPerEm) -- DejaVu Sans 2048
local g = font:glyphIndex(string.byte("A")) -- code point -> glyph index (0 = .notdef, missing)
local img = assert(font:rasterize(g, 32)) -- an alpha8 Image, 32 px per em
print(img.width, img.height, img.meta.advance) -- 22 24 21.89
assert(img.format == "alpha8")
```
## The type
`Font`:
| Field / method | Type | Meaning |
|---|---|---|
| `kind` | `"font"` | |
| `info` | table | `family`, `style`, `fullName`; outline fonts add the other `name` table strings (`postScriptName`, `version`, `copyright`, `license`, ...) |
| `unitsPerEm` | number | font units per em (TrueType: usually 1000 or 2048; BMFont: the size in pixels) |
| `ascent`, `descent`, `lineGap` | number | font units; `descent` is negative (below the baseline) |
| `numGlyphs` | number | glyph indices run `0 .. numGlyphs - 1` |
| `glyphIndex(self, cp)` | number | the glyph for a Unicode code point, `0` when the font has none |
| `advance(self, g)` | number | the horizontal advance (font units) |
| `kern(self, a, b)` | number | the kerning between glyphs `a` and `b` (font units, usually negative); `'kern'` table and GPOS pairs |
| `outline(self, g)` | `{ cmd }?` | the glyph's outline (outline fonts), `nil` for a bitmap font or a bad glyph |
| `rasterize(self, g, px)` | `Image?` | the glyph as an `alpha8` Image (below) |
| `pages` | `{ Image }?` | BMFont: the page images once loaded |
| `meta` | table | `source.format`; outline fonts: `outlines` (`"truetype"` / `"cff"`), `tables`, `os2`, `italicAngle`, `underlinePosition`, `fixedPitch`, `collection`; BMFont: `lineHeight`, `base`, `pageFiles`, `bmfont` (the parsed descriptor) |
Outline fonts also have `font:bounds(g)` (`xMin, yMin, xMax, yMax` in font units, `nil` for an empty glyph),
`font:kernCodepoints(a, b)`, `font:leftSideBearing(g)` and `font:scale(px)` (pixels per font unit, `px / unitsPerEm`).
**Units and directions.** Font units are the design grid: multiply by `px / unitsPerEm` to get pixels for a font
size of `px` pixels per em. In font units y points **up** from the baseline. Rasterized images are ordinary images,
rows top to bottom.
### Outlines
`outline(g)` returns a list of commands, each `{ op = name, x1, y1, ... }` with absolute coordinates in font units:
| `op` | Numbers | Meaning |
|---|---|---|
| `"moveTo"` | `x, y` | start a contour |
| `"lineTo"` | `x, y` | straight line |
| `"quadTo"` | `cx, cy, x, y` | quadratic Bézier (TrueType outlines) |
| `"cubicTo"` | `c1x, c1y, c2x, c2y, x, y` | cubic Bézier (CFF / OpenType outlines) |
| `"close"` | | close the contour |
TrueType fills by the nonzero rule, outer contours clockwise.
```luau
local font = assert(F.font.load(ttfBytes))
local cmds = assert(font:outline(font:glyphIndex(string.byte("A"))))
assert(cmds[1].op == "moveTo")
local x0, y0, x1, y1 = font:bounds(font:glyphIndex(string.byte("A")))
assert(y0 == 0 and y1 > 0) -- y up: the A stands on the baseline
local counts = {}
for _, c in cmds do
counts[c.op] = (counts[c.op] or 0) + 1
end
print(counts.moveTo, counts.lineTo, counts.close) -- 2 contours of straight lines
local _ = x0, x1
```
### Rasterized glyphs
`rasterize(g, px)` renders the glyph antialiased at `px` pixels per em (the CSS `font-size`, not the line height).
The result is an `alpha8` Image (one coverage byte per pixel, 0 to 255, rows top to bottom), cropped to the ink, with
the placement in `meta`:
| `meta` field | Meaning (pixels) |
|---|---|
| `left` | from the pen position to the image's left edge |
| `top` | from the baseline **up** to the image's top row (as FreeType's `bitmap_top`) |
| `advance` | how far to move the pen afterwards (fractional) |
| `glyph` | the glyph index |
Glyphs without ink (the space) give a 0 x 0 image that still has `meta.advance`. Outline fonts take an optional third
argument `{ scaleX, scaleY, shiftX, shiftY }` (pixels per font unit and a subpixel shift) for stretched or
subpixel-positioned glyphs.
```luau
local font = assert(F.font.load(ttfBytes))
local space = assert(font:rasterize(font:glyphIndex(32), 16))
assert(space.width == 0 and space.meta.advance > 0)
assert(font:glyphIndex(0x4E00) == 0) -- no CJK in this font: .notdef
```
## Drawing a string
Place each glyph at the pen position, move the pen by the advance plus the kerning, and draw the coverage onto an
image. `F.ops.image.blit` converts an `alpha8` glyph to white with that alpha and blends it "over" the canvas:
```luau
local font = assert(F.font.load(ttfBytes))
local px = 24
local scale = px / font.unitsPerEm
local text = "AVA Hello"
local width = 0
local prev = nil
for _, cp in utf8.codes(text) do -- measure: advances + kerning, in font units
local g = font:glyphIndex(cp)
width += font:advance(g) + (if prev then font:kern(prev, g) else 0)
prev = g
end
local baseline = math.ceil(font.ascent * scale)
local canvas = assert(F.ops.image.new(math.ceil(width * scale) + 2, math.ceil((font.ascent - font.descent) * scale)))
F.ops.image.fill(canvas, 20, 20, 40, 255)
local pen = 1
prev = nil
for _, cp in utf8.codes(text) do
local g = font:glyphIndex(cp)
if prev then
pen += font:kern(prev, g) * scale -- "AV" moves closer
end
local glyph = assert(font:rasterize(g, px))
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
assert(font:kern(font:glyphIndex(65), font:glyphIndex(86)) < 0)
local png = assert(F.save(canvas, nil, { format = "png" }))
local _ = png
```
This is simple left-to-right layout: no shaping (ligatures, Arabic joining, combining marks) and no line breaking.
## Load
```luau
local ttf = assert(F.font.load(ttfBytes)) -- TrueType
local woff = assert(F.font.load(woffBytes)) -- WOFF 1 (zlib tables)
local woff2 = assert(F.font.load(woff2Bytes)) -- WOFF 2 (Brotli + glyf / loca / hmtx transforms)
assert(woff.info.family == ttf.info.family and woff2.numGlyphs == ttf.numGlyphs)
assert(woff.meta.source.format == "woff" and woff2.meta.source.format == "woff2")
```
| Option | Format | Meaning |
|---|---|---|
| `index` | ttf | which font of a collection (`.ttc` / `.otc`), 0-based (default 0); `F.format("ttf").count` gives the count |
| `pages` | bmfont | the page images, if you have them already (page 0 first) |
| `loadPage` | bmfont | `function(file, page) -> Image | buffer | string`: loads a page lazily, the first time a glyph needs it |
## BMFont
A BMFont is a descriptor (text, XML or binary `.fnt`) plus page images that hold the glyphs. The descriptor names the
page files (`meta.pageFiles`). Metrics are in **pixels**: `unitsPerEm` is the size the font was baked at, and
`advance`, `kern`, `ascent` and `descent` are pixels too. `outline` returns `nil`. `rasterize(g)` crops the glyph from its page
as `alpha8` (it ignores `px`; `meta.scale = px / unitsPerEm` tells you how much to scale).
The pages load lazily: through `opts.loadPage`, through `opts.pages`, through `font:loadPages(loader)`, or, when the
font was loaded from a path, from the files next to the `.fnt`. Without any of these, `rasterize` returns `nil`.
```luau
local bm = assert(F.font.load(fntText, {
loadPage = function(file, page)
assert(file == "mini_0.png" and page == 0)
return fntPageBytes -- an Image, or the encoded bytes
end,
}))
assert(bm.meta.source.format == "bmfont" and bm.meta.lineHeight == 9)
local a, b = bm:glyphIndex(65), bm:glyphIndex(66)
assert(bm:advance(a) == 7 and bm:kern(a, b) == -1) -- pixels
local glyph = assert(bm:rasterize(b)) -- loads page 0 now
assert(glyph.format == "alpha8" and glyph.width == 6 and glyph.height == 7)
assert(buffer.readu8(glyph.pixels, 0) == 255) -- the B's outline
```
```luau
local bm = assert(F.font.load(fntText)) -- no loader: the pages are not available yet
assert(bm:rasterize(bm:glyphIndex(65)) == nil)
assert(bm:loadPages(function(file) return F.image.load(fntPageBytes) end))
assert(#bm.pages == 1 and bm:rasterize(bm:glyphIndex(65)))
```
<!-- doc:files -->
```luau
local bm = assert(F.font.load("assets/mini.fnt")) -- a path: mini_0.png is read from the same folder on demand
assert(bm:rasterize(bm:glyphIndex(65)))
```
### Baking a TTF into a BMFont
`F.format("bmfont").bake(font, opts)` rasterizes the characters of any outline font and packs them into pages. It
returns a BMFont `Font` whose `pages` are `rgba8` Images (white, coverage in alpha) and whose `meta.pageFiles` are
the page file names. Kerning pairs between the baked characters are kept, rounded to pixels.
| Option | Default | Meaning |
|---|---|---|
| `px` | 32 | pixels per em |
| `chars` | printable ASCII 32..126 | a string, or a list of code points |
| `pageSize` | smallest power of two that fits (up to 4096) | page width and height |
| `padding` | 1 | empty pixels around each glyph |
| `file` | `"font"` | page file name prefix: pages are `<file>_<n>.png` |
Save the descriptor with `F.save` (`variant` = `"text"`, `"xml"` or `"binary"`) and each page as a PNG under its
file name:
```luau
local ttf = assert(F.font.load(ttfBytes))
local baked = assert(F.format("bmfont").bake(ttf, { px = 16, chars = "Hello, world!", file = "ui" }))
local fnt = assert(F.saveString(baked)) -- the text descriptor (bake gives variant "text")
assert(string.find(fnt, 'page id=0 file="ui_0.png"', 1, true))
local files = { ["ui.fnt"] = fnt }
for i, page in baked.pages do
files[baked.meta.pageFiles[i]] = assert(F.save(page, nil, { format = "png" }))
end
local bin = assert(F.save(baked, nil, { variant = "binary" }))
local again = assert(F.font.load(bin, { pages = baked.pages }))
assert(again:advance(again:glyphIndex(string.byte("H"))) == baked:advance(baked:glyphIndex(string.byte("H"))))
```
`F.save(ttf, nil, { format = "bmfont", px = 16 })` bakes too, but returns only the descriptor: the page images are
not written anywhere. Use `bake` when you need the pages.
## Formats
| Format | Read | Write | Notes |
|---|---|---|---|
| ttf (`.ttf .otf .ttc .otc`) | yes | - | TrueType and CFF outlines, collections, `kern` and GPOS pair kerning |
| woff | yes | - | |
| woff2 | yes | - | |
| bmfont (`.fnt`) | yes | yes | text, XML and binary descriptors; `bake` from any outline font |
See [FORMATS.md](../FORMATS.md) for the capability matrix.
## Gotchas
- **No hinting, no shaping.** Glyphs are rendered from the outlines without hinting; there is no GSUB (ligatures,
contextual forms), no variable fonts (CFF2 / gvar return `UNSUPPORTED`) and no colour or bitmap glyphs.
- **`px` is the em size**, not the line height. The line height is `(ascent - descent + lineGap) * px / unitsPerEm`.
- **Units differ by kind.** Outline fonts measure in font units; BMFont in pixels at its baked size. Use
`font.unitsPerEm` for both: for a BMFont, `px / unitsPerEm` is the scale relative to the baked size.
- **Missing characters** map to glyph 0 (`.notdef`, usually an empty box); check `glyphIndex(cp) ~= 0`.
- **Fonts are read-only** except BMFont descriptors; `F.save(ttf)` returns `UNSUPPORTED` and suggests `bmfont`.
- **Per-glyph methods never throw**: a broken glyph gives `nil` from `outline` / `rasterize` (the reason is in
`font.meta.lastError`).
+249
View File
@@ -0,0 +1,249 @@
# Layered images (PSD, Aseprite)
Photoshop documents and Aseprite sprites load as a `Layered`: a canvas size and a tree of layers, each with its own
rgba8 [Image](image.md), position, opacity, blend mode and visibility. `F.ops.layers.flatten` composites the tree
into one Image; `F.save` writes PSD or Aseprite, layers included. Aseprite animations also carry every frame's tree.
```luau
local doc = assert(F.layered.load(psdBytes))
print(doc.width, doc.height, #doc.layers) -- 48 32 3
for i, layer in doc.layers do -- bottom to top
print(i, layer.name, layer.x, layer.y, layer.image.width, layer.image.height)
end
local flat = assert(F.ops.layers.flatten(doc)) -- an rgba8 Image, 48 x 32
local png = assert(F.save(flat, nil, { format = "png" }))
assert(flat.width == 48 and F.detect(png) == "png")
```
## The type
`Layered`
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"layered"` | |
| `width`, `height` | number | the canvas size in pixels |
| `layers` | `{ Layer }` | the layer tree, **bottom to top** (index 1 is drawn first); for an animation: frame 1's tree |
| `frames` | `{ { layers, delay } }?` | animations (Aseprite): every frame's tree and its delay in seconds; `frames[1].layers` is `layers` |
| `meta` | table | see below |
`Layer`
| Field | Type | Meaning |
|---|---|---|
| `name` | string | |
| `image` | `Image` | rgba8 pixels of the layer's own rectangle (straight alpha); a 0 x 0 Image for groups and empty layers |
| `x`, `y` | number | the image's top-left corner on the canvas, in pixels (may be negative or past the canvas) |
| `opacity` | number | 0..1 |
| `fillOpacity` | number? | 0..1, multiplied with `opacity` (PSD fill opacity, Aseprite cel opacity) |
| `blend` | string | a blend mode name (below) |
| `visible` | boolean | hidden layers are skipped by `flatten` unless `opts.hidden` |
| `children` | `{ Layer }?` | set on groups: the group's layers, bottom to top |
| `clip` | boolean? | a clipping layer: drawn only where the nearest non-clipping layer below it has alpha |
| `mask` | `LayerMask?` | a grey mask |
`LayerMask`
| Field | Type | Meaning |
|---|---|---|
| `image` | `Image` | `gray8` (or rgba8: its red channel); 255 shows the layer, 0 hides it |
| `x`, `y` | number | the mask's position on the canvas (not relative to the layer) |
| `default` | number | 0..255: the mask value outside its rectangle |
| `disabled` | boolean? | ignore the mask |
**Blend modes**: `normal`, `dissolve`, `darken`, `multiply`, `colorBurn`, `linearBurn`, `darkerColor`, `lighten`,
`screen`, `colorDodge`, `linearDodge` (also `add`), `lighterColor`, `overlay`, `softLight`, `hardLight`,
`vividLight`, `linearLight`, `pinLight`, `hardMix`, `difference`, `exclusion`, `subtract`, `divide`, `hue`,
`saturation`, `color`, `luminosity`. Unknown names composite as `normal`.
**Groups.** A group with `blend = "passThrough"` blends its children straight onto what is below (as Photoshop's
pass-through and Aseprite's plain groups). Any other blend first composites the children on their own transparent
canvas, then blends that result with the group's mode and opacity.
**Format extras.**
| Format | Extra fields |
|---|---|
| PSD | `meta.composite` (the merged image the file stores, an rgba8 Image), `meta.resources`, `meta.icc` |
| Aseprite | `meta.colorDepth` (32, 16, 8), `meta.palette` (`{ { r, g, b, a } }`), `meta.tags` (`{ name, from, to, direction, repeat, color }`, frames 1-based), `meta.transparentIndex`, `meta.pixelRatio`, `meta.grid`; per layer `flags`, `userData`, `zIndex`; on a frame's layer, `link` = the frame whose cel it reuses |
```luau
local sprite = assert(F.layered.load(asepriteBytes))
assert(#sprite.frames == 2 and sprite.frames[2].delay == 0.25) -- seconds
local hero2 = sprite.frames[2].layers[2]
assert(hero2.name == "Hero" and hero2.x == 12) -- the hero moved 8 px
assert(sprite.frames[2].layers[1].link == 1) -- the background cel is frame 1's
local walk = sprite.meta.tags[1]
assert(walk.name == "walk" and walk.from == 1 and walk.to == 2)
```
## Load
`F.load` detects both formats by their magic numbers. Everything converts to rgba8: PSD bitmap, greyscale, indexed,
CMYK, Lab and 16 / 32-bit documents; Aseprite grayscale and indexed sprites.
| Option | Format | Meaning |
|---|---|---|
| `layers` | PSD | `false` reads only the merged image (`meta.composite`), much faster; `layers` is then empty |
| `maxPixels` | both | refuse documents or layers larger than this (default 2^26) |
| `maxLayers` | PSD | default 10000 |
| `maxFrames` | Aseprite | default 65535 |
```luau
local quick = assert(F.layered.load(psdBytes, { layers = false }))
assert(#quick.layers == 0 and quick.meta.composite.width == 48)
local preview = quick.meta.composite -- Photoshop's own flattening
assert(preview.format == "rgba8")
```
`F.image.load` does not read layered formats; load them with `F.layered.load` (or `F.load`) and flatten.
## Flatten
`F.ops.layers.flatten(layered, opts?)` returns a new rgba8 Image of `width x height`:
| Option | Meaning |
|---|---|
| `frame` | the animation frame to flatten (1-based; default: `layered.layers`, which is frame 1) |
| `hidden` | `true` includes invisible layers |
| `background` | `{ r, g, b, a }` (0..255) painted under everything; default transparent |
`F.ops.layers.flattenFrames(layered, opts?)` flattens every frame into one animated Image (`img.frames`, delays
from the frames), ready to save as GIF, APNG or WebP. A Layered without frames gives a still image.
```luau
local sprite = assert(F.layered.load(asepriteBytes))
local f2 = assert(F.ops.layers.flatten(sprite, { frame = 2 }))
local r, g, b, a = F.ops.image.getPixel(f2, 13, 9) -- inside the hero on frame 2
assert(r == 220 and g == 50 and b == 50 and a == 255)
local anim = assert(F.ops.layers.flattenFrames(sprite))
assert(#anim.frames == 2 and anim.frames[2].delay == 0.25)
local gif = assert(F.save(anim, nil, { format = "gif" }))
assert(F.detect(gif) == "gif")
local onWhite = assert(F.ops.layers.flatten(sprite, { background = { 255, 255, 255, 255 } }))
assert(onWhite.width == 32)
```
`F.ops.layers.leaves(layers)` walks the non-group layers of a tree, bottom to top, with their group depth:
```luau
local doc = assert(F.load(psdBytes))
local names = {}
for layer, depth in F.ops.layers.leaves(doc.layers) do
table.insert(names, layer.name .. "@" .. depth)
end
assert(table.concat(names, " ") == "Sky@0 Box@0 Glow@0")
```
## Build and edit
`F.Types.Layered.new(w, h)` makes an empty document, `F.Types.Layered.layer(name, image, x?, y?)` a visible normal
layer at full opacity, and `F.Types.Layered.group(name, children)` a pass-through group. Layers are plain tables:
edit their fields directly.
```luau
local L = F.Types.Layered
local doc = L.new(32, 32)
local paper = assert(F.ops.image.new(32, 32))
F.ops.image.fill(paper, 240, 240, 230)
local ink = assert(F.ops.image.new(16, 16))
F.ops.image.fill(ink, 30, 60, 200)
local shade = assert(F.ops.image.new(32, 32))
F.ops.image.fill(shade, 255, 0, 0, 128)
local shadeLayer = L.layer("Shade", shade)
shadeLayer.clip = true -- only where Ink has alpha
shadeLayer.blend = "multiply"
local inkLayer = L.layer("Ink", ink, 8, 8)
inkLayer.opacity = 0.8
doc.layers = { L.layer("Paper", paper), L.group("Art", { inkLayer, shadeLayer }) }
local mask = assert(F.ops.image.new(32, 16, "gray8"))
F.ops.image.fill(mask, 255, 255, 255) -- show the top half
doc.layers[2].blend = "normal" -- an isolated group (masks need one, see Gotchas)
doc.layers[2].mask = { image = mask, x = 0, y = 0, default = 0 } -- hide the rest
local flat = assert(F.ops.layers.flatten(doc))
local _, _, _, a = F.ops.image.getPixel(flat, 0, 0)
assert(a == 255)
local r1 = F.ops.image.getPixel(flat, 12, 12) -- ink under the mask's visible half
local r2 = F.ops.image.getPixel(flat, 12, 20) -- ink masked out: paper shows
assert(r1 < 200 and r2 == 240)
```
## Save and convert
`F.save` writes PSD or Aseprite from any Layered (the source format by default, else `opts.format` or the
destination's extension). Flatten first to write an ordinary image format.
| Format | Writes | Options |
|---|---|---|
| PSD | 8-bit RGB (PSB when a side is over 30000 px): every layer as RLE RGBA channels, groups, masks, clipping, opacity, fill opacity, hidden flags, Unicode names, and a merged composite | `composite` (an Image to store as the merged image; default: the layers flattened) |
| Aseprite | RGBA sprites (grayscale / indexed when `depth` asks and the pixels fit), frame 1's layer tree, every frame's cels (linked where a frame reuses an Image), palette, tags | `depth` (32, 16, 8), `level` (zlib level, default 6) |
```luau
local L = F.Types.Layered
local doc = L.new(16, 16)
local a = assert(F.ops.image.new(16, 16))
F.ops.image.fill(a, 0, 128, 255)
local b = assert(F.ops.image.new(4, 4))
F.ops.image.fill(b, 255, 255, 0)
doc.layers = { L.layer("Back", a), L.layer("Dot", b, 6, 6) }
local psd = assert(F.save(doc, nil, { format = "psd" }))
local back = assert(F.load(psd))
assert(#back.layers == 2 and back.layers[2].name == "Dot" and back.layers[2].x == 6)
local ase = assert(F.save(doc, nil, { format = "aseprite" }))
assert(F.detect(ase) == "aseprite")
-- PSD -> Aseprite and back keeps the layers
local converted = assert(F.convert(psdBytes, "aseprite"))
assert(#assert(F.load(converted)).layers == 3)
```
An animation for Aseprite: give `frames` (each with its own tree and delay) and set `layers = frames[1].layers`.
Frames must have the same layer structure as frame 1.
```luau
local L = F.Types.Layered
local doc = L.new(8, 8)
local dot = assert(F.ops.image.new(2, 2))
F.ops.image.fill(dot, 255, 0, 0)
doc.frames = {}
for i = 1, 4 do
doc.frames[i] = { layers = { L.layer("Dot", dot, i, i) }, delay = 0.1 }
end
doc.layers = doc.frames[1].layers
local ase = assert(F.save(doc, nil, { format = "aseprite" }))
local back = assert(F.load(ase))
assert(#back.frames == 4 and back.frames[3].layers[1].x == 3)
```
## Formats
| Format | Read | Write | Notes |
|---|---|---|---|
| PSD / PSB | 1 / 8 / 16 / 32-bit, every colour mode, layers, groups, masks, clipping | 8-bit RGB | adjustment, type and smart-object layers keep only their pixels; no layer effects |
| Aseprite | RGBA, grayscale, indexed; frames, linked cels, tags, palette, user data | yes | tilemap layers are skipped (`meta.skipped`); slices not kept |
See [FORMATS.md](../FORMATS.md) for the capability matrix.
## Gotchas
- `layers[1]` is the **bottom** layer. Insert at the end to put a layer on top.
- Layer and mask positions are canvas coordinates; layer images can extend past the canvas and are clipped when
flattened.
- `meta.composite` is whatever merged image the writing application stored (some store a blank one when
"maximize compatibility" is off). `flatten` always works from the layers.
- Flattening is our own compositing (W3C blend formulas); PSD effects (shadows, strokes) and adjustment layers are
not rendered, so the result can differ from Photoshop's `meta.composite`.
- Linked Aseprite cels share one Image table between frames: copy it (`F.ops.image.copy`) before editing a single
frame.
- `flatten` ignores the mask of a `passThrough` group (Photoshop applies it). Give a masked group a real blend mode
such as `"normal"` to isolate it.
- Pixels are straight (not premultiplied) alpha, like every Image.
+266
View File
@@ -0,0 +1,266 @@
# Music
Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT) load as a **Module**:
the patterns, the order list, the samples and the instruments. Standard MIDI files load as a **Midi**: tracks of
timed events. Both render to the standard audio [Decoder](audio.md#decoder), so every music file can also be
played, analysed or saved as audio. MIDI renders through a SoundFont 2 bank, or through a small built-in set of
waveforms when you don't give one.
```luau
local song = assert(F.music.load(modBytes)) -- Module
print(song.format, song.title, song.channels) -- mod basic 4
local dec = song:render({ sampleRate = 22050 }) -- an audio Decoder (stereo f32)
local wav = assert(F.save(dec, nil, { format = "wav" })) -- streamed into a WAV
assert(F.detect(wav) == "wav")
local tune = assert(F.music.load(midiBytes)) -- Midi
local bank = assert(F.music.load(sf2Bytes)) -- a SoundFont
local audio = assert(F.ops.audio.toAudio(tune:render({ soundfont = bank })))
assert(audio.channels == 2 and audio.sampleRate == 44100)
```
## The types
### Module (MOD, S3M, XM, IT)
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"music"` | |
| `format` | string | `"mod"`, `"s3m"`, `"xm"` or `"it"`: the effect family the engine plays |
| `title` | string | |
| `channels` | number | pattern channels |
| `speed`, `tempo` | number | initial ticks per row, and BPM (a tick lasts `2.5 / tempo` seconds) |
| `order` | `{ number }` | the play order: 0-based pattern numbers; 254 = skip (`+++`), 255 = end (`---`) |
| `restart` | number | the 0-based order index the song loops back to |
| `patterns` | `{ Pattern }` | pattern `n` (as numbered in `order`) is `patterns[n + 1]` |
| `samples` | `{ Sample }` | the sample data, as f32 |
| `instruments` | `{ Instrument }` | XM / IT instruments (empty for MOD and S3M, where the instrument column names a sample) |
| `instrumentMode` | boolean | notes go through instrument keymaps (XM, IT with instruments) |
| `globalVolume`, `mixVolume` | number | 0..128 |
| `channelPan`, `channelVolume`, `channelMute` | `{ number }`, `{ number }`, `{ boolean }` | per channel: pan 0..256 (128 = centre), volume 0..64 |
| `linear` | boolean | linear frequency slides (XM / IT) rather than Amiga periods |
| `meta` | table | `meta.source.format` |
| `module:render(opts?)` | Decoder | plays the song once (see [Rendering](#rendering)) |
**Pattern layout.** A Pattern is `{ rows, data }`. `data` is a buffer of `rows * channels` cells of 5 bytes each,
row by row: note, instrument, volume column, effect, parameter. Row `r` (0-based), channel `c` (0-based) starts at
byte `(r * channels + c) * 5`. Notes are 0 (none), 1..120 (1 = C-0), 253 (note fade), 254 (note cut), 255 (key
off). The volume column and the effect bytes keep the file's own coding: MOD / XM effects 0..35, S3M / IT effects
1..26 (A = 1).
```luau
local m = assert(F.music.load(modBytes))
local p = m.patterns[m.order[1] + 1] -- the first pattern played
local notes = 0
for row = 0, p.rows - 1 do
for ch = 0, m.channels - 1 do
local at = (row * m.channels + ch) * 5
local note, instrument = buffer.readu8(p.data, at), buffer.readu8(p.data, at + 1)
if note > 0 and note <= 120 then
notes += 1
local _ = instrument -- a sample number for MOD / S3M
end
end
end
assert(buffer.len(p.data) == p.rows * m.channels * 5 and notes > 0)
```
**Samples.** Each Sample has `name`, `data` (f32, interleaved when `channels` is 2), `length` (frames),
`channels`, `bits` (8 or 16, what writers store), `loopStart` / `loopEnd` (frames, end exclusive), `loopType` (0 none,
1 forward, 2 ping-pong), `volume` 0..64, and the tuning fields of its format (`finetune` and `relativeNote` for MOD
/ XM, `c5speed` for S3M / IT).
```luau
local m = assert(F.music.load(modBytes))
for i, s in m.samples do
if s.length > 0 then
assert(buffer.len(s.data) == s.length * s.channels * 4)
print(i, s.name, s.length, s.loopType)
end
end
```
### Midi
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"midi"` | |
| `format` | number | SMF type 0, 1 or 2 |
| `division` | number | ticks per quarter note (negative: SMPTE time) |
| `tracks` | `{ { events, name? } }` | |
| `meta` | table | `tempos`, `timeSignatures`, `keySignatures`, `length` (seconds), `source` |
| `midi:render(opts?)` | Decoder | set by the decoder; for a hand-built Midi use `F.format("midi").render(midi, opts)` |
Each event is `{ tick, type, channel?, data?, meta? }`. `tick` is absolute (ticks since the start of the track,
not a delta). `channel` is 0..15. `data` holds the raw data bytes as numbers:
| `type` | `data` |
|---|---|
| `noteOn`, `noteOff` | `{ note, velocity }` (a `noteOn` with velocity 0 is kept as written) |
| `aftertouch` | `{ note, pressure }` |
| `controller` | `{ controller, value }` |
| `program` | `{ program }` |
| `channelPressure` | `{ pressure }` |
| `pitchBend` | `{ lsb, msb }` (centre 0, 64) |
| `meta` | the meta event's bytes; `meta` is its type (0x03 track name, 0x51 tempo, 0x58 time signature, ...) |
| `sysex`, `escape` | the bytes after the length |
```luau
local tune = assert(F.music.load(midiBytes))
assert(tune.format == 1 and tune.division == 480 and #tune.tracks == 2)
assert(tune.tracks[2].name == "Melody")
assert(tune.meta.tempos[1].bpm == 120 and tune.meta.length == 2)
local notes = {}
for _, ev in tune.tracks[2].events do
if ev.type == "noteOn" and ev.data[2] > 0 then
table.insert(notes, ev.data[1]) -- MIDI note numbers: 60 = middle C
end
end
assert(#notes == 8 and notes[1] == 60)
local midi = assert(F.format("midi"))
assert(midi.tickToSeconds(tune, 480) == 0.5) -- one quarter note at 120 BPM
```
### SoundFont
`F.music.load(sf2Bytes)` returns a SoundFont bank (`kind = "soundfont"`, read only): `info` (`name`, `engine`,
`comment`, ...), `presets` (each with `name`, `bank`, `preset`), `instruments`, `sampleHeaders` and `samples`.
Its only use is as `opts.soundfont` when rendering MIDI.
```luau
local bank = assert(F.music.load(sf2Bytes))
assert(bank.kind == "soundfont" and bank.info.name == "formats-luau test bank")
for _, p in bank.presets do
print(p.bank, p.preset, p.name) -- 0 0 Sine, ...
end
```
## Loading
| Call | Gives |
|---|---|
| `F.music.load(src, opts?)` / `F.load` | a Module, a Midi or a SoundFont |
| `F.music.open(src, opts?)` / `F.open` | the rendered audio Decoder (decode and render options together) |
`F.audio.open` and `F.audio.load` do not take music files; use `F.music.open`, or `F.open`, which detects any
category.
| Option | Formats | Meaning |
|---|---|---|
| `maxBytes` | mod, xm, s3m, it | refuse more sample data (f32 bytes) |
| `strict` | midi | a truncated track is an error (default: keep the events read, `meta.truncated = true`) |
| `maxEvents` | midi | default 2^24 |
```luau
local dec = assert(F.music.open(midiBytes, { soundfont = sf2Bytes, sampleRate = 22050 }))
assert(dec.sampleRate == 22050 and dec.channels == 2)
assert(math.abs(dec.duration - 3) < 0.01) -- 2 s of notes + the 1 s release tail
local d2 = assert(F.open(modBytes)) -- any category: a Decoder for a module
assert(d2.channels == 2)
```
## Rendering
`render(opts?)` returns a Decoder (stereo f32). Read it block by block, convert it with `F.ops.audio.toAudio`, or
save it with `F.save(decoder, dest, { format = ... })`, which encodes as it reads.
| Option | Applies to | Meaning |
|---|---|---|
| `sampleRate` | both | default 44100 |
| `soundfont` | MIDI | a SoundFont value, or SF2 bytes (buffer / string); default the built-in waveforms |
| `gain` | MIDI | linear output gain, default 0.5 |
| `tail` | MIDI | seconds rendered after the last event (release tails), default 1 |
| `maxVoices` | MIDI | default 256 |
| `interpolation` | modules | `"linear"` (default) or `"none"` |
| `stereoSeparation` | modules | 0..200 % (default 100; 200 makes MOD's Amiga panning hard left / right) |
| `loop` | modules | keep playing past the end (`frames` / `duration` still give one pass) |
| `maxDuration` | modules | seconds, default 3600 |
```luau
local tune = assert(F.music.load(midiBytes))
local plain = tune:render() -- built-in waveforms
local sf = tune:render({ soundfont = sf2Bytes, gain = 0.8, tail = 0.5 })
assert(plain.frames == 3 * 44100 and sf.frames == 2.5 * 44100) -- 2 s of notes + the tail
local flac = assert(F.save(sf, nil, { format = "flac" }))
assert(F.detect(flac) == "flac")
```
A module's `frames` and `duration` come from one pass through the order list, with song loops detected:
```luau
local song = assert(F.music.load(modBytes))
local dec = song:render({ sampleRate = 22050, stereoSeparation = 200 })
assert(dec.duration > 1 and dec.frames == math.floor(dec.duration * 22050 + 0.5))
local first = assert(F.ops.audio.trim(F.ops.audio.toAudio(dec), 0, 1)) -- the first second as an Audio
assert(first.frames == 22050)
```
## Building and saving
A Midi is plain data: build one with `F.Types.Midi.new(division?)` and save it as `.mid`. Events need absolute
ticks; the writer sorts nothing, so keep each track's events in tick order. A track's `name` is read from its
track-name meta event (0x03); the writer writes events only, so put the name in an event.
```luau
local m = F.Types.Midi.new(480) -- 480 ticks per quarter note, SMF type 1
local events = {
{ tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- tempo: 500000 us per quarter
{ tick = 0, type = "meta", meta = 0x03, data = { string.byte("Arpeggio", 1, -1) } }, -- the track name
{ tick = 0, type = "program", channel = 0, data = { 0 } },
}
for i, note in { 60, 64, 67, 72 } do
table.insert(events, { tick = (i - 1) * 240, type = "noteOn", channel = 0, data = { note, 100 } })
table.insert(events, { tick = i * 240, type = "noteOff", channel = 0, data = { note, 0 } })
end
table.insert(m.tracks, { events = events })
local bytes = assert(F.save(m, nil, { format = "midi" }))
local back = assert(F.music.load(bytes))
assert(back.tracks[1].name == "Arpeggio" and back.meta.length == 1) -- 4 eighth notes at 120 BPM
local dec = assert(F.format("midi").render(m, { soundfont = sf2Bytes })) -- render without saving first
assert(dec.frames > 0)
```
Modules save as MOD or XM. MOD writes the 31-sample format; XM modules convert to MOD when they fit (one sample per
instrument, effects 0..F, 64-row patterns). S3M and IT are read only.
```luau
local song = assert(F.music.load(modBytes))
local mod = assert(F.save(song)) -- the source format: MOD
local xm = assert(F.save(song, nil, { format = "xm", tracker = "my tool" }))
assert(F.detect(mod) == "mod" and F.detect(xm) == "xm")
local _, err = F.save(song, nil, { format = "it" })
assert(err.code == F.Err.UNSUPPORTED) -- read only
```
| Format | Encoder options |
|---|---|
| midi | `runningStatus` (default true: the bytes python's mido writes) |
| xm | `tracker` (the tracker name field) |
| mod | none |
## Formats
| Format | Read | Write | Value |
|---|---|---|---|
| mod (MOD, 4..32 channels) | yes | yes | Module |
| xm | yes | yes | Module |
| s3m, it | yes | - | Module |
| midi (.mid, .kar, RMID) | yes | yes (SMF) | Midi |
| sf2 | yes | - | SoundFont |
See [FORMATS.md](../FORMATS.md) for each format's capabilities.
## Gotchas
- **Saving music as audio needs a render.** `F.save(song, nil, { format = "wav" })` and `F.convert(modBytes, "wav")`
fail with `UNKNOWN_FORMAT` ("no format named wav for music"). Render first:
`F.save(song:render(), nil, { format = "wav" })`.
- `F.audio.open(midiBytes)` fails with `UNKNOWN_FORMAT`; use `F.music.open` or `F.open`.
- `track.name` is not written: add a meta 0x03 event to name a track.
- A Midi you build yourself has no `render` method; `F.format("midi").render(midi, opts)` renders it.
- MIDI event ticks are absolute, not the deltas stored in the file. Pitch bend `data` is `{ lsb, msb }`, not a
signed value: `(msb * 128 + lsb) - 8192`.
- Without a SoundFont, MIDI plays on simple built-in waveforms, which is fine for testing but not General MIDI.
SF3 banks (Ogg-compressed samples) are not supported.
- Pattern cells keep the file's own effect numbering, which differs between MOD / XM (0..35) and S3M / IT (1..26).
- A module's `duration` is one pass. `render({ loop = true })` keeps playing past it.
+166
View File
@@ -0,0 +1,166 @@
# Playlists
M3U / M3U8 (including HLS), PLS and XSPF load as one `Playlist`: a list of entries with a location, an optional
title and duration, and whether a player can fetch it. Relative locations resolve against the playlist's own URL
when you pass it, and every entry is classified as playable (an `http(s)` URL) or not, with the reason. All three
formats are writable, so converting between them is a load and a save.
```luau
local pl = assert(F.playlist.load(m3uText, { baseUrl = "https://example.com/lists/mix.m3u" }))
print(pl.format, pl.title, #pl.entries) -- m3u Docs Mix 3
for _, e in pl.entries do
print(e.url, e.title, e.duration, e.playable)
end
-- https://example.com/music/first.mp3 Ada - First Song 215 true
-- http://radio.example/stream Live Radio nil true
-- https://example.com/lists/songs/local.flac nil nil true
local pls = assert(F.saveString(pl, { format = "pls" }))
```
## The type
`Playlist`:
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"playlist"` | |
| `format` | string | `"m3u"`, `"hls"` (an M3U8 with HLS tags), `"pls"` or `"xspf"` |
| `entries` | `{ PlaylistEntry }` | in playlist order |
| `warnings` | `{ string }` | what was odd but readable (an unresolvable location, a `NumberOfEntries` mismatch, ...), with line numbers |
| `title` | string? | M3U `#PLAYLIST:`, XSPF `<title>` (PLS has none) |
| `hls` | table? | HLS playlists only (below) |
| `meta` | table | `source.format`; XSPF: `creator`, `annotation`, `info`, `location`, `identifier`, `image`, `date` |
`PlaylistEntry`:
| Field | Type | Meaning |
|---|---|---|
| `url` | string | the location, resolved against `opts.baseUrl` (or XSPF `xml:base`) when relative |
| `title` | string? | `#EXTINF` title, PLS `TitleN`, XSPF `<title>` |
| `duration` | number? | seconds; `nil` when unknown (`-1` in M3U / PLS) |
| `playable` | boolean | an `http` / `https` URL a player can fetch |
| `reason` | string? | why not playable: `"local path"`, `"relative path without a base URL"`, `"scheme ftp"`, ... |
| `bandwidth`, `codecs`, `attributes` | | HLS master playlists: `BANDWIDTH`, `CODECS` and the whole attribute list (`RESOLUTION`, ...) |
| `byteRange` | `{ length, offset? }`? | HLS media playlists: `EXT-X-BYTERANGE` |
| `creator`, `album`, `annotation`, `info`, `image`, `trackNum`, `locations` | | XSPF tracks (`locations`: every `<location>`; `url` is the first) |
## Load
| Option | Meaning |
|---|---|
| `baseUrl` | the playlist's own URL (or a Windows path): relative entries resolve against it (RFC 3986) |
| `maxBytes` | refuse bigger files (default 64 MB) |
Text decoding is forgiving: a UTF-8 BOM, CRLF or CR line ends, and Windows-1252 text (old M3U files) all work.
```luau
local pl = assert(F.playlist.load(m3uText)) -- no base URL: the relative entry is not playable
local last = pl.entries[3]
assert(last.url == "songs/local.flac" and not last.playable)
assert(last.reason == "relative path without a base URL")
assert(#pl.warnings == 1)
print(pl.warnings[1]) -- line 7: relative path without a base URL: songs/local.flac
local radio = assert(F.playlist.load(plsText))
assert(radio.format == "pls" and radio.entries[1].title == "Radio One" and radio.entries[1].duration == nil)
assert(radio.entries[2].duration == 187)
local spiff = assert(F.playlist.load(xspfText))
local track = spiff.entries[1]
assert(spiff.format == "xspf" and track.creator == "Ada" and track.duration == 215) -- XSPF stores milliseconds
```
### HLS
An M3U8 with HLS tags loads with `format = "hls"` and an `hls` table. A *master* playlist lists variant streams; a
*media* playlist lists segments.
| `hls` field | Meaning |
|---|---|
| `master` | true for a master playlist (variants), false for a media playlist (segments) |
| `targetDuration`, `mediaSequence` | media: `EXT-X-TARGETDURATION`, `EXT-X-MEDIA-SEQUENCE` |
| `endList` | media: `EXT-X-ENDLIST` seen (false = live, the playlist grows) |
| `encrypted` | an `EXT-X-KEY` with a method other than NONE |
| `totalDuration` | media: the sum of the segment durations, seconds |
| `segmentFormat` | media: the segments' common extension (`"mp3"`, `"ts"`, `"aac"`, ...) or `"mixed"` |
Segments that are MPEG-TS, AAC or fragmented MP4 are flagged unplayable (`reason` says so): the classification is
about what a simple player can stream as a file, not what the library can decode.
```luau
local master = assert(F.playlist.load(hlsText, { baseUrl = "https://cdn.example/v/master.m3u8" }))
assert(master.format == "hls" and master.hls.master)
for _, v in master.entries do
print(v.bandwidth, v.attributes.RESOLUTION, v.url)
end
-- 800000 640x360 https://cdn.example/v/low/index.m3u8
-- 2400000 1280x720 https://cdn.example/v/high/index.m3u8
assert(master.entries[1].codecs == "avc1.4d401e,mp4a.40.2")
local media = assert(F.playlist.load(
"#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXTINF:4,\nseg1.mp3\n#EXTINF:3.5,\nseg2.mp3\n#EXT-X-ENDLIST\n",
{ format = "m3u8", baseUrl = "https://cdn.example/audio/list.m3u8" }))
assert(not media.hls.master and media.hls.endList and media.hls.segmentFormat == "mp3")
assert(media.hls.totalDuration == 7.5 and media.entries[2].url == "https://cdn.example/audio/seg2.mp3")
```
## Edit, save and convert
Entries are plain tables: filter, reorder or add them, then save. The format comes from `opts.format`, the
destination's extension, or the format the playlist was loaded from (as everywhere, see the [guide](README.md#saving)).
```luau
local pl = assert(F.playlist.load(m3uText, { baseUrl = "https://example.com/lists/mix.m3u" }))
local keep = {}
for _, e in pl.entries do
if e.duration then -- drop the live stream (unknown length)
table.insert(keep, e)
end
end
table.insert(keep, { url = "https://example.com/music/bonus.ogg", title = "Bonus", duration = 61, playable = true })
pl.entries = keep
local m3u = assert(F.saveString(pl)) -- M3U8 text, the source format
assert(string.find(m3u, "#EXTINF:61,Bonus\nhttps://example.com/music/bonus.ogg", 1, true))
local pls = assert(F.saveString(pl, { format = "pls" }))
assert(string.find(pls, "NumberOfEntries=2", 1, true))
local xspf = assert(F.saveString(pl, { format = "xspf" }))
assert(F.playlist.load(xspf).entries[2].duration == 61)
```
A playlist built from scratch needs `kind = "playlist"`, `entries` and a format to save as:
```luau
local pl = { kind = "playlist", format = "m3u", title = "New", entries = {
{ url = "https://example.com/a.mp3", title = "A", duration = 120, playable = true },
}, warnings = {}, meta = {} }
local text = assert(F.saveString(pl, { format = "m3u" }))
assert(string.sub(text, 1, 7) == "#EXTM3U")
```
| Writer | Writes |
|---|---|
| m3u | `#EXTM3U`, `#PLAYLIST:` (opts.`title` overrides), `#EXTINF:<seconds>,<title>`, the locations |
| pls | `[playlist]`, `FileN` / `TitleN` / `LengthN` (`-1` for unknown), `NumberOfEntries`, `Version=2` |
| xspf | XSPF version 1: title, track location / title / creator / album / annotation / info / image / trackNum / duration |
## Formats
| Format | Extensions | Read | Write |
|---|---|---|---|
| m3u | `.m3u .m3u8` | yes, including HLS master and media playlists | yes (plain M3U8; HLS tags are not written) |
| pls | `.pls` | yes | yes |
| xspf | `.xspf` | yes | yes |
See [FORMATS.md](../FORMATS.md).
## Gotchas
- **Pass `baseUrl`** for playlists fetched from the web: otherwise relative entries keep their text and are not
playable.
- **HLS round trips lose the HLS tags.** Saving an HLS playlist writes a plain M3U8 (locations, `#EXTINF`); variant
attributes, keys and byte ranges are not written.
- **M3U durations are written as whole seconds** (`#EXTINF:4,` for 3.5 s).
- **`F.detect` says `m3u`** for HLS text; `pl.format` tells you whether HLS tags were found.
- **Local paths** (`C:\Music\a.mp3`, `/home/me/a.mp3`, `file:` URLs) are kept as written and flagged unplayable; the
library never reads the files a playlist points to.
+135
View File
@@ -0,0 +1,135 @@
# Subtitles
SRT, WebVTT and ASS / SSA files load as one **Subtitles** value: a list of timed cues, plus named styles where the
format has them. Cue text uses one small markup for all three (`<i>`, `<b>`, `<u>`, `<s>`, and line breaks as
`\n`), so converting between the formats keeps italics and line breaks.
```luau
local subs = assert(F.subtitle.load(srtText))
local cue = subs.cues[1]
print(cue.start, cue.stop, cue.text) -- 0.5 2 Hello, <i>world</i>.
local vtt = assert(F.saveString(subs, { format = "vtt" }))
assert(string.sub(vtt, 1, 6) == "WEBVTT")
```
## The type
`F.Types.Subtitles.new()` makes an empty one.
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"subtitles"` | |
| `cues` | `{ Cue }` | in file order |
| `styles` | `{ [name]: { [field]: string } }` | ASS styles by name; empty for SRT and WebVTT |
| `meta` | table | `source`, and each format's extras (below) |
| Cue field | Type | Meaning |
|---|---|---|
| `start`, `stop` | number | seconds |
| `text` | string | the shared markup: `<i>`, `<b>`, `<u>`, `<s>` (SRT also `<font ...>`, WebVTT `<c.class>` / `<v Name>` as written); lines separated by `"\n"` |
| `id` | string? | SRT index, WebVTT cue identifier |
| `style` | string? | ASS: the style name |
| `settings` | string? | WebVTT cue settings (`"align:start"`), SRT coordinates, as written |
ASS cues also keep `layer`, `name`, `marginL`, `marginR`, `marginV`, `effect`, and `raw`: the original text with its
override blocks (`{\pos(...)}`, karaoke, ...), which the writer uses when `text` is unchanged.
| Format | `meta` extras |
|---|---|
| ASS | `scriptInfo` (`Title`, `PlayResX`, ...), `scriptInfoOrder`, `styleFormat`, `styleOrder`, `eventFormat`, `comments`, `sections` (other sections, verbatim) |
| WebVTT | `header`, `notes`, `css` (STYLE blocks), `regions` |
```luau
local s = assert(F.subtitle.load(assText))
assert(#s.cues == 2 and s.cues[2].style == "Sign")
assert(s.cues[2].text == "A sign\nwith two lines") -- \N became a line break
assert(s.styles.Sign.Fontsize == "16" and s.styles.Default.PrimaryColour == "&H00FFFFFF")
assert(s.meta.scriptInfo.PlayResX == "640")
local v = assert(F.subtitle.load(vttText))
assert(v.cues[1].id == "intro" and v.cues[1].settings == "align:start")
```
## Loading
`F.subtitle.load(src, opts?)` or `F.load(src)`; text with a BOM, CRLF or CR line ends is fine. The one option is
`maxBytes` (default 64 MB). SRT has no magic number, but its timing lines are recognised.
```luau
assert(F.detect(srtText) == "srt" and F.detect(vttText) == "vtt" and F.detect(assText) == "ass")
local s = assert(F.load(srtText))
assert(s.kind == "subtitles" and s.cues[2].text == "Second line\nspans two rows.")
```
## Finding the cue at a time
```luau
local s = assert(F.subtitle.load(srtText))
local function cueAt(t: number): string?
for _, c in s.cues do
if t >= c.start and t < c.stop then
return c.text
end
end
return nil
end
assert(cueAt(1) == "Hello, <i>world</i>." and cueAt(2.2) == nil)
local plain = string.gsub(cueAt(1) :: string, "<[^>]+>", "") -- strip the markup for a plain label
assert(plain == "Hello, world.")
```
## Editing, saving, converting
Cues are plain tables: shift, edit or add them, then save. The format comes from `opts.format`, the destination's
extension, or the source format.
```luau
local s = assert(F.subtitle.load(srtText))
for _, c in s.cues do
c.start += 1.5 -- delay everything by 1.5 s
c.stop += 1.5
end
table.insert(s.cues, { start = 6, stop = 7.5, text = "<b>The end</b>" })
local srt = assert(F.saveString(s)) -- SRT again; cues are renumbered from 1
assert(string.find(srt, "00:00:02,000 --> 00:00:03,500", 1, true))
local ass = assert(F.saveString(s, { format = "ass" })) -- markup becomes {\b1}...{\b0}
assert(string.find(ass, "{\\b1}The end{\\b0}", 1, true))
local fresh = F.Types.Subtitles.new()
table.insert(fresh.cues, { start = 1, stop = 2.5, text = "Hi" })
assert(F.saveString(fresh, { format = "srt" }) == "1\n00:00:01,000 --> 00:00:02,500\nHi\n\n")
```
| Format | Writes | Options |
|---|---|---|
| srt | cues renumbered, times to the millisecond | `crlf` |
| vtt | header, STYLE / REGION blocks, cues (times to the millisecond) | |
| ass | an ASS v4.00+ script with the source's styles (a `Default` style when there are none); times to the centisecond | `crlf` |
Converting ASS to SRT or WebVTT drops the styles and anything the markup cannot hold (positions, colours, karaoke);
converting to ASS gives every cue without a style the `Default` style.
```luau
local srt = assert(F.convert(assText, "srt"))
local back = assert(F.subtitle.load(srt))
assert(back.cues[1].text == "Hello, <i>world</i>." and back.cues[2].style == nil)
```
## Formats
| Format | Read | Write | Styles |
|---|---|---|---|
| srt | yes | yes | no |
| vtt (WebVTT) | yes | yes | CSS kept in `meta.css` |
| ass / ssa | yes | yes (ASS v4.00+) | yes |
See [FORMATS.md](../FORMATS.md). Text subtitle tracks inside Matroska files are read by `F.format("mkv").subtitles`
([video.md](video.md)).
## Gotchas
- Times are seconds as floating point numbers; writers round them (SRT / WebVTT to the millisecond, ASS to the
centisecond).
- Style fields are strings as written in the file (`Fontsize = "16"`, colours as `&HAABBGGRR`). Nothing is rendered.
- WebVTT cue text cannot hold blank lines or `-->`: the writer drops the blank lines and escapes the arrow.
- Tags in SRT text are not validated; unknown ones pass through as text.
- The cue list is not sorted for you. Sort by `start` after inserting cues out of order if the player needs it.
+214
View File
@@ -0,0 +1,214 @@
# Tile maps (Tiled TMX / TMJ)
[Tiled](https://www.mapeditor.org) maps load as a `TileMap`: the map grid, its tilesets, and a list of layers
(tile layers, object layers, image layers and groups) with Tiled's custom properties. The XML flavour (TMX) and the
JSON flavour (TMJ) decode to the same value, so converting between them is a load and a save. Standalone tileset
files (TSX / TSJ) load too.
```luau
local map = assert(F.load(tmxText))
print(map.width, map.height, map.tileWidth, map.tileHeight) -- 4 3 16 16
local ground = map.layers[1]
local gid = ground.data[1 + 0 * map.width + 2] -- the tile at column 2, row 0
assert(gid == 2)
local json = assert(F.saveString(map, { format = "tmj" }))
assert(F.detect(json, { name = "level.tmj" }) == "tiled")
```
## The type
`TileMap`
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"tilemap"` | |
| `width`, `height` | number | the map size **in tiles** (for infinite maps: the bounds Tiled stored) |
| `tileWidth`, `tileHeight` | number | the grid cell size in pixels |
| `orientation` | string | `"orthogonal"`, `"isometric"`, `"staggered"`, `"hexagonal"` |
| `renderOrder` | string | `"right-down"`, `"right-up"`, `"left-down"`, `"left-up"` |
| `infinite` | boolean | tile layers use `chunks` instead of `data` |
| `tilesets` | `{ Tileset }` | sorted by `firstGid` |
| `layers` | `{ TileLayer }` | in Tiled's order: the first is drawn first (at the bottom) |
| `properties` | `{ [name]: value }` | custom properties (below) |
| `propertyTypes` | `{ [name]: type }?` | the Tiled type of each non-string property |
| `meta` | table | `source.format` (`"tmx"` or `"tmj"`), `tileset = true` for a TSX / TSJ file |
Other Tiled map attributes keep their Tiled names in camel case: `version`, `tiledVersion`, `class`,
`nextLayerId`, `nextObjectId`, `backgroundColor`, `parallaxOriginX` / `Y`, `hexSideLength`, `staggerAxis`,
`staggerIndex`.
`Tileset`
| Field | Type | Meaning |
|---|---|---|
| `firstGid` | number | the gid of the tileset's tile 0 |
| `name`, `class` | string | |
| `tileWidth`, `tileHeight` | number | pixels |
| `columns`, `count` | number | tiles per row of the image, total tiles |
| `spacing`, `margin` | number | pixels between tiles / around the image |
| `imageSource` | string? | the tileset image's path **as written in the file** (relative to the map) |
| `imageWidth`, `imageHeight` | number? | |
| `image` | `Image?` | never set by the decoder: load the image yourself (below) |
| `source` | string? | an external tileset (`.tsx` / `.tsj`): only `firstGid` and `source` are known |
| `tiles` | `{ { id, class, properties, imageSource?, animation?, objectGroup? } }` | per-tile data; `id` is 0-based within the tileset; `animation = { { tileId, duration } }` with durations in **milliseconds** |
| `tileOffset`, `objectAlignment`, `transparentColor`, `properties` | | as in Tiled |
`TileLayer` (every layer)
| Field | Type | Meaning |
|---|---|---|
| `type` | string | `"tiles"`, `"objects"`, `"image"` or `"group"` |
| `id`, `name`, `class` | | |
| `visible`, `locked` | boolean | |
| `opacity` | number | 0..1 |
| `offsetX`, `offsetY`, `parallaxX`, `parallaxY`, `tintColor` | | as in Tiled (pixels, factors, `"#rrggbb"` / `"#aarrggbb"`) |
| `properties`, `propertyTypes` | | custom properties |
By `type`:
| Type | Fields |
|---|---|
| `"tiles"` | `width`, `height` (tiles); `data` = `width * height` gids, row by row from the top-left (`data[1 + x + y * width]`, `x` and `y` 0-based); or `chunks = { { x, y, width, height, data } }` on infinite maps (`x`, `y` in tiles, may be negative); `encoding` / `compression` as stored |
| `"objects"` | `objects`, `drawOrder` (`"topdown"` / `"index"`), `color` |
| `"image"` | `imageSource`, `imageWidth`, `imageHeight`, `repeatX`, `repeatY`, `transparentColor` |
| `"group"` | `layers` (the child layers) |
An object: `id`, `name`, `class`, `x`, `y`, `width`, `height` (pixels), `rotation` (degrees clockwise), `visible`,
`shape` (`"rectangle"`, `"ellipse"`, `"point"`, `"polygon"`, `"polyline"`, `"text"`), `points` (`{ { x, y } }`,
relative to the object, for polygons and polylines), `text` (`{ text, fontFamily, pixelSize, color, ... }`), `gid`
(tile objects), `template`, `properties`.
**Custom properties** are plain values: strings, numbers (`int`, `float`), booleans, colours as `"#aarrggbb"`
strings, files as path strings, objects as object ids, and `class` properties as `{ class, properties,
propertyTypes }`. `propertyTypes` remembers the Tiled type of each non-string property, so a save writes the same
types back.
```luau
local map = assert(F.load(tmxText))
assert(map.properties.music == "cave.ogg" and map.properties.gravity == 9.8)
assert(map.propertyTypes.gravity == "float")
local ts = map.tilesets[1]
assert(ts.firstGid == 1 and ts.columns == 4 and ts.imageSource == "tiles.png")
local things = map.layers[2]
assert(things.type == "objects")
local spawn = things.objects[1]
assert(spawn.shape == "point" and spawn.class == "Spawn" and spawn.x == 24 and spawn.y == 16)
```
## Gids and flip flags
A gid (global tile id) of 0 is an empty cell. Otherwise the low 28 bits name a tile across all tilesets: the tile
belongs to the tileset with the largest `firstGid` not above it, and its index there is `gid - firstGid`. The top
bits are flags, kept as they are in `data`:
| Bit | Value | Meaning |
|---|---|---|
| 31 | `0x80000000` | flipped horizontally |
| 30 | `0x40000000` | flipped vertically |
| 29 | `0x20000000` | flipped diagonally (with the other two: rotations) |
| 28 | `0x10000000` | rotated 120 degrees (hexagonal maps) |
```luau
local map = assert(F.load(tmjText))
local raw = map.layers[1].data[4] -- 2147483652 = 0x80000004
local FLAGS = 0xF0000000
local gid = bit32.band(raw, bit32.bnot(FLAGS))
local flipH = bit32.btest(raw, 0x80000000)
assert(gid == 4 and flipH)
-- the tileset and the tile's pixel rectangle in the tileset image
local function lookup(m, g)
local found = nil
for _, t in m.tilesets do
if t.firstGid <= g then
found = t
end
end
local index = g - found.firstGid
local col, row = index % found.columns, index // found.columns
return found, (found.margin or 0) + col * (found.tileWidth + (found.spacing or 0)),
(found.margin or 0) + row * (found.tileHeight + (found.spacing or 0))
end
local ts, sx, sy = lookup(map, gid)
assert(ts.name == "t" and sx == 8 and sy == 8) -- tile 3 of a 2-column tileset
```
## Tileset images
Tilesets keep their image as a path (`imageSource`), relative to the map file: a map format never decodes images.
Read the image yourself and attach it:
<!-- doc:files -->
```luau
local mapPath = "assets/level.tmx"
local map = assert(F.load(mapPath))
local dir = string.match(mapPath, "^(.*/)") or ""
for _, ts in map.tilesets do
if ts.imageSource and F.host.exists(dir .. ts.imageSource) then
ts.image = assert(F.image.load(dir .. ts.imageSource))
end
end
assert(map.tilesets[1].image.width == 64)
```
On Roblox and in the luau CLI, fetch the bytes your own way and call `F.image.load(bytes)`. External tilesets
(`ts.source`) work the same way: `F.load(dir .. ts.source)` gives a TileMap with `meta.tileset = true` and the
tileset in `tilesets[1]`.
## Load and save
`F.load` detects TMX (`<map`) and TMJ (a JSON object with `"type": "map"` or Tiled's keys). JSON without those keys
is plain [data](data.md); pass `{ format = "tiled" }` or a `.tmj` name to force it. Option: `maxBytes` (default
256 MB).
`F.save` writes the source's flavour unless `opts.format` says otherwise:
| Option | Meaning |
|---|---|
| `format` | `"tmx"` / `"tsx"` (XML) or `"tmj"` / `"tsj"` / `"json"` (JSON) |
| `encoding` | tile data: `"csv"` (TMX default), `"base64"`, `"xml"` (TMX only); TMJ writes arrays unless `"base64"` |
| `compression` | for base64 data: `nil`, `"zlib"` or `"gzip"` |
| `level` | deflate level for compressed data (default 6) |
| `indent` | spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON) |
```luau
local map = assert(F.load(tmxText))
local tmj = assert(F.saveString(map, { format = "tmj", indent = 0 }))
local back = assert(F.load(tmj, { format = "tiled" }))
assert(back.layers[1].data[12] == 6 and back.properties.gravity == 9.8)
local packed = assert(F.saveString(map, { encoding = "base64", compression = "zlib" }))
assert(string.find(packed, 'compression="zlib"', 1, true))
```
Build a map from scratch with `F.Types.TileMap.new(width, height, tileWidth, tileHeight)`:
```luau
local map = F.Types.TileMap.new(3, 2, 16, 16)
table.insert(map.tilesets, { name = "terrain", firstGid = 1, tileWidth = 16, tileHeight = 16, columns = 8,
count = 64, imageSource = "terrain.png", imageWidth = 128, imageHeight = 128 })
table.insert(map.layers, { type = "tiles", name = "floor", width = 3, height = 2, visible = true, opacity = 1,
properties = {}, data = { 1, 1, 2, 0, 9, bit32.bor(9, 0x80000000) } })
local tmx = assert(F.saveString(map, { format = "tmx" }))
local back = assert(F.load(tmx))
assert(back.layers[1].data[6] == 0x80000009)
```
## Formats
| Format | Read | Write | Notes |
|---|---|---|---|
| TMX / TSX | yes | yes | CSV, base64 (raw, zlib, gzip) and `<tile>` data; zstd data returns `UNSUPPORTED` |
| TMJ / TSJ | yes | yes | |
Both are the `tiled` format in [FORMATS.md](../FORMATS.md). Wang sets and terrains are dropped.
## Gotchas
- `data` is 1-based in Luau but cells are 0-based: cell `(x, y)` is `data[1 + x + y * width]`.
- Always mask the flag bits before looking a gid up; a flipped tile's raw gid is over 2^31.
- Infinite maps have no `data` on their tile layers, only `chunks`.
- Object `y` is the bottom-left corner for tile objects (`gid` set) and the top-left for everything else (Tiled's
convention).
- Tile animation durations are milliseconds (Tiled's unit), unlike the seconds used elsewhere in the library.
- Colours are strings (`"#rrggbb"` or `"#aarrggbb"`), not tables.
+305
View File
@@ -0,0 +1,305 @@
# Video
A video file opens as a **VideoDecoder**: frames come out one at a time, as Images, with their presentation time.
Underneath sits a **Demuxer**: the container's tracks and their compressed packets. Video tracks decode through a
codec registry (H.264, VP8, MPEG-1, Motion-JPEG, raw), and the first audio track opens as an audio
[Decoder](audio.md#decoder). Animated GIF, APNG and WebP open as videos too. [docs/video.md](../video.md) covers the
internals and how to add a codec.
```luau
local v = assert(F.video.open(mp4Bytes)) -- H.264 + AAC
print(v.format, v.codec, v.width, v.height, v.frameRate, v.frames) -- mp4 h264 64 48 10 10
local f = assert(v:nextFrame()) -- the first frame
local rgba = v:toRGBA(f) -- yuv420p -> rgba8 Image
local png = assert(F.save(rgba, nil, { format = "png" }))
local avi = assert(F.save(v, nil, { format = "avi" })) -- re-encoded as Motion-JPEG + PCM
assert(F.detect(png) == "png" and F.detect(avi) == "avi")
```
## The types
Times: `VideoFrame.pts` / `duration`, `seek` and every `duration` field are **seconds**. Packet `pts` / `dts` /
`duration` are integer **ticks** of their track's `timescale` (exact, for remuxing): seconds = ticks / timescale.
### VideoDecoder
`F.video.open(src)`, `F.open(src)` and `F.load(src)` return one (`F.load` does not decode anything up front).
| Member | Meaning |
|---|---|
| `kind` | `"video"` |
| `format` | the container: `"mp4"`, `"mkv"` / `"webm"`, `"avi"`, `"mpegts"`, `"y4m"`, `"gif"`, ... |
| `codec` | the video codec id: `"h264"`, `"vp8"`, `"mjpeg"`, `"mpeg1"`, `"rawvideo"`; `"frames"` for animated images and frame lists |
| `width`, `height` | pixels |
| `frameRate` | nominal frames per second |
| `frames` | the frame count when known (0 = unknown) |
| `duration` | seconds |
| `track` | the video Track being decoded |
| `audio` | the first audio track as an audio Decoder, or nil; `audioError` says why it is nil |
| `demuxer` | the Demuxer (nil for animated images and frame lists) |
| `meta` | container metadata (title, tags, ...) |
| `v:nextFrame()` | the next VideoFrame in display order; `nil, nil` at the end, `nil, err` on a decode error |
| `v:toRGBA(frameOrImage)` | an rgba8 Image (the frame's own image when it already is rgba8) |
| `v:seek(seconds)` | the next frame is the first at or after that time (decoded from the keyframe before it) |
| `v:reset()` | back to the start |
### VideoFrame
| Field | Meaning |
|---|---|
| `image` | an Image: `yuv420p` (what the codecs produce) or `rgba8` (`opts.rgba = true`, animated images) |
| `pts` | seconds from the start of the stream |
| `duration` | seconds |
| `keyframe` | true for frames that decode on their own |
| `index` | 1-based, counted in output order since the decoder was opened |
A `yuv420p` image holds three planes in one buffer: Y (`width * height` bytes, rows top down), then U and then V,
each `ceil(width / 2) * ceil(height / 2)` bytes. `image.meta.yuv` gives the matrix (`"bt601"` / `"bt709"`) and the
range (`"limited"` / `"full"`); `toRGBA` and `F.ops.image.convert(img, "rgba8")` use it.
```luau
local v = assert(F.video.open(webmBytes))
local f = assert(v:nextFrame())
local img = f.image
assert(img.format == "yuv420p" and f.pts == 0 and f.keyframe)
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
assert(buffer.len(img.pixels) == img.width * img.height + 2 * cw * ch)
local y = buffer.readu8(img.pixels, 10 * img.width + 20) -- luma at x = 20, y = 10
local u = buffer.readu8(img.pixels, img.width * img.height + 5 * cw + 10) -- its chroma sample (U plane)
local _ = y + u
local r, g, b = F.ops.image.getPixel(v:toRGBA(f), 20, 10)
assert(r and g and b)
```
### Demuxer, Track, Packet
`v.demuxer` (or `F.format("mp4").demux(F.Bytes.reader(bytes))` for the container alone) has:
| Member | Meaning |
|---|---|
| `kind`, `format` | `"demuxer"`, the container name |
| `tracks` | `{ Track }` |
| `duration`, `startTime` | seconds; frame times count from `startTime` |
| `d:packets(trackId?)` | an iterator over the Packets of one track (or all), in file order, from the current position |
| `d:read(trackId?)` | the next Packet, or nil at the end |
| `d:seek(seconds)` | every track to its last keyframe at or before the time |
| `d:track(kind)` | the first Track of a kind (`"video"`, `"audio"`, ...) |
| Track field | Meaning |
|---|---|
| `id` | the container's track number (Matroska track number, AVI stream index + 1, MPEG-TS PID, ...) |
| `kind` | `"video"`, `"audio"`, `"subtitle"` or `"data"` |
| `codec` | our codec id (`"h264"`, `"vp8"`, `"aac"`, `"vorbis"`, `"pcm_s16le"`, ...) |
| `codecTag` | the container's own id (`"avc1"`, `"V_VP8"`, `"MJPG"`, ...) |
| `timescale` | ticks per second for this track's packets |
| `width`, `height`, `frameRate` | video tracks |
| `sampleRate`, `channels`, `bitsPerSample` | audio tracks |
| `config` | codec configuration bytes (avcC, CodecPrivate, Vorbis headers, ...) |
| `duration`, `language`, `name`, `default` | when the container has them |
A Packet is `{ track, pts, dts?, duration?, keyframe, data }`: `data` is a buffer of the compressed bytes.
```luau
local v = assert(F.video.open(mp4Bytes))
local d = v.demuxer
local vt, at = d:track("video"), d:track("audio")
assert(vt.codec == "h264" and at.codec == "aac" and at.sampleRate == 44100)
local count, bytes, keys = 0, 0, 0
for p in d:packets(vt.id) do
count += 1
bytes += buffer.len(p.data)
if p.keyframe then keys += 1 end
local seconds = p.pts / vt.timescale -- ticks -> seconds
local _ = seconds
end
assert(count == 10 and keys >= 2)
print(string.format("%d packets, %.1f kbit/s", count, bytes * 8 / d.duration / 1000))
```
## Loading and playing
| Option | Meaning |
|---|---|
| `rgba` | `nextFrame` returns rgba8 images (default: the codec's yuv420p) |
| `track` | the video track id to decode (default: the first video track) |
| `audio` | `false`: do not open the audio track |
| `maxPixels` | refuse bigger frames (`LIMIT`) |
```luau
local v = assert(F.video.open(aviBytes, { rgba = true })) -- Motion-JPEG + PCM
local frames = 0
while true do
local f, err = v:nextFrame()
assert(not err, tostring(err))
if not f then break end
assert(f.image.format == "rgba8")
frames += 1
end
assert(frames == v.frames)
v:seek(0.5) -- jump: decodes from the keyframe before 0.5 s
assert(v:nextFrame().pts == 0.5)
v:reset()
assert(v:nextFrame().pts == 0)
```
The audio track is an ordinary audio Decoder: read it, or turn it into an Audio.
```luau
local v = assert(F.video.open(webmBytes))
local a = assert(v.audio, tostring(v.audioError))
assert(a.sampleRate == 44100 and a.channels == 1)
local sound = assert(F.ops.audio.toAudio(a))
local ogg = assert(F.save(sound, nil, { format = "vorbis" })) -- the soundtrack on its own
assert(F.detect(ogg) == "vorbis")
```
Animated images open as videos (`codec = "frames"`, rgba8 frames, no demuxer). `F.video.fromImage(img)` does the same
for an Image you already have, and `F.video.fromFrames(images, delays?)` makes a video from a list of same-size
images (delays in seconds: one number for all, or one per frame; default 0.1).
```luau
local g = assert(F.video.open(gifBytes))
assert(g.codec == "frames" and g.frames == 3 and g.demuxer == nil)
local imgs = {}
for i = 1, 5 do
local im = assert(F.ops.image.new(32, 16))
F.ops.image.fill(im, i * 50, 0, 0, 255)
imgs[i] = im
end
local v = assert(F.video.fromFrames(imgs, 1 / 5)) -- 5 frames at 5 fps
assert(v.frames == 5 and v.duration == 1)
```
## Saving and converting
`F.save(video, dest?, opts?)` writes a container. Packets the destination can hold are copied as they are
(remuxing); otherwise frames are decoded and re-encoded as Motion-JPEG (the one video encoder), and audio as PCM.
Images and animated images save as videos too.
| Destination | Video | Audio |
|---|---|---|
| webm | VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) | Opus / Vorbis copied |
| mkv | any codec copied, else MJPEG | copied, else PCM s16 |
| mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only |
| avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 |
| y4m | raw yuv420p | none |
| h264 | an H.264 track copied as an Annex B stream | none |
MPEG-TS and MPEG-PS are read only.
```luau
local mkv = assert(F.save(assert(F.video.open(mp4Bytes)), nil, { format = "mkv" })) -- remux: H.264 + AAC copied
local back = assert(F.video.open(mkv))
assert(back.codec == "h264" and back.audio ~= nil)
local webm = assert(F.save(assert(F.video.open(webmBytes)), nil, { format = "webm" }))
assert(F.detect(webm) == "mkv") -- WebM is the mkv format
local avi = assert(F.convert(mp4Bytes, "avi", { quality = 80 })) -- decoded, re-encoded as MJPEG
assert(F.video.open(avi).codec == "mjpeg")
local y4m = assert(F.save(assert(F.video.fromFrames({ F.Types.Image.new(16, 16) }, 0.04)), nil, { format = "y4m" }))
assert(F.detect(y4m) == "y4m")
local gifAvi = assert(F.convert(gifBytes, "avi")) -- an animated image as a video
assert(F.detect(gifAvi) == "avi")
```
A VideoDecoder is consumed as it is saved: open the source again to save it twice. Uneven frame delays (a GIF's)
become a constant frame rate with repeated frames.
## The codec registry
`F.video.codecs` maps codec ids to entries `{ id, name, fourcc?, matroska?, new?, encode? }`. Containers use it to
name a track's codec from its FourCC or Matroska CodecID, so tracks of unknown codecs still remux.
```luau
local C = F.video.codecs
assert(C.fromFourcc("MJPG") == "mjpeg" and C.fromMatroska("V_VP8") == "vp8")
assert(C.canDecode("h264") and not C.canDecode("vp9")) -- vp9 is known (remuxable) but has no decoder
assert(C.entry("h264").name == "H.264 / AVC")
```
`C.register(entry)` adds or replaces a codec at run time. `new(track, opts)` returns a decoder instance with
`decode(self, packet) -> err?`, `receive(self) -> image?, pts?, keyframe?`, `flush(self)` and `reset(self)`.
`C.simpleDecoder(decodeOne)` builds one for codecs with one picture per packet and no reordering:
```luau
local C = F.video.codecs
assert(C.register({
id = "solid", name = "Solid colour test codec", fourcc = { "SLID" },
new = function(track)
return C.simpleDecoder(function(data: buffer) -- one packet -> one Image
local img = assert(F.ops.image.new(track.width, track.height))
F.ops.image.fill(img, buffer.readu8(data, 0), 0, 0, 255)
return img
end)
end,
}))
assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid"))
```
## Playing in a game loop
Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes
the video late instead of stalling the game.
```luau
local v = assert(F.video.open(webmBytes))
local clock, shown, pending = 0, 0, nil
local function update(dt: number, budget: number) -- call once per game frame
clock += dt
local t0 = os.clock()
while os.clock() - t0 < budget do
pending = pending or v:nextFrame()
if not pending or pending.pts > clock then
return -- finished, or the next frame is not due yet
end
shown += 1 -- draw v:toRGBA(pending) (EditableImage / ImageData)
pending = nil
end
end
for _ = 1, 120 do -- two seconds at 60 fps
update(1 / 60, 0.004)
end
assert(shown == 10)
```
On LÖVE, `F.host.toImageData(v:toRGBA(frame))` gives the ImageData for a texture (`Image:replacePixels` updates it
each frame); [examples/love/main.lua](../../examples/love/main.lua) plays a GIF this way. On Roblox,
`F.host.toEditableImage` makes an EditableImage; for later frames write the pixels into the same one:
<!-- doc:display needs Roblox -->
```luau
local editable = assert(F.host.toEditableImage(v:toRGBA(first)))
-- each new frame:
editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels)
```
## Formats
| Format | Read | Write | Video codecs (decode) |
|---|---|---|---|
| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 |
| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) |
| avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) |
| mpegts, mpegps | yes | - | MPEG-1, H.264 |
| y4m | yes | yes | raw |
| h264 (Annex B) | yes | yes (copy) | H.264 |
| gif, png (APNG), webp | as video | as video via the image writers | frames |
See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`.
## Gotchas
- Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with `tools/bench.luau`
and use the budget pattern above.
- The only video encoder is Motion-JPEG. H.264, VP8 and the others are copied (remuxed) or decoded, never
encoded; `F.save(v, nil, { format = "webm" })` needs a WebM-compatible source.
- Saving consumes the decoder, and so does iterating `v.demuxer:packets()`: they share the read position.
- `frame.index` keeps counting after `seek`; use `frame.pts` to know where you are.
- A video does not save to an image format: `F.save(v, nil, { format = "gif" })` and `F.convert(aviBytes, "gif")`
fail with `UNKNOWN_FORMAT`. Collect `v:toRGBA(frame)` images and save `F.ops.image.fromFrames(images, delay)`.
- Packet times are ticks, frame times are seconds. Divide by `track.timescale`.
- `nextFrame` returns yuv420p by default. Convert with `v:toRGBA(frame)` or open with `{ rgba = true }` before handing
pixels to `F.host.toEditableImage` / `toImageData`, which need rgba8.
- Calling a video format's `open` directly (through `F.format(name)`) leaves `v.audio = nil`; the audio hook is set
by `F.video.open` / `F.open` / `F.load`.
+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)
+6 -2
View File
@@ -1,8 +1,8 @@
# Docs inputs for the 2D pages (tools/fixtures.py; see tools/docs_check.py): a layered PSD written by ImageMagick (three
# layers: Sky, Box, a half-transparent Glow; the merged image flattened by ImageMagick), a two-frame Aseprite sprite
# (built with the chunk writer of tools/fixtures/aseprite.py), an SVG icon and a Tiled map as TMX and TMJ (hand-written
# from the Tiled format docs).
# tests/gen/docs_2d.luau { files, vars = { psdBytes, asepriteBytes, svgText, tmxText, tmjText } }
# from the Tiled format docs) with its tileset image tiles.png (ImageMagick).
# tests/gen/docs_2d.luau { files, vars = { psdBytes, asepriteBytes, svgText, tmxText, tmjText, tilesPngBytes } }
import importlib.util, os, struct, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/aseprite.py"]
@@ -93,10 +93,14 @@ def generate(ctx):
"(", "-clone", "0--1", "-background", "none", "-flatten", ")", "-insert", "0",
"-depth", "8", "-type", "TrueColorAlpha", out])
files["art.psd"] = open(out, "rb").read()
tiles = os.path.join(d, "tiles.png")
ctx.nix("imagemagick", ["magick", "-size", "64x32", "pattern:checkerboard", "-depth", "8", tiles])
files["tiles.png"] = open(tiles, "rb").read()
dc.emit_inputs(ctx, files, {
"psdBytes": "art.psd",
"asepriteBytes": "sprite.aseprite",
"svgText": "icon.svg",
"tmxText": "level.tmx",
"tmjText": "level.tmj",
"tilesPngBytes": "tiles.png",
})