codecs/model/DoomMap: the Doom map-to-Scene builder moved out of archive/wad, plus a UDMF 1.1 TEXTMAP parser (fields kept, namespace flag bits); Wad.map loads UDMF maps; model/udmf for a standalone TEXTMAP; codecs/text/Lexer (C-style tokens for id Tech / UDMF text)

STYLE.md: layout block and the 2a table list DoomMap and Lexer. tests/archive/wad: the UDMF stub map now loads (empty) instead of UNSUPPORTED.
This commit is contained in:
4DBug committed 2026-11-01 18:33:24 -06:00
1 parent 01c044805f
commit 7d4e0381fe
20 files changed
+3857 -1979

No files matched your search

+4 -3
View File
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats ## Formats
<!-- formats:begin --> <!-- formats:begin -->
174 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) 175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities. adds each format's capabilities.
| Category | Format | Extensions | Read | Write | | Category | Format | Extensions | Read | Write |
@@ -133,6 +133,7 @@ adds each format's capabilities.
| 3D models | schematic | .schem .schematic .litematic | yes | yes | | 3D models | schematic | .schem .schematic .litematic | yes | yes |
| 3D models | smd | .smd | yes | yes | | 3D models | smd | .smd | yes | yes |
| 3D models | stl | .stl | yes | yes | | 3D models | stl | .stl | yes | yes |
| 3D models | udmf | .udmf .textmap | yes | - |
| 3D models | usda | .usda .usd .usdz | yes | yes | | 3D models | usda | .usda .usd .usdz | yes | yes |
| 3D models | vox | .vox | yes | yes | | 3D models | vox | .vox | yes | yes |
| 3D models | vrml | .wrl .wrz .vrml | yes | yes | | 3D models | vrml | .wrl .wrz .vrml | yes | yes |
@@ -238,8 +239,8 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`
| entropy | Huffman, RangeCoder | | entropy | Huffman, RangeCoder |
| font | Bitmap, Cff, GlyphNames, TrueType | | font | Bitmap, Cff, GlyphNames, TrueType |
| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | | image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv |
| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml | | model | DoomMap, Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml |
| text | Json, Nbt, Text, Url, Xml | | text | Json, Lexer, Nbt, Text, Url, Xml |
| video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video |
| containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | | containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip |
<!-- codecs:end --> <!-- codecs:end -->
+937 -441
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+937 -441
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+3
View File
@@ -89,6 +89,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` | | model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` |
| model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` | | model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` |
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
| model | udmf | .udmf .textmap | yes | - | maps: true | `tests/model/udmf.luau` |
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
| model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` | | model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` |
@@ -245,6 +246,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3). - codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3).
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range. - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range.
- **model** - **model**
- codecs/model/DoomMap: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) and UDMF TEXTMAP to
- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). - codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. - codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers.
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF).
@@ -256,6 +258,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. - codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d.
- **text** - **text**
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/text/Lexer: C-style tokens for id Tech / UDMF text (idLib idLexer conventions, UDMF 1.1 §I; no code taken):
- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). - codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT").
- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. - codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting.
- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. - codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding.
+4 -2
View File
@@ -33,9 +33,9 @@ src/Rosetta/
audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample
SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack
video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry) video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry)
text/ Json Nbt Text Url Xml text/ Json Lexer Nbt Text Url Xml
font/ Bitmap Cff GlyphNames TrueType font/ Bitmap Cff GlyphNames TrueType
model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler Vrml model/ DoomMap Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler Vrml
host/ host (layer 2) runtime adapters; only the api uses them host/ host (layer 2) runtime adapters; only the api uses them
Types.luau types (layer 1) standard types + constructors Types.luau types (layer 1) standard types + constructors
core/ core (layer 0) Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input core/ core (layer 0) Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input
@@ -242,6 +242,8 @@ them. Anything generic goes down a layer and is called:
| GPU texture pixels (BCn, ETC / EAC, uncompressed texel layouts, half floats) | `codecs/image/Texture` (`Bcn`, `Etc`, `Texel`, `Half`) | | GPU texture pixels (BCn, ETC / EAC, uncompressed texel layouts, half floats) | `codecs/image/Texture` (`Bcn`, `Etc`, `Texel`, `Half`) |
| animation channels sampled at a time; game-model frames, joints and skins -> Scene | `codecs/model/Sampler`, `codecs/model/Rig` | | animation channels sampled at a time; game-model frames, joints and skins -> Scene | `codecs/model/Sampler`, `codecs/model/Rig` |
| polygons with holes -> triangles | `codecs/model/Polygon` | | polygons with holes -> triangles | `codecs/model/Polygon` |
| Doom-engine maps (binary lumps, UDMF) -> tables and a Scene | `codecs/model/DoomMap` |
| C-style tokens (id Tech / UDMF text: comments, strings, numbers, words) | `codecs/text/Lexer` |
| NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` | | NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` |
| Roblox instance trees and property values | `codecs/model/Rbx` | | Roblox instance trees and property values | `codecs/model/Rbx` |
| bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` | | bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` |
+1 -1
View File
@@ -210,7 +210,7 @@ assert(F.archive.load(bytes):read("maps/e1m1.bsp"))
A WAD's lumps keep their order; lumps of a map are named `"<map>/<lump>"` (`"E1M1/THINGS"`) and repeated names get A WAD's lumps keep their order; lumps of a map are named `"<map>/<lump>"` (`"E1M1/THINGS"`) and repeated names get
`"~2"`, `"~3"`, ... so every entry is unique (writing strips both again). The format module turns lumps into game `"~2"`, `"~3"`, ... so every entry is unique (writing strips both again). The format module turns lumps into game
data: graphics (flats, patches, sprites, menu pictures) into Images through the `PLAYPAL` palette, wall textures data: graphics (flats, patches, sprites, menu pictures) into Images through the `PLAYPAL` palette, wall textures
composed from their patches, and maps into a Scene (z up, map units: floors and ceilings triangulated from the composed from their patches, and maps (binary lumps or UDMF `TEXTMAP`) into a Scene (z up, map units: floors and ceilings triangulated from the
sector outlines, walls, things as nodes standing on their floor). sector outlines, walls, things as nodes standing on their floor).
```luau ```luau
+21
View File
@@ -507,6 +507,26 @@ local again = assert(F.save(barney, nil, { format = "smd" })) -- SMD writes ba
assert(F.model.load(again).skins[1]) assert(F.model.load(again).skins[1])
``` ```
## Doom maps (UDMF)
Doom-engine maps load as Scenes (z up, map units): floors and ceilings triangulated from the sector outlines, walls
with vanilla texture alignment, things as child nodes standing on their floor. Maps inside a WAD (binary lumps or a
UDMF `TEXTMAP`) load through `F.format("wad").map(wad, name)` (see the archive page); a standalone UDMF text
(`.udmf`, or a `TEXTMAP` lump saved alone) loads directly, with texture sizes from `textureSize` (else 64 x 128 walls
and 64 x 64 flats) and the textures as URIs. `F.format("udmf").data` gives the tables: every UDMF block keeps its
fields as written (`fields`, lower-case keys: namespace and `user_` keys too), flags are rebuilt in the binary layout
(Doom bits for the Doom / Heretic / Strife namespaces, Hexen bits otherwise), and unknown blocks stay in `blocks`.
```luau
local room = assert(F.model.load(udmfText))
assert(room.meta.source.format == "udmf" and room.meta.source.namespace == "ZDoom")
assert(room.nodes[3].translation[3] == 40) -- a thing 8 units above the 32-unit pillar
local Udmf = F.format("udmf")
local data = assert(Udmf.data(F.Bytes.reader(buffer.fromstring(udmfText))))
assert(data.sectors[1].fields.user_gravity == 0.5)
assert(data.linedefs[4].tag == 7 and data.blocks[1].type == "vavoombox")
```
## Blitz3D (B3D) ## Blitz3D (B3D)
`.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; `.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS;
@@ -746,6 +766,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3)
| STEP | via the CAD plug-in | | see [cad.md](cad.md) | | STEP | via the CAD plug-in | | see [cad.md](cad.md) |
| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above |
| SMD | yes | yes | Valve studiomdl data | | SMD | yes | yes | Valve studiomdl data |
| UDMF (`.udmf`, `TEXTMAP`) | yes | | Doom maps as text: see "Doom maps (UDMF)" above |
| Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) |
| Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) |
+13 -1
View File
@@ -1022,6 +1022,18 @@ local list: { Entry } = {
return require("@rosetta/model/stl") return require("@rosetta/model/stl")
end, end,
}, },
{
name = "udmf",
category = "model",
path = "model/udmf",
extensions = { "udmf", "textmap" },
mime = { "text/x-udmf" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/DoomMap" },
caps = { decode = true, encode = false, maps = true },
load = function()
return require("@rosetta/model/udmf")
end,
},
{ {
name = "usda", name = "usda",
category = "model", category = "model",
@@ -1520,7 +1532,7 @@ local list: { Entry } = {
path = "archive/wad", path = "archive/wad",
extensions = { "wad" }, extensions = { "wad" },
mime = { "application/x-doom" }, mime = { "application/x-doom" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/DoomMap" },
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
load = function() load = function()
return require("@rosetta/archive/wad") return require("@rosetta/archive/wad")
+14 -10
View File
@@ -1,7 +1,7 @@
--!strict --!strict
-- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps, -- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps,
-- palettes, pictures, wall textures and maps. Entry names: "<map>/<lump>", repeats "<name>~<n>". Not supported: UDMF -- palettes, pictures, wall textures and maps (binary and UDMF TEXTMAP). Entry names: "<map>/<lump>", repeats
-- geometry (lumps listed), Strife's TEXTURE variant, big-endian (Jaguar) WADs, compressed Jaguar lumps. -- "<name>~<n>". Not supported: Strife's TEXTURE variant, big-endian (Jaguar) WADs, compressed Jaguar lumps.
-- ------------------------------------------------------------------------------------------------ requires -- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
@@ -10,7 +10,7 @@ local Types = require("@rosetta/Types")
local Archive = require("@rosetta/containers/Archive") local Archive = require("@rosetta/containers/Archive")
local Pixels = require("@rosetta/codecs/image/Pixels") local Pixels = require("@rosetta/codecs/image/Pixels")
local Picture = require("@rosetta/archive/wad/Picture") local Picture = require("@rosetta/archive/wad/Picture")
local Map = require("@rosetta/archive/wad/Map") local Map = require("@rosetta/codecs/model/DoomMap")
-- ------------------------------------------------------------------------------------------------ contract -- ------------------------------------------------------------------------------------------------ contract
local Wad = { local Wad = {
@@ -18,7 +18,7 @@ local Wad = {
category = "archive", category = "archive",
extensions = { "wad" }, extensions = { "wad" },
mime = { "application/x-doom" }, mime = { "application/x-doom" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/DoomMap" },
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
} }
@@ -38,6 +38,7 @@ export type Lump = {
export type MapOptions = { export type MapOptions = {
textures: boolean?, -- default true textures: boolean?, -- default true
palette: number?, -- default 0 palette: number?, -- default 0
maxBlocks: number?, -- UDMF, default 2^22
} }
-- ------------------------------------------------------------------------------------------------ constants -- ------------------------------------------------------------------------------------------------ constants
@@ -377,7 +378,7 @@ function Wad.maps(a: any): { string }
return out return out
end end
function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) function Wad.mapData(a: any, name: string, opts: MapOptions?): (Map.MapData?, Err.Err?)
local w = info(a) local w = info(a)
if not w then if not w then
return nil, Err.new(Err.ARG, "expected a decoded WAD archive") return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
@@ -392,10 +393,13 @@ function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
if not next(lumps) then if not next(lumps) then
return nil, Err.new(Err.ARG, "no map named " .. tostring(name)) return nil, Err.new(Err.ARG, "no map named " .. tostring(name))
end end
if lumps.TEXTMAP then local m, msg
return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps") local tm = lumps.TEXTMAP
if tm then
m, msg = Map.udmf(buffer.readstring(tm.buf, tm.at, tm.size), opts and opts.maxBlocks)
else
m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil)
end end
local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil)
if not m then if not m then
return nil, Err.from(msg) return nil, Err.from(msg)
end end
@@ -403,7 +407,7 @@ function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
end end
function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?) function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?)
local m, err = Wad.mapData(a, name) local m, err = Wad.mapData(a, name, opts)
if not m then if not m then
return nil, err return nil, err
end end
@@ -441,7 +445,7 @@ function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Er
image = if images then image else nil, image = if images then image else nil,
} }
local scene = Map.scene(m, tex, string.upper(name)) local scene = Map.scene(m, tex, string.upper(name))
scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 } scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, namespace = m.namespace, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 }
return scene, nil return scene, nil
end end
+248
View File
@@ -0,0 +1,248 @@
--!strict
-- codecs/model/DoomMap/Udmf: UDMF 1.1 TEXTMAP text (zdoom.org specs/udmf.txt; no code taken) to the DoomMap tables.
-- Every block keeps its fields (lower-case keys, namespace and user_ keys included); unknown blocks and global
-- assignments are kept as data. Flags are rebuilt in the binary layout of the namespace (Doom or Hexen bits).
local Lexer = require("@rosetta/codecs/text/Lexer")
local Udmf = {}
export type Block = { type: string, fields: { [string]: any } }
export type Document = { namespace: string?, globals: { [string]: any }, blocks: { Block } }
-- ------------------------------------------------------------------------------------------------ parse
local function value(L: Lexer.Lexer): (any, string?)
local k, v = L:next()
if k == "number" then
local raw = L.raw :: string
-- integer := ... | 0[0-9]+ (octal) | 0x[0-9A-Fa-f]+
if string.match(raw, "^[+-]?0[0-7]+$") then
local neg = string.sub(raw, 1, 1) == "-"
local o = tonumber((string.gsub(raw, "^[+-]?0", "")), 8) :: number
return if neg then -o else o, nil
end
return v, nil
elseif k == "string" then
return v, nil
elseif k == "word" then
local w = string.lower(v)
if w == "true" then
return true, nil
elseif w == "false" then
return false, nil
end
return v, nil
end
return nil, L.err or "expected a value"
end
function Udmf.parse(text: string, maxBlocks: number?): (Document?, string?)
local L = Lexer.new(text)
local doc: Document = { namespace = nil, globals = {}, blocks = {} }
local limit = maxBlocks or 2 ^ 22
while true do
local k, id = L:next()
if k == nil then
if L.err then
return nil, L.err .. " at line " .. L:line()
end
break
end
if k ~= "word" then
return nil, "expected an identifier at line " .. L:line()
end
local name = string.lower(id)
local pk, pv = L:next()
if pk == "punct" and pv == "=" then
local v, err = value(L)
if err then
return nil, err .. " at line " .. L:line()
end
local sk, sv = L:next()
if sk ~= "punct" or sv ~= ";" then
return nil, "expected ; at line " .. L:line()
end
doc.globals[name] = v
if name == "namespace" and type(v) == "string" then
doc.namespace = v
end
elseif pk == "punct" and pv == "{" then
if #doc.blocks >= limit then
return nil, "limit: more than " .. limit .. " blocks"
end
local fields: { [string]: any } = {}
while true do
local fk, fv = L:next()
if fk == "punct" and fv == "}" then
break
end
if fk ~= "word" then
return nil, (L.err or "expected a field name") .. " at line " .. L:line()
end
local ek, ev = L:next()
if ek ~= "punct" or ev ~= "=" then
return nil, "expected = at line " .. L:line()
end
local v, err = value(L)
if err then
return nil, err .. " at line " .. L:line()
end
local sk, sv = L:next()
if sk ~= "punct" or sv ~= ";" then
return nil, "expected ; at line " .. L:line()
end
fields[string.lower(fv)] = v
end
table.insert(doc.blocks, { type = name, fields = fields })
else
return nil, "expected = or { at line " .. L:line()
end
end
return doc, nil
end
-- ------------------------------------------------------------------------------------------------ map
local LINE_FLAGS: { [string]: number } = { blocking = 1, blockmonsters = 2, twosided = 4, dontpegtop = 8, dontpegbottom = 16, secret = 32, blocksound = 64, dontdraw = 128, mapped = 256 }
-- Hexen SPAC activation (bits 10..12) and repeat (bit 9)
local SPAC: { [string]: number } = { playercross = 0, playeruse = 1, monstercross = 2, impact = 3, playerpush = 4, missilecross = 5 }
local function num(f: { [string]: any }, k: string, default: number): number
local v = f[k]
return if type(v) == "number" then v else default
end
local function flag(f: { [string]: any }, k: string): boolean
return f[k] == true
end
local function tex(f: { [string]: any }, k: string, default: string): string
local v = f[k]
return if type(v) == "string" then string.upper(v) else default
end
local function args(f: { [string]: any }): { number }
return { num(f, "arg0", 0), num(f, "arg1", 0), num(f, "arg2", 0), num(f, "arg3", 0), num(f, "arg4", 0) }
end
local function index(f: { [string]: any }, k: string): number?
local v = f[k]
return if type(v) == "number" and v >= 0 and v % 1 == 0 then v + 1 else nil
end
function Udmf.map(doc: Document): (any, string?)
local ns = string.lower(doc.namespace or "")
local hexenBits = ns ~= "doom" and ns ~= "heretic" and ns ~= "strife"
local m = { format = "udmf", namespace = doc.namespace, globals = doc.globals, things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {}, blocks = {} }
for _, b in doc.blocks do
local f = b.fields
if b.type == "vertex" then
local x, y = f.x, f.y
if type(x) ~= "number" or type(y) ~= "number" then
return nil, "vertex " .. (#m.vertices // 2) .. " has no x / y"
end
table.insert(m.vertices, x)
table.insert(m.vertices, y)
elseif b.type == "linedef" then
local flags = 0
for k, bit in LINE_FLAGS do
if flag(f, k) then
flags += bit
end
end
if hexenBits then
if flag(f, "repeatspecial") then
flags += 512
end
for k, a in SPAC do
if flag(f, k) then
flags = bit32.bor(bit32.band(flags, bit32.bnot(0x1C00)), a * 1024)
end
end
end
local v1, v2 = index(f, "v1"), index(f, "v2")
if not v1 or not v2 then
return nil, "linedef " .. #m.linedefs .. " has no v1 / v2"
end
local a = args(f)
table.insert(m.linedefs, {
v1 = v1,
v2 = v2,
flags = flags,
special = num(f, "special", 0),
tag = if hexenBits then num(f, "id", -1) else a[1],
args = a,
front = index(f, "sidefront"),
back = index(f, "sideback"),
fields = f,
})
elseif b.type == "sidedef" then
local s = index(f, "sector")
if not s then
return nil, "sidedef " .. #m.sidedefs .. " has no sector"
end
table.insert(m.sidedefs, {
xoff = num(f, "offsetx", 0),
yoff = num(f, "offsety", 0),
upper = tex(f, "texturetop", "-"),
lower = tex(f, "texturebottom", "-"),
middle = tex(f, "texturemiddle", "-"),
sector = s,
fields = f,
})
elseif b.type == "sector" then
table.insert(m.sectors, {
floor = num(f, "heightfloor", 0),
ceiling = num(f, "heightceiling", 0),
floorFlat = tex(f, "texturefloor", "-"),
ceilingFlat = tex(f, "textureceiling", "-"),
light = num(f, "lightlevel", 160),
special = num(f, "special", 0),
tag = num(f, "id", 0),
fields = f,
})
elseif b.type == "thing" then
local x, y = f.x, f.y
if type(x) ~= "number" or type(y) ~= "number" then
return nil, "thing " .. #m.things .. " has no x / y"
end
local fl = 0
if flag(f, "skill1") or flag(f, "skill2") then
fl += 1
end
if flag(f, "skill3") then
fl += 2
end
if flag(f, "skill4") or flag(f, "skill5") then
fl += 4
end
if flag(f, "ambush") then
fl += 8
end
if hexenBits then
fl += (if flag(f, "dormant") then 16 else 0) + (if flag(f, "class1") then 32 else 0) + (if flag(f, "class2") then 64 else 0)
+ (if flag(f, "class3") then 128 else 0) + (if flag(f, "single") then 256 else 0) + (if flag(f, "coop") then 512 else 0)
+ (if flag(f, "dm") then 1024 else 0)
else
-- Doom / Boom / MBF: 16 not in single player, 32 not in deathmatch, 64 not in coop, 128 friend
fl += (if flag(f, "single") then 0 else 16) + (if flag(f, "dm") then 0 else 32) + (if flag(f, "coop") then 0 else 64)
+ (if flag(f, "friend") then 128 else 0)
end
table.insert(m.things, {
x = x,
y = y,
z = num(f, "height", 0),
angle = num(f, "angle", 0),
type = num(f, "type", 0),
flags = fl,
tid = num(f, "id", 0),
special = num(f, "special", 0),
args = args(f),
fields = f,
})
else
table.insert(m.blocks, b)
end
end
return m, nil
end
return Udmf
@@ -1,9 +1,10 @@
--!strict --!strict
-- archive/wad/Map: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) to tables and a Scene, with -- codecs/model/DoomMap: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) and UDMF TEXTMAP to
-- vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the Unofficial Doom Specs and -- tables and a Scene, with vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the
-- the Hexen specs; no code taken. Not supported: UDMF (TEXTMAP). -- Unofficial Doom Specs, the Hexen specs and UDMF 1.1; no code taken. Not supported: UDMF slopes / per-part offsets.
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Polygon = require("@rosetta/codecs/model/Polygon") local Polygon = require("@rosetta/codecs/model/Polygon")
local Udmf = require("@rosetta/codecs/model/DoomMap/Udmf")
local Map = {} local Map = {}
@@ -12,12 +13,16 @@ local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16
local writef32, writeu32 = buffer.writef32, buffer.writeu32 local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { buf: buffer, at: number, size: number } export type Lump = { buf: buffer, at: number, size: number }
export type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? } export type Fields = { [string]: any } -- UDMF: the block's fields as written (lower-case keys)
export type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? } export type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }?, fields: Fields? }
export type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number } export type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number?, fields: Fields? }
export type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number } export type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number, fields: Fields? }
export type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number, fields: Fields? }
export type MapData = { export type MapData = {
format: "doom" | "hexen", format: "doom" | "hexen" | "udmf",
namespace: string?, -- UDMF
globals: Fields?, -- UDMF global assignments
blocks: { Udmf.Block }?, -- UDMF blocks other than vertex / linedef / sidedef / sector / thing
things: { Thing }, things: { Thing },
linedefs: { Linedef }, linedefs: { Linedef },
sidedefs: { Sidedef }, sidedefs: { Sidedef },
@@ -136,6 +141,16 @@ function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string
return m, nil return m, nil
end end
function Map.udmf(text: string, maxBlocks: number?): (MapData?, string?)
local doc, err = Udmf.parse(text, maxBlocks)
if not doc then
return nil, err
end
return Udmf.map(doc)
end
Map.parseUdmf = Udmf.parse
-- ------------------------------------------------------------------------------------------------ sector outlines -- ------------------------------------------------------------------------------------------------ sector outlines
-- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest -- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest
-- right turn at forks; unclosed chains dropped -- right turn at forks; unclosed chains dropped
+130
View File
@@ -0,0 +1,130 @@
--!strict
-- codecs/text/Lexer: C-style tokens for id Tech / UDMF text (idLib idLexer conventions, UDMF 1.1 §I; no code taken):
-- // and /* */ comments, "strings" with backslash escapes, numbers (decimal, float, 0x hex), bare words, and single
-- punctuation characters { } ( ) [ ] ; = ,.
local Lexer = {}
export type Kind = "word" | "number" | "string" | "punct"
export type Lexer = {
s: string,
p: number, -- next byte to read, 1-based
n: number,
raw: string?, -- the last token's text as written
err: string?,
next: (self: Lexer) -> (Kind?, any),
peek: (self: Lexer) -> (Kind?, any),
line: (self: Lexer, at: number?) -> number,
}
local find, sub, byte, match = string.find, string.sub, string.byte, string.match
local ESC: { [string]: string } = { n = "\n", t = "\t", r = "\r", ["0"] = "\0" }
local function skip(L: Lexer): number?
local s, p = L.s, L.p
while true do
p = find(s, "[^ \t\r\n\f\v]", p)
if not p then
return nil
end
if byte(s, p) == 47 then
local c2 = byte(s, p + 1)
if c2 == 47 then
local e = find(s, "\n", p + 2, true)
if not e then
return nil
end
p = e + 1
elseif c2 == 42 then
local _, e = find(s, "*/", p + 2, true)
if not e then
L.err = "unterminated comment"
return nil
end
p = e + 1
else
return p
end
else
return p
end
end
end
local function token(L: Lexer): (Kind?, any, number)
local p = skip(L)
if not p then
return nil, nil, L.n + 1
end
local s = L.s
local c = byte(s, p)
if c == 34 then
local parts: { string }? = nil
local q = p + 1
while true do
local e = find(s, "[\"\\]", q)
if not e then
L.err = "unterminated string"
return nil, nil, L.n + 1
end
if byte(s, e) == 34 then
local tail = sub(s, q, e - 1)
if parts then
table.insert(parts, tail)
L.raw = sub(s, p, e)
return "string", table.concat(parts), e + 1
end
L.raw = sub(s, p, e)
return "string", tail, e + 1
end
parts = parts or {}
local ch = sub(s, e + 1, e + 1)
table.insert(parts :: { string }, sub(s, q, e - 1))
table.insert(parts :: { string }, ESC[ch] or ch)
q = e + 2
end
end
if find("{}()[];=,", string.char(c), 1, true) then
L.raw = string.char(c)
return "punct", L.raw, p + 1
end
local w = match(s, "^[^ \t\r\n\f\v{}()%[%];=,\"]+", p) :: string
local e = p + #w
-- a comment right after a word ends it
local cm = find(w, "/[/*]")
if cm then
w = sub(w, 1, cm - 1)
e = p + #w
end
L.raw = w
if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then
local v = tonumber(w)
if v and not find(w, "[iInN]") then
return "number", v, e
end
end
return "word", w, e
end
local function nextToken(L: Lexer): (Kind?, any)
local k, v, e = token(L)
L.p = e
return k, v
end
local function peek(L: Lexer): (Kind?, any)
local raw = L.raw
local k, v = token(L)
L.raw = raw
return k, v
end
local function line(L: Lexer, at: number?): number
local _, n = string.gsub(sub(L.s, 1, (at or L.p) - 1), "\n", "")
return n + 1
end
function Lexer.new(s: string): Lexer
return { s = s, p = 1, n = #s, raw = nil, err = nil, next = nextToken, peek = peek, line = line }
end
return Lexer
+81
View File
@@ -0,0 +1,81 @@
--!strict
-- model/udmf: a standalone UDMF TEXTMAP (UDMF 1.1, zdoom.org specs/udmf.txt) into a Scene through codecs/model/DoomMap,
-- read only. Texture sizes come from opts.textureSize (default 64 x 128 walls, 64 x 64 flats); textures are URIs.
-- Maps inside a WAD load through archive/wad (Wad.map). Not supported: writing, slopes, per-part offsets.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Types = require("@rosetta/Types")
local DoomMap = require("@rosetta/codecs/model/DoomMap")
-- ------------------------------------------------------------------------------------------------ contract
local Udmf = {
name = "udmf",
category = "model",
extensions = { "udmf", "textmap" },
mime = { "text/x-udmf" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/DoomMap" },
caps = { decode = true, encode = false, maps = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
textureSize: ((kind: string, name: string) -> (number?, number?))?, -- kind "texture" or "flat"
decodeTexture: ((kind: string, name: string) -> Types.Image?)?,
name: string?, -- the mesh name, default "MAP"
maxBlocks: number?, -- default 2^22
}
-- ------------------------------------------------------------------------------------------------ sniff
function Udmf.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 1024, true)
for _ = 1, 32 do
local rest = string.match(head, "^//[^\n]*\n%s*(.*)$") or string.match(head, "^/%*.-%*/%s*(.*)$")
if not rest then
break
end
head = rest
end
if string.match(head, "^[Nn][Aa][Mm][Ee][Ss][Pp][Aa][Cc][Ee]%s*=%s*\"") then
return 0.9
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Udmf.data(r: Bytes.Reader, opts: DecodeOptions?): (DoomMap.MapData?, Err.Err?)
local text = Sniff.dropBom(r:string(r:remaining()))
if r.err then
return nil, r.err
end
local m, msg = DoomMap.udmf(text, opts and opts.maxBlocks)
if not m then
return nil, Err.from(msg)
end
return m, nil
end
function Udmf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local m, err = Udmf.data(r, opts)
if not m then
return nil, err
end
local size = opts and opts.textureSize
local tex: DoomMap.Textures = {
size = function(kind: string, name: string): (number?, number?)
if size then
return size(kind, name)
end
return nil, nil
end,
image = opts and opts.decodeTexture,
}
local name = opts and opts.name or "MAP"
local scene = DoomMap.scene(m, tex, name)
scene.meta.source = { format = "udmf", namespace = m.namespace, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 }
return scene, nil
end
return Udmf
+2 -2
View File
@@ -121,8 +121,8 @@ do
t:eq(names[17], "E1M2/ENDMAP", "up to ENDMAP") t:eq(names[17], "E1M2/ENDMAP", "up to ENDMAP")
t:eq(names[18], "DEMO1", "after the map") t:eq(names[18], "DEMO1", "after the map")
t:eq(names[19], "DEMO1~2", "duplicate names get ~n") t:eq(names[19], "DEMO1~2", "duplicate names get ~n")
local _, ue = Wad.map(rm, "E1M2") local us = Wad.map(rm, "E1M2") :: any
t:check(ue and ue.code == Err.UNSUPPORTED, "UDMF unsupported") t:check(us and us.meta.source.mapFormat == "udmf" and #us.meshes[1].primitives == 0, "UDMF stub: an empty map")
local s = Wad.map(rm, "E1M1") :: any local s = Wad.map(rm, "E1M1") :: any
local area = { floor = 0, ceil = 0, wall = 0 } local area = { floor = 0, ceil = 0, wall = 0 }
for _, p in s.meshes[1].primitives do for _, p in s.meshes[1].primitives do
+57
View File
@@ -0,0 +1,57 @@
-- codecs/text/Lexer tests: token kinds, comments, escapes, numbers, errors, and a no-throw pass.
local T = require("@tests/T")
local Lexer = require("@rosetta/codecs/text/Lexer")
local t = T.suite("lexer")
local function all(s: string): ({ string }, string?)
local L = Lexer.new(s)
local out = {}
while true do
local k, v = L:next()
if not k then
break
end
table.insert(out, k .. ":" .. tostring(v))
end
return out, L.err
end
local got = all('Version 2 // c\n{ "a \\"b\\"" ( -0.5 25e-2 0x10 ) /* x\n y */ textures/base_wall/lfwall13f3 a=b; }')
t:eq(table.concat(got, " "), 'word:Version number:2 punct:{ string:a "b" punct:( number:-0.5 number:0.25 number:16 punct:) word:textures/base_wall/lfwall13f3 word:a punct:= word:b punct:; punct:}', "tokens")
local L = Lexer.new("a // tail")
t:eq(select(2, L:peek()), "a", "peek")
t:eq(select(2, L:next()), "a", "next after peek")
t:eq(L:next(), nil, "end after a trailing comment")
t:eq(table.concat((all("x/*y*/z")), " "), "word:x word:z", "a comment ends a word")
t:eq(table.concat((all("- inf 1.2.3")), " "), "word:- word:inf word:1.2.3", "not numbers")
t:eq(select(2, all('"open')), "unterminated string", "unterminated string")
t:eq(select(2, all("/* open")), "unterminated comment", "unterminated comment")
local L2 = Lexer.new("a\nb\nc")
L2:next()
L2:next()
t:eq(L2:line(), 2, "line")
local rand = T.rng(5)
local alphabet = '{}()[];=,"\\/* \n\t0123456789.-+exabc_'
t:fuzz("tokens", function(b: buffer)
local L3 = Lexer.new(buffer.tostring(b))
for _ = 1, 10000 do
if not L3:next() then
break
end
end
return true
end, (function()
local out = {}
for _ = 1, 50 do
local s = {}
for _ = 1, 1 + rand(80) do
local i = 1 + rand(#alphabet)
table.insert(s, string.sub(alphabet, i, i))
end
table.insert(out, buffer.fromstring(table.concat(s)))
end
return out
end)())
t:done()
+173
View File
@@ -0,0 +1,173 @@
-- model/udmf + archive/wad UDMF tests: Freedoom MAP01 converted to TEXTMAP against its binary lumps (same tables, same
-- Scene geometry), and a hand-written ZDoom room with exact areas. Fixtures: tools/fixtures/udmf.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Udmf = require("@rosetta/model/udmf")
local Wad = require("@rosetta/archive/wad")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Fx = require("@tests/gen/udmf")
local t = T.suite("udmf")
t:eq(Udmf.name, "udmf", "name")
t:eq(F.detect(Fx.room), "udmf", "F.detect")
do
local bin = Wad.decode(Bytes.reader(buffer.fromstring(Fx.binary))) :: any
local udmf = Wad.decode(Bytes.reader(buffer.fromstring(Fx.textmap))) :: any
t:eq(Wad.maps(udmf)[1], "MAP01", "UDMF map listed")
local a = Wad.mapData(bin, "MAP01") :: any
local b, e = Wad.mapData(udmf, "MAP01")
t:check(b, "TEXTMAP: " .. tostring(e))
local m = b :: any
t:eq(m.format, "udmf", "format")
t:eq(m.namespace, "Doom", "namespace")
t:eq(#m.vertices, #a.vertices, "vertices")
local same = true
for i, v in a.vertices do
same = same and m.vertices[i] == v
end
t:check(same, "vertex coordinates")
for _, k in { "linedefs", "sidedefs", "sectors", "things" } do
t:eq(#m[k], #a[k], k)
end
local bad = {}
for i, l in a.linedefs do
local u = m.linedefs[i]
if u.v1 ~= l.v1 or u.v2 ~= l.v2 or u.flags ~= l.flags or u.special ~= l.special or (l.special ~= 0 and u.tag ~= l.tag) or u.front ~= l.front or u.back ~= l.back then
table.insert(bad, "linedef " .. i)
end
end
for i, s in a.sidedefs do
local u = m.sidedefs[i]
if u.xoff ~= s.xoff or u.yoff ~= s.yoff or u.upper ~= s.upper or u.lower ~= s.lower or u.middle ~= s.middle or u.sector ~= s.sector then
table.insert(bad, "sidedef " .. i)
end
end
for i, s in a.sectors do
local u = m.sectors[i]
if u.floor ~= s.floor or u.ceiling ~= s.ceiling or u.floorFlat ~= s.floorFlat or u.ceilingFlat ~= s.ceilingFlat or u.light ~= s.light or u.special ~= s.special or u.tag ~= s.tag then
table.insert(bad, "sector " .. i)
end
end
for i, th in a.things do
local u = m.things[i]
if u.x ~= th.x or u.y ~= th.y or u.type ~= th.type or u.angle ~= th.angle or u.flags ~= th.flags then
table.insert(bad, "thing " .. i)
end
end
t:eq(#bad, 0, "TEXTMAP tables equal the binary ones: " .. table.concat(bad, ", ", 1, math.min(#bad, 5)))
local t0 = T.clock()
local s1 = Wad.map(bin, "MAP01") :: any
local s2, se = Wad.map(udmf, "MAP01")
t:check(s2, "TEXTMAP scene: " .. tostring(se))
local dt = T.clock() - t0
local p1, p2 = s1.meshes[1].primitives, (s2 :: any).meshes[1].primitives
t:eq(#p2, #p1, "primitives")
local geo = true
for i, p in p1 do
local q = p2[i]
geo = geo and q ~= nil and p.extras.wad.texture == q.extras.wad.texture
and buffer.tostring(p.attributes.POSITION.data) == buffer.tostring(q.attributes.POSITION.data)
and buffer.tostring(p.attributes.TEXCOORD_0.data) == buffer.tostring(q.attributes.TEXCOORD_0.data)
end
t:check(geo, "the TEXTMAP Scene is the binary map's geometry, byte for byte")
local withImage = 0
for _, tex in (s2 :: any).textures do
if tex.image then
withImage += 1
end
end
t:check(withImage > 0, "textures from the WAD")
t:eq((s2 :: any).meta.source.namespace, "Doom", "meta namespace")
t:eq(#(s2 :: any).nodes, 1 + #a.things, "a node per thing")
t:note("MAP01 as UDMF: %d bytes of TEXTMAP, %d primitives, both scenes in %.2f s", #Fx.text, #p2, dt)
t:check(F.detect(Fx.text) == "udmf", "TEXTMAP text detected")
local alone = F.load(Fx.text) :: any
t:check(alone and #alone.meshes[1].primitives == #p1, "standalone TEXTMAP: same batches")
end
do
local s, e = Udmf.decode(Bytes.reader(buffer.fromstring(Fx.room)), { textureSize = function(kind: string, name: string)
if kind == "texture" then
return 64, 128
end
return 64, 64
end })
t:check(s, "room: " .. tostring(e))
local area = { floor = 0, ceil = 0, wall = 0 }
for _, p in (s :: any).meshes[1].primitives do
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any
for k = 0, p.attributes.POSITION.count - 1, 3 do
local ux, uy, uz = pos(k + 1, 0) - pos(k, 0), pos(k + 1, 1) - pos(k, 1), pos(k + 1, 2) - pos(k, 2)
local vx, vy, vz = pos(k + 2, 0) - pos(k, 0), pos(k + 2, 1) - pos(k, 1), pos(k + 2, 2) - pos(k, 2)
local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
local ar = math.sqrt(cx * cx + cy * cy + cz * cz) / 2
if nrm(k, 2) > 0.5 then
area.floor += ar
elseif nrm(k, 2) < -0.5 then
area.ceil += ar
else
area.wall += ar
end
end
end
t:eq(area.floor, 256 * 256, "room floors")
t:eq(area.ceil, 256 * 256, "room ceilings")
t:eq(area.wall, 4 * 256 * 128 + 4 * 64 * 32, "room walls")
local sc = s :: any
t:eq(sc.nodes[3].translation[3], 40, "thing height above the pillar floor")
t:eq(sc.nodes[3].translation[1], 128.5, "float coordinates")
t:eq(sc.meta.source.namespace, "ZDoom", "namespace (case-insensitive key)")
local m = Udmf.data(Bytes.reader(buffer.fromstring(Fx.room))) :: any
t:eq(m.globals.user_note, 'a "quoted" \\ note', "string escapes")
t:eq(m.vertices[3], 256, "hex")
t:eq(m.vertices[8], 256, "octal")
t:eq(m.sectors[1].fields.user_gravity, 0.5, "user_ field kept")
t:eq(m.sidedefs[5].fields.offsetx_bottom, 4, "namespace field kept")
t:eq(m.sidedefs[1].middle, "WALL", "texture names upper-cased")
t:eq(m.sidedefs[1].fields.texturemiddle, "Wall", "as written in fields")
t:eq(m.linedefs[2].flags, 1, "keys and keywords are case-insensitive")
t:eq(m.linedefs[4].flags, 1 + 512 + 1024, "Hexen bits: blocking, repeat, use activation")
t:eq(m.linedefs[4].tag, 7, "id is the tag outside Doom namespaces")
t:eq(m.linedefs[4].args[1], 3, "args")
t:eq(m.sectors[2].light, 200, "light")
t:eq(m.sectors[2].tag, 3, "sector id")
t:eq(m.things[2].flags, 16, "Hexen thing bits: dormant")
t:eq(m.things[2].tid, 5, "thing id")
t:eq(m.blocks[1].type, "vavoombox", "unknown block kept")
t:eq(m.blocks[1].fields.foo, 1, "unknown block fields")
end
do
local function bad(s: string): any
local _, e = Udmf.decode(Bytes.reader(buffer.fromstring(s)))
return e and e.code
end
t:eq(bad('namespace = "x"; vertex { x = 1 y = 2; }'), Err.CORRUPT, "missing ;")
t:eq(bad('namespace = "x"; /* open'), Err.CORRUPT, "unterminated comment")
t:eq(bad('namespace = "x'), Err.CORRUPT, "unterminated string")
t:eq(bad('namespace = "x"; linedef { v2 = 1; sidefront = 0; }'), Err.CORRUPT, "linedef without v1")
t:eq(bad('namespace = "x"; vertex { x = 1; y = 2; } vertex { x = 1; y = 2; } } '), Err.CORRUPT, "stray }")
local _, le = Udmf.decode(Bytes.reader(buffer.fromstring('namespace = "x"; a {} b {} c {}')), { maxBlocks = 2 })
t:check(le and le.code == Err.LIMIT, "maxBlocks")
t:check(F.detect("namespace = 1;") ~= "udmf", "a quoted namespace is required to sniff")
end
t:fuzz("decode", function(b: buffer)
return Udmf.decode(Bytes.reader(b))
end, { buffer.fromstring(Fx.room) }, { mutations = 400 })
local small = Wad.new()
small:add("E1M1", "")
small:add("TEXTMAP", Fx.room)
small:add("ENDMAP", "")
t:fuzz("wad", function(b: buffer)
local w = Wad.decode(Bytes.reader(b))
if w then
Wad.map(w, "MAP01")
end
return w
end, { small:write() :: buffer }, { mutations = 300 })
t:done()
+21
View File
@@ -0,0 +1,21 @@
# Docs inputs for the id Tech sections of the scene / tilemap / archive pages (tools/fixtures.py; tools/docs_check.py
# explains the inputs), made by the format fixtures' writers: the hand-written UDMF room (udmf.py).
# tests/gen/docs_idtech.luau { files = { [name] = bytes }, vars = { udmfText = "room.udmf", ... } }
import importlib.util, os
INPUTS = ["tools/docs_check.py"]
def mod(ctx, name):
spec = importlib.util.spec_from_file_location("fx_" + name, os.path.join(ctx.root, "tools", name + ".py") if name == "docs_check"
else os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
check = mod(ctx, "docs_check")
files = {"room.udmf": mod(ctx, "udmf").ROOM.encode()}
vars = {"udmfText": "room.udmf"}
check.emit_inputs(ctx, files, vars)
+112
View File
@@ -0,0 +1,112 @@
# UDMF fixtures (tools/fixtures.py). Freedoom has no UDMF maps, so Freedoom MAP01 (BSD, licenses/freedoom-COPYING.txt;
# the nix freedoom package, cut down as in wad.py) is converted here to a "Doom"-namespace TEXTMAP by the UDMF 1.1
# conversion rules (tag -> id and arg0, flag bits -> booleans). The test checks that the TEXTMAP map gives the same
# tables and the same Scene geometry as the binary lumps. Plus a hand-written ZDoom-namespace room (comments, octal /
# hex, escapes, user_ and unknown keys, an unknown block) with exact areas.
# tests/gen/udmf.luau { binary = <IWAD>, textmap = <PWAD with MAP01 as UDMF>, text = <the TEXTMAP>, room = <text> }
import importlib.util, os, struct
HERE = os.path.dirname(os.path.abspath(__file__))
def wadgen():
spec = importlib.util.spec_from_file_location("_wadfx", os.path.join(HERE, "wad.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def q(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
def to_udmf(d):
out = ['namespace = "Doom";', ""]
nm = lambda b: b.split(b"\0")[0].decode("latin1")
for i in range(0, len(d["THINGS"]), 10):
x, y, a, t, f = struct.unpack_from("<hhHHH", d["THINGS"], i)
kv = ["x = %d.0;" % x, "y = %d.0;" % y, "angle = %d;" % a, "type = %d;" % t]
for k, on in [("skill1", f & 1), ("skill2", f & 1), ("skill3", f & 2), ("skill4", f & 4), ("skill5", f & 4),
("ambush", f & 8), ("single", not f & 16), ("dm", not f & 32), ("coop", not f & 64), ("friend", f & 128)]:
if on:
kv.append("%s = true;" % k)
out.append("thing // %d\n{\n%s\n}\n" % (i // 10, "\n".join(kv)))
for i in range(0, len(d["VERTEXES"]), 4):
x, y = struct.unpack_from("<hh", d["VERTEXES"], i)
out.append("vertex { x = %d.000; y = %d.000; }" % (x, y))
bits = ["blocking", "blockmonsters", "twosided", "dontpegtop", "dontpegbottom", "secret", "blocksound", "dontdraw", "mapped"]
for i in range(0, len(d["LINEDEFS"]), 14):
v1, v2, f, sp, tag, fr, bk = struct.unpack_from("<HHHHHHH", d["LINEDEFS"], i)
kv = ["id = %d;" % tag, "v1 = %d;" % v1, "v2 = %d;" % v2, "sidefront = %d;" % fr]
if bk != 0xFFFF:
kv.append("sideback = %d;" % bk)
if sp:
kv += ["special = %d;" % sp, "arg0 = %d;" % tag]
kv += ["%s = true;" % b for k, b in enumerate(bits) if f & (1 << k)]
out.append("linedef\n{\n%s\n}\n" % "\n".join(kv))
for i in range(0, len(d["SIDEDEFS"]), 30):
xo, yo, up, lo, mid, sec = struct.unpack_from("<hh8s8s8sH", d["SIDEDEFS"], i)
kv = ["sector = %d;" % sec]
if xo:
kv.append("offsetx = %d;" % xo)
if yo:
kv.append("offsety = %d;" % yo)
for k, v in [("texturetop", up), ("texturebottom", lo), ("texturemiddle", mid)]:
if nm(v) != "-":
kv.append("%s = %s;" % (k, q(nm(v))))
out.append("sidedef\n{\n%s\n}\n" % "\n".join(kv))
for i in range(0, len(d["SECTORS"]), 26):
fl, ce, ff, cf, li, sp, tag = struct.unpack_from("<hh8s8sHHH", d["SECTORS"], i)
kv = ["heightfloor = %d;" % fl, "heightceiling = %d;" % ce, "texturefloor = %s;" % q(nm(ff)),
"textureceiling = %s;" % q(nm(cf)), "lightlevel = %d;" % li]
if sp:
kv.append("special = %d;" % sp)
if tag:
kv.append("id = %d;" % tag)
out.append("sector\n{\n%s\n}\n" % "\n".join(kv))
return "\n".join(out) + "\n"
ROOM = r'''// a 256 x 256 room (sector 0) with a 64 x 64 pillar sector (1), pillar floor 32
/* written by hand
for the rosetta tests */
NameSpace = "ZDoom";
user_note = "a \"quoted\" \\ note";
vertex { x = 0; y = 0.0; } // 0
vertex { x = 0x100; y = 0; } // 1: hex
vertex { x = 256.0; y = 256e0; } // 2
vertex { x = 0; y = 0400; } // 3: octal 256
vertex { x = 96; y = 96; } vertex { x = 160; y = 96; } vertex { x = 160; y = 160; } vertex { x = 96; y = 160; }
sidedef { sector = 0; texturemiddle = "Wall"; }
sidedef { sector = 0; texturemiddle = "WALL"; }
sidedef { sector = 0; texturemiddle = "WALL"; }
sidedef { sector = 0; texturemiddle = "WALL"; }
sidedef { sector = 0; texturebottom = "STEP"; offsetx_bottom = 4.0; } sidedef { sector = 0; texturebottom = "STEP"; }
sidedef { sector = 0; texturebottom = "STEP"; } sidedef { sector = 0; texturebottom = "STEP"; }
sidedef { sector = 1; } sidedef { sector = 1; } sidedef { sector = 1; } sidedef { sector = 1; }
linedef { v1 = 0; v2 = 3; sidefront = 0; blocking = true; }
linedef { v1 = 3; v2 = 2; sidefront = 1; Blocking = TRUE; }
linedef { v1 = 2; v2 = 1; sidefront = 2; blocking = true; }
linedef { v1 = 1; v2 = 0; sidefront = 3; blocking = true; id = 7; special = 80; arg0 = 3; playeruse = true; repeatspecial = true; }
linedef { v1 = 4; v2 = 5; sidefront = 4; sideback = 8; twosided = true; }
linedef { v1 = 5; v2 = 6; sidefront = 5; sideback = 9; twosided = true; }
linedef { v1 = 6; v2 = 7; sidefront = 6; sideback = 10; twosided = true; }
linedef { v1 = 7; v2 = 4; sidefront = 7; sideback = 11; twosided = true; }
sector { heightfloor = 0; heightceiling = 128; texturefloor = "FLOOR"; textureceiling = "CEIL"; user_gravity = 0.5; }
sector { heightfloor = 32; heightceiling = 128; texturefloor = "FLOOR"; textureceiling = "CEIL"; lightlevel = 200; id = 3; }
thing { x = 32; y = 32; angle = 90; type = 1; skill1 = true; single = true; }
thing { x = 128.5; y = 128; height = 8; type = 2014; id = 5; special = 80; arg0 = 1; dormant = true; }
vavoombox { foo = 1; } // unknown block, kept
'''
def generate(ctx):
W = wadgen()
root = ctx.nix("freedoom", ["sh", "-c", "dirname $(dirname $(readlink -f $(command -v freedoom2)))"]).decode().strip()
full = open(os.path.join(root, W.FREEDOOM), "rb").read()
sel, rng = W.cut(full)
sel += rng("P_START", "P_END", 40) + rng("F_START", "F_END", 40)
binary = W.write(b"IWAD", sel)
text = to_udmf(dict(sel[1:11]))
textmap = W.write(b"PWAD", [("MAP01", b""), ("TEXTMAP", text.encode()), ("ENDMAP", b"")] + sel[11:])
ctx.emit("udmf", {"binary": binary, "textmap": textmap, "text": text, "room": ROOM})