ws-docs: recipes: MIDI render, glTF to OBJ, vox greedy mesh, zip, CSV, SVG to PNG, TTF bake to BMFont, drawing text

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 13:18:01 -05:00
1 parent 25782c9bfd
commit 66cf0c4a6b
1 file changed
+143
+143
View File
@@ -118,6 +118,21 @@ assert(dec.sampleRate == 44100 and dec.channels == 2)
assert(math.abs(dec.duration - 1) < 0.1)
```
### Render a MIDI file with a SoundFont
A MIDI file loads as a `Midi`; `render` turns it into an audio `Decoder`. Pass an SF2 SoundFont (bytes or a loaded
one); without it the built-in waveforms play.
```luau
local song = assert(F.music.load(midiBytes))
local dec = song:render({ soundfont = sf2Bytes, sampleRate = 44100 })
assert(dec.channels == 2 and dec.duration > 0)
local wav = assert(F.save(assert(F.ops.audio.toAudio(dec)), nil, { format = "wav" }))
assert(F.detect(wav) == "wav")
```
`F.convert(midiBytes, "ogg")` does the same with the built-in waveforms.
### Read the tags of any audio file
Tag keys are lower case (`title`, `artist`, `album`, `date`, `genre`, `track`, `comment`, ...), whatever the
@@ -163,4 +178,132 @@ the future.
## 3D
### glTF to OBJ with textures
A glTF's textures stay encoded (PNG / JPEG bytes in `texture.data`). The OBJ writer puts the `.mtl` and the texture
files into `opts.files`; with a destination path `F.save` writes them next to the `.obj`.
```luau
local scene = assert(F.model.load(texturedGltfText)) -- a glTF with an embedded PNG texture
local files = {}
local obj = assert(F.save(scene, nil, { format = "obj", name = "box.obj", files = files }))
assert(files["box.mtl"]) -- the material library
local back = assert(F.model.load(obj, { format = "obj", files = files }))
assert(#back.materials >= 1 and back.textures[1] and back.textures[1].data)
```
<!-- doc:files -->
```luau
assert(F.convert("assets/BoxTextured.gltf", "obj", { out = "out/box.obj" })) -- .bin and .png read next to it
assert(F.host.exists("out/box.mtl"))
```
### MagicaVoxel .vox to a greedy mesh
```luau
local scene = assert(F.model.load(voxBytes)) -- nodes reference voxel grids (scene.voxels)
assert(F.ops.mesh.meshVoxels(scene, { scale = 0.1 })) -- one greedy mesh per grid, colours per vertex
local prim = assert(F.ops.mesh.merge(scene)) -- everything in world space, one primitive
assert(prim.attributes.POSITION.count > 0 and prim.attributes.COLOR_0)
local glb = assert(F.save(scene, nil, { format = "glb" }))
assert(F.detect(glb) == "gltf")
```
Greedy meshing merges coplanar faces of the same colour into rectangles, so a 20 x 20 wall is two triangles instead
of 800.
## Other files
### Extract a zip and re-zip it
```luau
local zip = assert(F.archive.load(zipBytes))
local files = {}
for _, e in zip:list() do
if not e.dir then
files[e.name] = assert(zip:read(e.name)) -- a buffer per file
end
end
local new = assert(F.archive.load(assert(F.save(zip, nil, { format = "tar" })))) -- any archive -> tar
new:add("extra/hello.txt", "hi")
local rezipped = assert(F.save(new, nil, { format = "zip", level = 9 }))
local check = assert(F.archive.load(rezipped))
for name, data in files do
assert(buffer.tostring(assert(check:read(name))) == buffer.tostring(data))
end
```
<!-- doc:files -->
```luau
local zip = assert(F.archive.load("assets/files.zip"))
for _, e in zip:list() do
if not e.dir then
assert(F.host.writeFile("out/" .. string.gsub(e.name, "/", "_"), assert(zip:read(e.name))))
end
end
```
### Read a CSV into rows
```luau
local rows = assert(F.data.load(csvText, { format = "csv" })) -- { { "name", "score" }, { ... } }
local recs = assert(F.data.load(csvText, { format = "csv", header = true, numbers = true }))
assert(#rows == #recs + 1)
for _, r in recs do
print(r.name, r.score) -- records keyed by the header
end
```
### SVG to PNG
```luau
local icon = assert(F.vector.load(svgText))
local img = assert(F.ops.vector.rasterize(icon, 128, 128)) -- rgba8, antialiased
local png = assert(F.save(img, nil, { format = "png" }))
assert(img.width == 128 and F.detect(png) == "png")
```
### Bake a TTF to a BMFont
`bake` renders the glyphs into packed page images. Save the descriptor and each page:
```luau
local font = assert(F.font.load(ttfBytes))
local bmfont = F.format("bmfont")
local baked = assert(bmfont.bake(font, { px = 24, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789" }))
local fnt = assert(F.saveString(baked, { format = "bmfont" })) -- the text descriptor
local pages = {}
for i, page in baked.pages do
pages[baked.meta.pageFiles[i]] = assert(F.save(page, nil, { format = "png" }))
end
local back = assert(F.font.load(fnt, { format = "bmfont", loadPage = function(file) return pages[file] end }))
assert(back:glyphIndex(string.byte("A")) ~= 0)
```
### Measure and draw a string with a TTF
```luau
local font = assert(F.font.load(ttfBytes))
local px = 20
local scale = px / font.unitsPerEm
local canvas = assert(F.ops.image.new(200, 32))
local baseline = math.ceil(font.ascent * scale) + 2 -- y of the baseline, pixels down
local x, prev = 2, nil
for _, cp in utf8.codes("Hello") do
local g = font:glyphIndex(cp)
if prev then
x += font:kern(prev, g) * scale
end
local glyph = font:rasterize(g, px) -- alpha8 coverage
if glyph and glyph.width > 0 then
-- meta.left / meta.top: the bitmap's offset from the pen; top counts up from the baseline
F.ops.image.blit(canvas, glyph, math.floor(x + glyph.meta.left), baseline - glyph.meta.top)
end
x += font:advance(g) * scale -- advance is in font units
prev = g
end
assert(x > 20)
local png = assert(F.save(canvas, nil, { format = "png" })) -- white text, transparent background
```
`alpha8` images blit as white with that alpha; tint the canvas afterwards, or blit onto a coloured background.