model/d3map: Doom 3 / Quake 4 editor .map (Version 2 / 3): brushDef3 through codecs/model/Brush, patchDef2 / 3 through codecs/model/Patch, entities as nodes; side areas checked against qhull

This commit is contained in:
4DBug committed 2026-11-01 19:06:29 -06:00
1 parent 4bd59a30c8
commit 0f0da6e8ea
13 files changed
+2945 -1101

No files matched your search

+2 -1
View File
@@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats
<!-- formats:begin -->
179 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
180 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities.
| Category | Format | Extensions | Read | Write |
@@ -110,6 +110,7 @@ adds each format's capabilities.
| 3D models | 3mf | .3mf | yes | yes |
| 3D models | b3d | .b3d | yes | - |
| 3D models | bsp | .bsp | yes | - |
| 3D models | d3map | .map | yes | - |
| 3D models | dae | .dae .zae | yes | yes |
| 3D models | fbx | .fbx | yes | yes |
| 3D models | gltf | .gltf .glb | yes | yes |
+492
View File
@@ -1616,6 +1616,18 @@ local list: { Entry } = {
return __include("model/bsp")
end,
},
{
name = "d3map",
category = "model",
path = "model/d3map",
extensions = { "map" },
mime = { "text/x-doom3-map" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Brush", "codecs/model/Patch", "codecs/model/Mat4", "codecs/text/Lexer" },
caps = { decode = true, encode = false, patches = true, variants = { "doom3", "quake4" } },
load = function()
return __include("model/d3map")
end,
},
{
name = "dae",
category = "model",
@@ -146847,6 +146859,486 @@ end
return Quake3
end
__FILES["model/d3map"] = function()
-- model/d3map: Doom 3 / Quake 4 / Prey editor .map ("Version 2" / "Version 3"), read only. brushDef3 sides (plane
-- equations, Doom 3 texture matrices on the ComputeAxisBase axes) become polygons through codecs/model/Brush,
-- patchDef2 / patchDef3 surfaces grids through codecs/model/Patch (patchDef3: its explicit subdivisions); a mesh per
-- entity with geometry, entities as nodes (keys in extras; origin / rotation / angle on point entities), materials as
-- URIs. From the Doom 3 GPL source docs (MapFile.cpp layout; no code taken). Not supported: writing, brushDef (Quake
-- III brush primitives) and Version 1 brushes (counted in meta.skipped), compiling (see model/proc for dmap output).
-- ------------------------------------------------------------------------------------------------ requires
local Err = __include("core/Err")
local Bytes = __include("core/Bytes")
local Sniff = __include("core/Sniff")
local Types = __include("Types")
local Brush = __include("codecs/model/Brush")
local Patch = __include("codecs/model/Patch")
local Mat4 = __include("codecs/model/Mat4")
local Parse = __include("model/d3map/Parse")
-- ------------------------------------------------------------------------------------------------ contract
local D3map = {
name = "d3map",
category = "model",
extensions = { "map" },
mime = { "text/x-doom3-map" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Brush", "codecs/model/Patch", "codecs/model/Mat4", "codecs/text/Lexer" },
caps = { decode = true, encode = false, patches = true, variants = { "doom3", "quake4" } },
}
-- ------------------------------------------------------------------------------------------------ types
type DecodeOptions = {
hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false
merge: boolean?, -- merge coplanar faces with the same material and projection, default false
epsilon: number?, -- default 1e-3
patchLevel: number?, -- patchDef2 segments per sub-patch, default 4
skip: { string }?, -- material names left out of the meshes ("textures/common/caulk", ...)
maxPrimitives: number?, -- brushes + patches, default 2^20
maxPolygons: number?, -- default 2^20
}
-- ------------------------------------------------------------------------------------------------ constants
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
-- ------------------------------------------------------------------------------------------------ sniff
function D3map.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 512, true)
for _ = 1, 16 do
local rest = string.match(head, "^//[^\n]*\n%s*(.*)$")
if not rest then
break
end
head = rest
end
return if string.match(head, "^Version%s+[123]%s") then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Grid = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } }
local function side(s: Parse.Side): Brush.Face?
local a, b, c, d = s.plane[1], s.plane[2], s.plane[3], s.plane[4]
local l = math.sqrt(a * a + b * b + c * c)
if l < 1e-9 then
return nil
end
-- a x + b y + c z + d = 0 with the normal outward: inside is n . p <= -d
return { plane = { a / l, b / l, c / l, -d / l }, texture = s.material, bp = s.matrix, flags = s.flags }
end
local function addPatch(prim: Parse.Prim, level: number, g: Grid): boolean
local w, h = prim.width :: number, prim.height :: number
local src = prim.points :: { number }
if not Patch.valid(w, h, #src // 5) then
return false
end
-- the file lists the grid column by column; Patch wants rows (point (i, j) at j * w + i)
local rows = table.create(w * h * 5, 0) :: { number }
for col = 0, w - 1 do
for row = 0, h - 1 do
table.move(src, (col * h + row) * 5 + 1, (col * h + row) * 5 + 5, (row * w + col) * 5 + 1, rows)
end
end
local info = prim.info :: { number }
local explicit = prim.type == "patchDef3"
local su: number = if explicit then math.max(1, info[3] or 1) else level
local sv: number = if explicit then math.max(1, info[4] or 1) else level
local pts, gw, gh = Patch.grid(rows, w, h, 5, su, sv)
if not pts then
return false
end
local normals = Patch.normals(pts, 5, gw, gh)
local first = #g.pos // 3
local P, N, U = g.pos, g.nrm, g.uv
for v = 0, gw * gh - 1 do
P[#P + 1], P[#P + 2], P[#P + 3] = pts[v * 5 + 1], pts[v * 5 + 2], pts[v * 5 + 3]
U[#U + 1], U[#U + 2] = pts[v * 5 + 4], pts[v * 5 + 5]
N[#N + 1], N[#N + 2], N[#N + 3] = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3]
end
local I = g.idx
for _, t in Patch.triangles(gw, gh) do
I[#I + 1] = first + t
end
return true
end
local function gridPrimitive(g: Grid): Types.Primitive
local n, ni = #g.pos // 3, #g.idx
local bp, bn, bu, bi = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(ni * 4)
for i = 0, n - 1 do
for c = 0, 2 do
writef32(bp, i * 12 + c * 4, g.pos[i * 3 + c + 1])
writef32(bn, i * 12 + c * 4, g.nrm[i * 3 + c + 1])
end
writef32(bu, i * 8, g.uv[i * 2 + 1])
writef32(bu, i * 8 + 4, g.uv[i * 2 + 2])
end
for i = 0, ni - 1 do
writeu32(bi, i * 4, g.idx[i + 1])
end
local attributes = { POSITION = Scene.accessor(bp, "f32", 3, n), NORMAL = Scene.accessor(bn, "f32", 3, n), TEXCOORD_0 = Scene.accessor(bu, "f32", 2, n) }
return { attributes = attributes, indices = Scene.accessor(bi, "u32", 1, ni), mode = "triangles" :: any }
end
local function numbers(s: string?, n: number): { number }?
if type(s) ~= "string" then
return nil
end
local out = {}
for w in string.gmatch(s, "%S+") do
local v = tonumber(w)
if not v then
return nil
end
table.insert(out, v)
end
return if #out == n then out else nil
end
-- "rotation": the 3 x 3 axis matrix by rows (row k = local axis k in the world); "angle": yaw in degrees
local function orientation(keys: { [string]: string }): { number }?
local m = numbers(keys.rotation, 9)
if m then
return Mat4.quat({ m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, 0, 0, 0, 1 })
end
local a = tonumber(keys.angle)
if a then
local h = math.rad(a) / 2
return { 0, 0, math.sin(h), math.cos(h) }
end
return nil
end
function D3map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text = Sniff.dropBom(r:string(r:remaining()))
if r.err then
return nil, r.err
end
local m, msg = Parse.parse(text, opts and opts.maxPrimitives)
if not m then
return nil, Err.from(msg)
end
if #m.entities == 0 then
return nil, Err.new(Err.CORRUPT, "no entities")
end
local skip: { [string]: boolean } = {}
for _, s in opts and opts.skip or {} do
skip[string.lower(s)] = true
end
local scene = Scene.new()
scene.meta.up = "z"
local root: Types.Node = { name = "map", children = {} }
scene.nodes[1] = root
scene.roots[1] = 1
local matIndex: { [string]: number } = {}
local function material(nm: string): number
local i = matIndex[nm]
if not i then
table.insert(scene.textures, { name = nm, uri = nm })
local mat = Scene.material(nm)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
table.insert(scene.materials, mat)
i = #scene.materials
matIndex[nm] = i
end
return i
end
local stats = { brushes = 0, patches = 0, skippedPrimitives = 0, skippedSides = 0, badPatches = 0 }
local entities: { { [string]: string } } = {}
local total = 0
local maxPolys = opts and opts.maxPolygons or 2 ^ 20
for ei, ent in m.entities do
local keys = ent.keys
table.insert(entities, keys)
stats.skippedPrimitives += ent.skipped
local brushes: { { Brush.Face } } = {}
local grids: { [string]: Grid } = {}
local gridOrder: { string } = {}
for _, prim in ent.prims do
if prim.sides then
stats.brushes += 1
local faces: { Brush.Face } = {}
for _, s in prim.sides do
local f = side(s)
if f then
table.insert(faces, f)
else
stats.skippedSides += 1
end
end
table.insert(brushes, faces)
elseif prim.points then
stats.patches += 1
local mname = prim.material or ""
if not skip[string.lower(mname)] then
local g = grids[mname]
if not g then
g = { pos = {}, nrm = {}, uv = {}, idx = {} }
grids[mname] = g
table.insert(gridOrder, mname)
end
if not addPatch(prim, opts and opts.patchLevel or 4, g :: Grid) then
stats.badPatches += 1
end
end
end
end
local prims: { Types.Primitive } = {}
if #brushes > 0 then
local polys, perr = Brush.polygons(brushes, { hull = opts and opts.hull, merge = opts and opts.merge, epsilon = opts and opts.epsilon, maxPolygons = maxPolys })
if not polys then
return nil, Err.from(perr)
end
total += #polys
if total > maxPolys then
return nil, Err.new(Err.LIMIT, "too many polygons")
end
local keep: { Brush.Polygon } = {}
for _, poly in polys do
if not skip[string.lower(brushes[poly.brush][poly.face].texture or "")] then
table.insert(keep, poly)
end
end
-- Doom 3 texture matrices are in texture widths already: the size divides nothing
local function unit(_: string): (number, number)
return 1, 1
end
for _, built in Brush.primitives(keep, brushes, unit) do
built.primitive.material = material(built.texture)
built.primitive.extras = { d3map = { material = built.texture } }
table.insert(prims, built.primitive)
end
end
for _, mname in gridOrder do
local g = grids[mname]
if #g.idx > 0 then
local prim = gridPrimitive(g)
prim.material = material(mname)
prim.extras = { d3map = { material = mname, patch = true } }
table.insert(prims, prim)
end
end
local node: Types.Node = { name = keys.name or keys.classname or ("entity " .. (ei - 1)), children = {}, extras = { classname = keys.classname, keys = keys, entity = ei - 1 } }
if #prims > 0 then
table.insert(scene.meshes, { name = node.name, primitives = prims })
node.mesh = #scene.meshes
elseif #ent.prims == 0 then
node.translation = numbers(keys.origin, 3)
node.rotation = orientation(keys)
end
table.insert(scene.nodes, node)
table.insert(root.children, #scene.nodes)
end
scene.meta.entities = entities
scene.meta.counts = stats
scene.meta.source = { format = "d3map", version = m.version, variant = if m.version >= 3 then "quake4" else "doom3", entities = #m.entities, brushes = stats.brushes, patches = stats.patches }
return scene, nil
end
return D3map
end
__FILES["model/d3map/Parse"] = function()
-- model/d3map/Parse: Doom 3 / Quake 4 editor .map text ("Version 2" / "Version 3"; idMapFile / idMapEntity /
-- idMapBrush / idMapPatch layouts of the Doom 3 GPL source docs, no code taken) to entities with brushDef3 sides
-- (plane a b c d with a x + b y + c z + d = 0, normal out of the brush; 2 x 3 texture matrix) and patchDef2 / 3.
local Lexer = __include("codecs/text/Lexer")
local Parse = {}
type Side = { plane: { number }, matrix: { { number } }, material: string, flags: { number } }
type Prim = {
type: string, -- "brushDef3" | "patchDef2" | "patchDef3"
sides: { Side }?,
material: string?,
info: { number }?, -- patchDef2: width height 0 0 0; patchDef3: width height subdivX subdivY 0 0 0
width: number?,
height: number?,
points: { number }?, -- x y z s t per control point, in file order (column by column)
}
type Entity = { keys: { [string]: string }, prims: { Prim }, skipped: number }
type Map = { version: number, entities: { Entity } }
type P = { L: Lexer.Lexer, err: string? }
local function fail(p: P, msg: string)
if not p.err then
p.err = (p.L.err or msg) .. " at line " .. p.L:line()
end
end
local function want(p: P, c: string)
local k, v = p.L:next()
if k ~= "punct" or v ~= c then
fail(p, "expected " .. c)
end
end
local function number(p: P): number
local k, v = p.L:next()
if k ~= "number" then
fail(p, "expected a number")
return 0
end
return v
end
local function tuple(p: P, n: number): { number }
want(p, "(")
local out = table.create(n, 0)
for i = 1, n do
out[i] = number(p)
end
want(p, ")")
return out
end
local function name(p: P): string
local k, v = p.L:next()
if k == "string" or k == "word" then
return v
end
fail(p, "expected a material name")
return ""
end
local function brushDef3(p: P): Prim
want(p, "{")
local sides: { Side } = {}
while not p.err do
local k, v = p.L:peek()
if k == "punct" and v == "}" then
p.L:next()
break
end
local plane = tuple(p, 4)
want(p, "(")
local m1 = tuple(p, 3)
local m2 = tuple(p, 3)
want(p, ")")
local material = name(p)
local flags: { number } = {}
while not p.err do
local fk = p.L:peek()
if fk ~= "number" then
break
end
table.insert(flags, number(p))
end
table.insert(sides, { plane = plane, matrix = { m1, m2 }, material = material, flags = flags })
end
return { type = "brushDef3", sides = sides }
end
local function patchDef(p: P, kind: string, maxPoints: number): Prim
want(p, "{")
local material = name(p)
local info = tuple(p, if kind == "patchDef3" then 7 else 5)
local w, h = info[1], info[2]
if p.err then
return { type = kind }
end
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w * h > maxPoints then
fail(p, "limit: patch size " .. w .. " x " .. h)
return { type = kind }
end
local pts: { number } = table.create(w * h * 5, 0)
want(p, "(")
for i = 0, w - 1 do
want(p, "(")
for j = 0, h - 1 do
local v = tuple(p, 5)
if p.err then
return { type = kind }
end
table.move(v, 1, 5, (i * h + j) * 5 + 1, pts)
end
want(p, ")")
end
want(p, ")")
want(p, "}")
return { type = kind, material = material, info = info, width = w, height = h, points = pts }
end
function Parse.parse(text: string, maxPrims: number?): (Map?, string?)
local p: P = { L = Lexer.new(text), err = nil }
local k, v = p.L:next()
if k ~= "word" or v ~= "Version" then
return nil, "missing the Version line"
end
local version = number(p)
local m: Map = { version = version, entities = {} }
local limit = maxPrims or 2 ^ 20
local count = 0
while not p.err do
local ek, ev = p.L:next()
if not ek then
if p.L.err then
fail(p, p.L.err)
end
break
end
if ek ~= "punct" or ev ~= "{" then
fail(p, "expected an entity")
break
end
local ent: Entity = { keys = {}, prims = {}, skipped = 0 }
while not p.err do
local tk, tv = p.L:next()
if tk == "string" then
local vk, vv = p.L:next()
if vk ~= "string" then
fail(p, "expected a key value")
break
end
ent.keys[tv] = vv
elseif tk == "punct" and tv == "{" then
count += 1
if count > limit then
p.err = "limit: more than " .. limit .. " primitives"
break
end
local pk, pv = p.L:peek()
if pk == "word" and (pv == "brushDef3" or pv == "patchDef2" or pv == "patchDef3") then
p.L:next()
local prim = if pv == "brushDef3" then brushDef3(p) else patchDef(p, pv, 2 ^ 16)
want(p, "}")
table.insert(ent.prims, prim)
else
-- brushDef (Quake III brush primitives) and Version 1 brushes are not read
ent.skipped += 1
local depth = 1
while not p.err and depth > 0 do
local sk, sv = p.L:next()
if not sk then
fail(p, "unterminated primitive")
elseif sk == "punct" and sv == "{" then
depth += 1
elseif sk == "punct" and sv == "}" then
depth -= 1
end
end
end
elseif tk == "punct" and tv == "}" then
break
else
fail(p, if tk then "unexpected " .. tostring(tv) else "unterminated entity")
end
end
table.insert(m.entities, ent)
end
if p.err then
return nil, p.err
end
return m, nil
end
return Parse
end
__FILES["model/dae"] = function()
-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry,
File diff suppressed because it is too large. Load diff
+492
View File
@@ -2249,6 +2249,18 @@ local list= {
return __include("model/bsp")
end,
},
{
name = "d3map",
category = "model",
path = "model/d3map",
extensions = { "map" },
mime = { "text/x-doom3-map" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Brush", "codecs/model/Patch", "codecs/model/Mat4", "codecs/text/Lexer" },
caps = { decode = true, encode = false, patches = true, variants = { "doom3", "quake4" } },
load = function()
return __include("model/d3map")
end,
},
{
name = "dae",
category = "model",
@@ -147480,6 +147492,486 @@ end
return Quake3
end
__FILES["model/d3map"] = function()
local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict
-- model/d3map: Doom 3 / Quake 4 / Prey editor .map ("Version 2" / "Version 3"), read only. brushDef3 sides (plane
-- equations, Doom 3 texture matrices on the ComputeAxisBase axes) become polygons through codecs/model/Brush,
-- patchDef2 / patchDef3 surfaces grids through codecs/model/Patch (patchDef3: its explicit subdivisions); a mesh per
-- entity with geometry, entities as nodes (keys in extras; origin / rotation / angle on point entities), materials as
-- URIs. From the Doom 3 GPL source docs (MapFile.cpp layout; no code taken). Not supported: writing, brushDef (Quake
-- III brush primitives) and Version 1 brushes (counted in meta.skipped), compiling (see model/proc for dmap output).
-- ------------------------------------------------------------------------------------------------ requires
local Err = __include("core/Err")
local Bytes = __include("core/Bytes")
local Sniff = __include("core/Sniff")
local Types = __include("Types")
local Brush = __include("codecs/model/Brush")
local Patch = __include("codecs/model/Patch")
local Mat4 = __include("codecs/model/Mat4")
local Parse = __include("model/d3map/Parse")
-- ------------------------------------------------------------------------------------------------ contract
local D3map = {
name = "d3map",
category = "model",
extensions = { "map" },
mime = { "text/x-doom3-map" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Brush", "codecs/model/Patch", "codecs/model/Mat4", "codecs/text/Lexer" },
caps = { decode = true, encode = false, patches = true, variants = { "doom3", "quake4" } },
}
-- ------------------------------------------------------------------------------------------------ types
-- ------------------------------------------------------------------------------------------------ constants
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
-- ------------------------------------------------------------------------------------------------ sniff
function D3map.sniff(r)
local head = Sniff.text(r, 512, true)
for _ = 1, 16 do
local rest = string.match(head, "^//[^\n]*\n%s*(.*)$")
if not rest then
break
end
head = rest
end
return string.match(head, "^Version%s+[123]%s") and 1 or 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function side(s)
local a, b, c, d = s.plane[1], s.plane[2], s.plane[3], s.plane[4]
local l = math.sqrt(a * a + b * b + c * c)
if l < 1e-9 then
return nil
end
-- a x + b y + c z + d = 0 with the normal outward: inside is n . p <= -d
return { plane = { a / l, b / l, c / l, -d / l }, texture = s.material, bp = s.matrix, flags = s.flags }
end
local function addPatch(prim, level, g)
local w, h = prim.width , prim.height
local src = prim.points
if not Patch.valid(w, h, math.floor(#src / 5)) then
return false
end
-- the file lists the grid column by column; Patch wants rows (point (i, j) at j * w + i)
local rows = (table.create(w * h * 5, 0) )
for col = 0, w - 1 do
for row = 0, h - 1 do
table.move(src, (col * h + row) * 5 + 1, (col * h + row) * 5 + 5, (row * w + col) * 5 + 1, rows)
end
end
local info = prim.info
local explicit = prim.type == "patchDef3"
local su= (explicit and{(math.max(1, info[3] or 1) )}or{level
})[1] local sv= (explicit and{(math.max(1, info[4] or 1) )}or{level
})[1] local pts, gw, gh = Patch.grid(rows, w, h, 5, su, sv)
if not pts then
return false
end
local normals = Patch.normals(pts, 5, gw, gh)
local first = math.floor(#g.pos / 3
) local P, N, U = g.pos, g.nrm, g.uv
for v = 0, gw * gh - 1 do
P[#P + 1], P[#P + 2], P[#P + 3] = pts[v * 5 + 1], pts[v * 5 + 2], pts[v * 5 + 3]
U[#U + 1], U[#U + 2] = pts[v * 5 + 4], pts[v * 5 + 5]
N[#N + 1], N[#N + 2], N[#N + 3] = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3]
end
local I = g.idx
for _, t in __iter(Patch.triangles(gw, gh)) do
I[#I + 1] = first + t
end
return true
end
local function gridPrimitive(g)
local n, ni = math.floor(#g.pos / 3), #g.idx
local bp, bn, bu, bi = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(ni * 4)
for i = 0, n - 1 do
for c = 0, 2 do
writef32(bp, i * 12 + c * 4, g.pos[i * 3 + c + 1])
writef32(bn, i * 12 + c * 4, g.nrm[i * 3 + c + 1])
end
writef32(bu, i * 8, g.uv[i * 2 + 1])
writef32(bu, i * 8 + 4, g.uv[i * 2 + 2])
end
for i = 0, ni - 1 do
writeu32(bi, i * 4, g.idx[i + 1])
end
local attributes = { POSITION = Scene.accessor(bp, "f32", 3, n), NORMAL = Scene.accessor(bn, "f32", 3, n), TEXCOORD_0 = Scene.accessor(bu, "f32", 2, n) }
return { attributes = attributes, indices = Scene.accessor(bi, "u32", 1, ni), mode = "triangles" }
end
local function numbers(s, n)
if type(s) ~= "string" then
return nil
end
local out = {}
for w in __iter(string.gmatch(s, "%S+")) do
local v = tonumber(w)
if not v then
return nil
end
table.insert(out, v)
end
return (#out == n and{out }or{nil
})[1]end
-- "rotation": the 3 x 3 axis matrix by rows (row k = local axis k in the world); "angle": yaw in degrees
local function orientation(keys)
local m = numbers(keys.rotation, 9)
if m then
return Mat4.quat({ m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, 0, 0, 0, 1 })
end
local a = tonumber(keys.angle)
if a then
local h = math.rad(a) / 2
return { 0, 0, math.sin(h), math.cos(h) }
end
return nil
end
function D3map.decode(r, opts)
local text = Sniff.dropBom(r:string(r:remaining()))
if r.err then
return nil, r.err
end
local m, msg = Parse.parse(text, opts and opts.maxPrimitives)
if not m then
return nil, Err.from(msg)
end
if #m.entities == 0 then
return nil, Err.new(Err.CORRUPT, "no entities")
end
local skip= {}
for _, s in __iter(opts and opts.skip or {}) do
skip[string.lower(s)] = true
end
local scene = Scene.new()
scene.meta.up = "z"
local root= { name = "map", children = {} }
scene.nodes[1] = root
scene.roots[1] = 1
local matIndex= {}
local function material(nm)
local i = matIndex[nm]
if not i then
table.insert(scene.textures, { name = nm, uri = nm })
local mat = Scene.material(nm)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
table.insert(scene.materials, mat)
i = #scene.materials
matIndex[nm] = i
end
return i
end
local stats = { brushes = 0, patches = 0, skippedPrimitives = 0, skippedSides = 0, badPatches = 0 }
local entities= {}
local total = 0
local maxPolys = opts and opts.maxPolygons or 2 ^ 20
for ei, ent in __iter(m.entities) do
local keys = ent.keys
table.insert(entities, keys)
stats.skippedPrimitives =stats.skippedPrimitives+ ent.skipped
local brushes= {}
local grids= {}
local gridOrder= {}
for _, prim in __iter(ent.prims) do
if prim.sides then
stats.brushes =stats.brushes+ 1
local faces= {}
for _, s in __iter(prim.sides) do
local f = side(s)
if f then
table.insert(faces, f)
else
stats.skippedSides =stats.skippedSides+ 1
end
end
table.insert(brushes, faces)
elseif prim.points then
stats.patches =stats.patches+ 1
local mname = prim.material or ""
if not skip[string.lower(mname)] then
local g = grids[mname]
if not g then
g = { pos = {}, nrm = {}, uv = {}, idx = {} }
grids[mname] = g
table.insert(gridOrder, mname)
end
if not addPatch(prim, opts and opts.patchLevel or 4, g ) then
stats.badPatches =stats.badPatches+ 1
end
end
end
end
local prims= {}
if #brushes > 0 then
local polys, perr = Brush.polygons(brushes, { hull = opts and opts.hull, merge = opts and opts.merge, epsilon = opts and opts.epsilon, maxPolygons = maxPolys })
if not polys then
return nil, Err.from(perr)
end
total =total+ #polys
if total > maxPolys then
return nil, Err.new(Err.LIMIT, "too many polygons")
end
local keep= {}
for _, poly in __iter(polys) do
if not skip[string.lower(brushes[poly.brush][poly.face].texture or "")] then
table.insert(keep, poly)
end
end
-- Doom 3 texture matrices are in texture widths already: the size divides nothing
local function unit(_)
return 1, 1
end
for _, built in __iter(Brush.primitives(keep, brushes, unit)) do
built.primitive.material = material(built.texture)
built.primitive.extras = { d3map = { material = built.texture } }
table.insert(prims, built.primitive)
end
end
for _, mname in __iter(gridOrder) do
local g = grids[mname]
if #g.idx > 0 then
local prim = gridPrimitive(g)
prim.material = material(mname)
prim.extras = { d3map = { material = mname, patch = true } }
table.insert(prims, prim)
end
end
local node= { name = keys.name or keys.classname or ("entity " .. (ei - 1)), children = {}, extras = { classname = keys.classname, keys = keys, entity = ei - 1 } }
if #prims > 0 then
table.insert(scene.meshes, { name = node.name, primitives = prims })
node.mesh = #scene.meshes
elseif #ent.prims == 0 then
node.translation = numbers(keys.origin, 3)
node.rotation = orientation(keys)
end
table.insert(scene.nodes, node)
table.insert(root.children, #scene.nodes)
end
scene.meta.entities = entities
scene.meta.counts = stats
scene.meta.source = { format = "d3map", version = m.version, variant = m.version >= 3 and"quake4" or"doom3", entities = #m.entities, brushes = stats.brushes, patches = stats.patches }
return scene, nil
end
return D3map
end
__FILES["model/d3map/Parse"] = function()
local __compat = __compat local type = __compat.type --!strict
-- model/d3map/Parse: Doom 3 / Quake 4 editor .map text ("Version 2" / "Version 3"; idMapFile / idMapEntity /
-- idMapBrush / idMapPatch layouts of the Doom 3 GPL source docs, no code taken) to entities with brushDef3 sides
-- (plane a b c d with a x + b y + c z + d = 0, normal out of the brush; 2 x 3 texture matrix) and patchDef2 / 3.
local Lexer = __include("codecs/text/Lexer")
local Parse = {}
local function fail(p, msg)
if not p.err then
p.err = (p.L.err or msg) .. " at line " .. p.L:line()
end
end
local function want(p, c)
local k, v = p.L:next()
if k ~= "punct" or v ~= c then
fail(p, "expected " .. c)
end
end
local function number(p)
local k, v = p.L:next()
if k ~= "number" then
fail(p, "expected a number")
return 0
end
return v
end
local function tuple(p, n)
want(p, "(")
local out = table.create(n, 0)
for i = 1, n do
out[i] = number(p)
end
want(p, ")")
return out
end
local function name(p)
local k, v = p.L:next()
if k == "string" or k == "word" then
return v
end
fail(p, "expected a material name")
return ""
end
local function brushDef3(p)
want(p, "{")
local sides= {}
while not p.err do
local k, v = p.L:peek()
if k == "punct" and v == "}" then
p.L:next()
break
end
local plane = tuple(p, 4)
want(p, "(")
local m1 = tuple(p, 3)
local m2 = tuple(p, 3)
want(p, ")")
local material = name(p)
local flags= {}
while not p.err do
local fk = p.L:peek()
if fk ~= "number" then
break
end
table.insert(flags, number(p))
end
table.insert(sides, { plane = plane, matrix = { m1, m2 }, material = material, flags = flags })
end
return { type = "brushDef3", sides = sides }
end
local function patchDef(p, kind, maxPoints)
want(p, "{")
local material = name(p)
local info = tuple(p, kind == "patchDef3" and 7 or 5)
local w, h = info[1], info[2]
if p.err then
return { type = kind }
end
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w * h > maxPoints then
fail(p, "limit: patch size " .. w .. " x " .. h)
return { type = kind }
end
local pts= table.create(w * h * 5, 0)
want(p, "(")
for i = 0, w - 1 do
want(p, "(")
for j = 0, h - 1 do
local v = tuple(p, 5)
if p.err then
return { type = kind }
end
table.move(v, 1, 5, (i * h + j) * 5 + 1, pts)
end
want(p, ")")
end
want(p, ")")
want(p, "}")
return { type = kind, material = material, info = info, width = w, height = h, points = pts }
end
function Parse.parse(text, maxPrims)
local p= { L = Lexer.new(text), err = nil }
local k, v = p.L:next()
if k ~= "word" or v ~= "Version" then
return nil, "missing the Version line"
end
local version = number(p)
local m= { version = version, entities = {} }
local limit = maxPrims or 2 ^ 20
local count = 0
while not p.err do
local ek, ev = p.L:next()
if not ek then
if p.L.err then
fail(p, p.L.err)
end
break
end
if ek ~= "punct" or ev ~= "{" then
fail(p, "expected an entity")
break
end
local ent= { keys = {}, prims = {}, skipped = 0 }
while not p.err do
local tk, tv = p.L:next()
if tk == "string" then
local vk, vv = p.L:next()
if vk ~= "string" then
fail(p, "expected a key value")
break
end
ent.keys[tv] = vv
elseif tk == "punct" and tv == "{" then
count =count+ 1
if count > limit then
p.err = "limit: more than " .. limit .. " primitives"
break
end
local pk, pv = p.L:peek()
if pk == "word" and (pv == "brushDef3" or pv == "patchDef2" or pv == "patchDef3") then
p.L:next()
local prim = (pv == "brushDef3" and{(brushDef3(p) )}or{(patchDef(p, pv, 2 ^ 16)
)})[1] want(p, "}")
table.insert(ent.prims, prim)
else
-- brushDef (Quake III brush primitives) and Version 1 brushes are not read
ent.skipped =ent.skipped+ 1
local depth = 1
while not p.err and depth > 0 do
local sk, sv = p.L:next()
if not sk then
fail(p, "unterminated primitive")
elseif sk == "punct" and sv == "{" then
depth =depth+ 1
elseif sk == "punct" and sv == "}" then
depth =depth- 1
end
end
end
elseif tk == "punct" and tv == "}" then
break
else
fail(p, (tk and(("unexpected " .. tostring(tv) ))or("unterminated entity")))
end
end
table.insert(m.entities, ent)
end
if p.err then
return nil, p.err
end
return m, nil
end
return Parse
end
__FILES["model/dae"] = function()
local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict
-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry,
File diff suppressed because it is too large. Load diff
+1
View File
@@ -66,6 +66,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
| model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` |
| model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` |
| model | d3map | .map | yes | - | patches: true, variants: "doom3", "quake4" | `tests/model/d3map.luau` |
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` |
+14
View File
@@ -535,6 +535,13 @@ A compiled `.proc` file (dmap's render geometry: `mapProcFile003`, Quake 4's `PR
materials are URIs. id Tech 4 triangles are clockwise-front, so they are turned counter-clockwise. The portals between
areas, the BSP nodes and the shadow models load as data in `meta.proc`.
The editor's `.map` (`Version 2` for Doom 3, `Version 3` for Quake 4; told apart from Quake's `.map` by that line)
loads as a Scene too: `brushDef3` brushes (plane equations) become polygons through the same brush clipper as the
Quake maps, with Doom 3's texture matrices, and `patchDef2` / `patchDef3` surfaces become triangle grids (patchDef3 at
its stored subdivisions, patchDef2 at `patchLevel` segments per sub-patch). Each entity is a node with its keys in
`extras.keys`; entities with geometry get a mesh (in world coordinates), point entities their `origin`, `rotation`
or `angle`. `skip` leaves materials out (`"textures/common/caulk"`), `hull` drops faces hidden inside other brushes.
```luau
local level = assert(F.model.load(procText))
assert(level.meshes[1].name == "_area0" and level.meta.up == "z")
@@ -542,6 +549,12 @@ local proc = level.meta.proc
assert(proc.areas == 2 and proc.portals[1].positive == 1 and #proc.portals[1].points == 12)
assert(proc.nodes[1].negative == -1) -- < 0: area -1 - n; > 0: a node (1-based); 0: solid
assert(level.materials[1].name == "textures/base_wall/lfwall1")
local room = assert(F.model.load(d3mapText, { name = "room.map", skip = { "textures/common/caulk" } }))
assert(room.meta.source.format == "d3map" and room.meta.source.variant == "doom3")
assert(#room.meshes[1].primitives == 1) -- the floor material; caulk skipped
local start = room.nodes[3]
assert(start.extras.classname == "info_player_start" and start.translation[3] == 1)
```
## Blitz3D (B3D)
@@ -784,6 +797,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3)
| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above |
| SMD | yes | yes | Valve studiomdl data |
| Doom 3 / Quake 4 `.proc` | yes | | render geometry per area, portals and BSP nodes as data |
| Doom 3 / Quake 4 `.map` (d3map) | yes | | brushDef3, patchDef2 / 3, entities as nodes |
| UDMF (`.udmf`, `TEXTMAP`) | yes | | Doom maps as text: see "Doom maps (UDMF)" above |
| 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) |
+12
View File
@@ -746,6 +746,18 @@ local list: { Entry } = {
return require("@rosetta/model/bsp")
end,
},
{
name = "d3map",
category = "model",
path = "model/d3map",
extensions = { "map" },
mime = { "text/x-doom3-map" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Brush", "codecs/model/Patch", "codecs/model/Mat4", "codecs/text/Lexer" },
caps = { decode = true, encode = false, patches = true, variants = { "doom3", "quake4" } },
load = function()
return require("@rosetta/model/d3map")
end,
},
{
name = "dae",
category = "model",
+196
View File
@@ -0,0 +1,196 @@
--!strict
-- model/d3map/Parse: Doom 3 / Quake 4 editor .map text ("Version 2" / "Version 3"; idMapFile / idMapEntity /
-- idMapBrush / idMapPatch layouts of the Doom 3 GPL source docs, no code taken) to entities with brushDef3 sides
-- (plane a b c d with a x + b y + c z + d = 0, normal out of the brush; 2 x 3 texture matrix) and patchDef2 / 3.
local Lexer = require("@rosetta/codecs/text/Lexer")
local Parse = {}
export type Side = { plane: { number }, matrix: { { number } }, material: string, flags: { number } }
export type Prim = {
type: string, -- "brushDef3" | "patchDef2" | "patchDef3"
sides: { Side }?,
material: string?,
info: { number }?, -- patchDef2: width height 0 0 0; patchDef3: width height subdivX subdivY 0 0 0
width: number?,
height: number?,
points: { number }?, -- x y z s t per control point, in file order (column by column)
}
export type Entity = { keys: { [string]: string }, prims: { Prim }, skipped: number }
export type Map = { version: number, entities: { Entity } }
type P = { L: Lexer.Lexer, err: string? }
local function fail(p: P, msg: string)
if not p.err then
p.err = (p.L.err or msg) .. " at line " .. p.L:line()
end
end
local function want(p: P, c: string)
local k, v = p.L:next()
if k ~= "punct" or v ~= c then
fail(p, "expected " .. c)
end
end
local function number(p: P): number
local k, v = p.L:next()
if k ~= "number" then
fail(p, "expected a number")
return 0
end
return v
end
local function tuple(p: P, n: number): { number }
want(p, "(")
local out = table.create(n, 0)
for i = 1, n do
out[i] = number(p)
end
want(p, ")")
return out
end
local function name(p: P): string
local k, v = p.L:next()
if k == "string" or k == "word" then
return v
end
fail(p, "expected a material name")
return ""
end
local function brushDef3(p: P): Prim
want(p, "{")
local sides: { Side } = {}
while not p.err do
local k, v = p.L:peek()
if k == "punct" and v == "}" then
p.L:next()
break
end
local plane = tuple(p, 4)
want(p, "(")
local m1 = tuple(p, 3)
local m2 = tuple(p, 3)
want(p, ")")
local material = name(p)
local flags: { number } = {}
while not p.err do
local fk = p.L:peek()
if fk ~= "number" then
break
end
table.insert(flags, number(p))
end
table.insert(sides, { plane = plane, matrix = { m1, m2 }, material = material, flags = flags })
end
return { type = "brushDef3", sides = sides }
end
local function patchDef(p: P, kind: string, maxPoints: number): Prim
want(p, "{")
local material = name(p)
local info = tuple(p, if kind == "patchDef3" then 7 else 5)
local w, h = info[1], info[2]
if p.err then
return { type = kind }
end
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w * h > maxPoints then
fail(p, "limit: patch size " .. w .. " x " .. h)
return { type = kind }
end
local pts: { number } = table.create(w * h * 5, 0)
want(p, "(")
for i = 0, w - 1 do
want(p, "(")
for j = 0, h - 1 do
local v = tuple(p, 5)
if p.err then
return { type = kind }
end
table.move(v, 1, 5, (i * h + j) * 5 + 1, pts)
end
want(p, ")")
end
want(p, ")")
want(p, "}")
return { type = kind, material = material, info = info, width = w, height = h, points = pts }
end
function Parse.parse(text: string, maxPrims: number?): (Map?, string?)
local p: P = { L = Lexer.new(text), err = nil }
local k, v = p.L:next()
if k ~= "word" or v ~= "Version" then
return nil, "missing the Version line"
end
local version = number(p)
local m: Map = { version = version, entities = {} }
local limit = maxPrims or 2 ^ 20
local count = 0
while not p.err do
local ek, ev = p.L:next()
if not ek then
if p.L.err then
fail(p, p.L.err)
end
break
end
if ek ~= "punct" or ev ~= "{" then
fail(p, "expected an entity")
break
end
local ent: Entity = { keys = {}, prims = {}, skipped = 0 }
while not p.err do
local tk, tv = p.L:next()
if tk == "string" then
local vk, vv = p.L:next()
if vk ~= "string" then
fail(p, "expected a key value")
break
end
ent.keys[tv] = vv
elseif tk == "punct" and tv == "{" then
count += 1
if count > limit then
p.err = "limit: more than " .. limit .. " primitives"
break
end
local pk, pv = p.L:peek()
if pk == "word" and (pv == "brushDef3" or pv == "patchDef2" or pv == "patchDef3") then
p.L:next()
local prim = if pv == "brushDef3" then brushDef3(p) else patchDef(p, pv, 2 ^ 16)
want(p, "}")
table.insert(ent.prims, prim)
else
-- brushDef (Quake III brush primitives) and Version 1 brushes are not read
ent.skipped += 1
local depth = 1
while not p.err and depth > 0 do
local sk, sv = p.L:next()
if not sk then
fail(p, "unterminated primitive")
elseif sk == "punct" and sv == "{" then
depth += 1
elseif sk == "punct" and sv == "}" then
depth -= 1
end
end
end
elseif tk == "punct" and tv == "}" then
break
else
fail(p, if tk then "unexpected " .. tostring(tv) else "unterminated entity")
end
end
table.insert(m.entities, ent)
end
if p.err then
return nil, p.err
end
return m, nil
end
return Parse
+280
View File
@@ -0,0 +1,280 @@
--!strict
-- model/d3map: Doom 3 / Quake 4 / Prey editor .map ("Version 2" / "Version 3"), read only. brushDef3 sides (plane
-- equations, Doom 3 texture matrices on the ComputeAxisBase axes) become polygons through codecs/model/Brush,
-- patchDef2 / patchDef3 surfaces grids through codecs/model/Patch (patchDef3: its explicit subdivisions); a mesh per
-- entity with geometry, entities as nodes (keys in extras; origin / rotation / angle on point entities), materials as
-- URIs. From the Doom 3 GPL source docs (MapFile.cpp layout; no code taken). Not supported: writing, brushDef (Quake
-- III brush primitives) and Version 1 brushes (counted in meta.skipped), compiling (see model/proc for dmap output).
-- ------------------------------------------------------------------------------------------------ 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 Brush = require("@rosetta/codecs/model/Brush")
local Patch = require("@rosetta/codecs/model/Patch")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Parse = require("@rosetta/model/d3map/Parse")
-- ------------------------------------------------------------------------------------------------ contract
local D3map = {
name = "d3map",
category = "model",
extensions = { "map" },
mime = { "text/x-doom3-map" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Brush", "codecs/model/Patch", "codecs/model/Mat4", "codecs/text/Lexer" },
caps = { decode = true, encode = false, patches = true, variants = { "doom3", "quake4" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false
merge: boolean?, -- merge coplanar faces with the same material and projection, default false
epsilon: number?, -- default 1e-3
patchLevel: number?, -- patchDef2 segments per sub-patch, default 4
skip: { string }?, -- material names left out of the meshes ("textures/common/caulk", ...)
maxPrimitives: number?, -- brushes + patches, default 2^20
maxPolygons: number?, -- default 2^20
}
-- ------------------------------------------------------------------------------------------------ constants
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
-- ------------------------------------------------------------------------------------------------ sniff
function D3map.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 512, true)
for _ = 1, 16 do
local rest = string.match(head, "^//[^\n]*\n%s*(.*)$")
if not rest then
break
end
head = rest
end
return if string.match(head, "^Version%s+[123]%s") then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Grid = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } }
local function side(s: Parse.Side): Brush.Face?
local a, b, c, d = s.plane[1], s.plane[2], s.plane[3], s.plane[4]
local l = math.sqrt(a * a + b * b + c * c)
if l < 1e-9 then
return nil
end
-- a x + b y + c z + d = 0 with the normal outward: inside is n . p <= -d
return { plane = { a / l, b / l, c / l, -d / l }, texture = s.material, bp = s.matrix, flags = s.flags }
end
local function addPatch(prim: Parse.Prim, level: number, g: Grid): boolean
local w, h = prim.width :: number, prim.height :: number
local src = prim.points :: { number }
if not Patch.valid(w, h, #src // 5) then
return false
end
-- the file lists the grid column by column; Patch wants rows (point (i, j) at j * w + i)
local rows = table.create(w * h * 5, 0) :: { number }
for col = 0, w - 1 do
for row = 0, h - 1 do
table.move(src, (col * h + row) * 5 + 1, (col * h + row) * 5 + 5, (row * w + col) * 5 + 1, rows)
end
end
local info = prim.info :: { number }
local explicit = prim.type == "patchDef3"
local su: number = if explicit then math.max(1, info[3] or 1) else level
local sv: number = if explicit then math.max(1, info[4] or 1) else level
local pts, gw, gh = Patch.grid(rows, w, h, 5, su, sv)
if not pts then
return false
end
local normals = Patch.normals(pts, 5, gw, gh)
local first = #g.pos // 3
local P, N, U = g.pos, g.nrm, g.uv
for v = 0, gw * gh - 1 do
P[#P + 1], P[#P + 2], P[#P + 3] = pts[v * 5 + 1], pts[v * 5 + 2], pts[v * 5 + 3]
U[#U + 1], U[#U + 2] = pts[v * 5 + 4], pts[v * 5 + 5]
N[#N + 1], N[#N + 2], N[#N + 3] = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3]
end
local I = g.idx
for _, t in Patch.triangles(gw, gh) do
I[#I + 1] = first + t
end
return true
end
local function gridPrimitive(g: Grid): Types.Primitive
local n, ni = #g.pos // 3, #g.idx
local bp, bn, bu, bi = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(ni * 4)
for i = 0, n - 1 do
for c = 0, 2 do
writef32(bp, i * 12 + c * 4, g.pos[i * 3 + c + 1])
writef32(bn, i * 12 + c * 4, g.nrm[i * 3 + c + 1])
end
writef32(bu, i * 8, g.uv[i * 2 + 1])
writef32(bu, i * 8 + 4, g.uv[i * 2 + 2])
end
for i = 0, ni - 1 do
writeu32(bi, i * 4, g.idx[i + 1])
end
local attributes = { POSITION = Scene.accessor(bp, "f32", 3, n), NORMAL = Scene.accessor(bn, "f32", 3, n), TEXCOORD_0 = Scene.accessor(bu, "f32", 2, n) }
return { attributes = attributes, indices = Scene.accessor(bi, "u32", 1, ni), mode = "triangles" :: any }
end
local function numbers(s: string?, n: number): { number }?
if type(s) ~= "string" then
return nil
end
local out = {}
for w in string.gmatch(s, "%S+") do
local v = tonumber(w)
if not v then
return nil
end
table.insert(out, v)
end
return if #out == n then out else nil
end
-- "rotation": the 3 x 3 axis matrix by rows (row k = local axis k in the world); "angle": yaw in degrees
local function orientation(keys: { [string]: string }): { number }?
local m = numbers(keys.rotation, 9)
if m then
return Mat4.quat({ m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, 0, 0, 0, 1 })
end
local a = tonumber(keys.angle)
if a then
local h = math.rad(a) / 2
return { 0, 0, math.sin(h), math.cos(h) }
end
return nil
end
function D3map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text = Sniff.dropBom(r:string(r:remaining()))
if r.err then
return nil, r.err
end
local m, msg = Parse.parse(text, opts and opts.maxPrimitives)
if not m then
return nil, Err.from(msg)
end
if #m.entities == 0 then
return nil, Err.new(Err.CORRUPT, "no entities")
end
local skip: { [string]: boolean } = {}
for _, s in opts and opts.skip or {} do
skip[string.lower(s)] = true
end
local scene = Scene.new()
scene.meta.up = "z"
local root: Types.Node = { name = "map", children = {} }
scene.nodes[1] = root
scene.roots[1] = 1
local matIndex: { [string]: number } = {}
local function material(nm: string): number
local i = matIndex[nm]
if not i then
table.insert(scene.textures, { name = nm, uri = nm })
local mat = Scene.material(nm)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
table.insert(scene.materials, mat)
i = #scene.materials
matIndex[nm] = i
end
return i
end
local stats = { brushes = 0, patches = 0, skippedPrimitives = 0, skippedSides = 0, badPatches = 0 }
local entities: { { [string]: string } } = {}
local total = 0
local maxPolys = opts and opts.maxPolygons or 2 ^ 20
for ei, ent in m.entities do
local keys = ent.keys
table.insert(entities, keys)
stats.skippedPrimitives += ent.skipped
local brushes: { { Brush.Face } } = {}
local grids: { [string]: Grid } = {}
local gridOrder: { string } = {}
for _, prim in ent.prims do
if prim.sides then
stats.brushes += 1
local faces: { Brush.Face } = {}
for _, s in prim.sides do
local f = side(s)
if f then
table.insert(faces, f)
else
stats.skippedSides += 1
end
end
table.insert(brushes, faces)
elseif prim.points then
stats.patches += 1
local mname = prim.material or ""
if not skip[string.lower(mname)] then
local g = grids[mname]
if not g then
g = { pos = {}, nrm = {}, uv = {}, idx = {} }
grids[mname] = g
table.insert(gridOrder, mname)
end
if not addPatch(prim, opts and opts.patchLevel or 4, g :: Grid) then
stats.badPatches += 1
end
end
end
end
local prims: { Types.Primitive } = {}
if #brushes > 0 then
local polys, perr = Brush.polygons(brushes, { hull = opts and opts.hull, merge = opts and opts.merge, epsilon = opts and opts.epsilon, maxPolygons = maxPolys })
if not polys then
return nil, Err.from(perr)
end
total += #polys
if total > maxPolys then
return nil, Err.new(Err.LIMIT, "too many polygons")
end
local keep: { Brush.Polygon } = {}
for _, poly in polys do
if not skip[string.lower(brushes[poly.brush][poly.face].texture or "")] then
table.insert(keep, poly)
end
end
-- Doom 3 texture matrices are in texture widths already: the size divides nothing
local function unit(_: string): (number, number)
return 1, 1
end
for _, built in Brush.primitives(keep, brushes, unit) do
built.primitive.material = material(built.texture)
built.primitive.extras = { d3map = { material = built.texture } }
table.insert(prims, built.primitive)
end
end
for _, mname in gridOrder do
local g = grids[mname]
if #g.idx > 0 then
local prim = gridPrimitive(g)
prim.material = material(mname)
prim.extras = { d3map = { material = mname, patch = true } }
table.insert(prims, prim)
end
end
local node: Types.Node = { name = keys.name or keys.classname or ("entity " .. (ei - 1)), children = {}, extras = { classname = keys.classname, keys = keys, entity = ei - 1 } }
if #prims > 0 then
table.insert(scene.meshes, { name = node.name, primitives = prims })
node.mesh = #scene.meshes
elseif #ent.prims == 0 then
node.translation = numbers(keys.origin, 3)
node.rotation = orientation(keys)
end
table.insert(scene.nodes, node)
table.insert(root.children, #scene.nodes)
end
scene.meta.entities = entities
scene.meta.counts = stats
scene.meta.source = { format = "d3map", version = m.version, variant = if m.version >= 3 then "quake4" else "doom3", entities = #m.entities, brushes = stats.brushes, patches = stats.patches }
return scene, nil
end
return D3map
+161
View File
@@ -0,0 +1,161 @@
-- model/d3map tests: an editor-layout Doom 3 / Quake 4 map written by the fixture: brushDef3 side areas against qhull
-- (scipy HalfspaceIntersection), texture coordinates against Doom 3's ComputeAxisBase + matrix, the patchDef3 grid
-- against a direct Bezier evaluation, entities. Fixtures: tools/fixtures/d3map.py.
local T = require("@tests/T")
local F = require("@rosetta")
local D3map = require("@rosetta/model/d3map")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Fx = require("@tests/gen/d3map")
local t = T.suite("d3map")
t:eq(D3map.name, "d3map", "name")
t:eq(F.detect(Fx.doom3, { name = "test.map" }), "d3map", "F.detect: Version 2 is not a Quake map")
t:eq(F.detect(Fx.quake4, { name = "test.map" }), "d3map", "F.detect: Version 3")
local s, err = D3map.decode(Bytes.reader(buffer.fromstring(Fx.doom3)))
t:check(s, "doom3: " .. tostring(err))
local sc = s :: any
t:eq(sc.meta.source.variant, "doom3", "variant")
t:eq((F.load(Fx.quake4, { format = "d3map" }) :: any).meta.source.variant, "quake4", "Quake 4")
t:eq(sc.meta.counts.brushes, 3, "brushes")
t:eq(sc.meta.counts.patches, 2, "patches")
t:eq(sc.meta.counts.skippedPrimitives, 1, "brushDef skipped")
local byMaterial: { [string]: any } = {}
for _, mesh in sc.meshes do
for _, p in mesh.primitives do
byMaterial[sc.materials[p.material].name] = p
end
end
local function tris(p: any, fn: (ax: number, ay: number, az: number, bx: number, by: number, bz: number, cx: number, cy: number, cz: number, a: number, b: number, c: number) -> ())
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
local idx = Types.Scene.reader(p.indices) :: any
for k = 0, p.indices.count - 1, 3 do
local a, b, c = idx(k, 0), idx(k + 1, 0), idx(k + 2, 0)
fn(pos(a, 0), pos(a, 1), pos(a, 2), pos(b, 0), pos(b, 1), pos(b, 2), pos(c, 0), pos(c, 1), pos(c, 2), a, b, c)
end
end
do
local bad, uvBad, windBad, faces = {}, 0, 0, 0
for _, w in Fx.sides do
local p = byMaterial[w.material]
if w.area < 1e-6 then
t:check(p == nil, w.material .. ": a redundant side has no polygon")
elseif not p then
table.insert(bad, w.material .. " missing")
else
faces += 1
local area = 0
local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any
tris(p, function(ax, ay, az, bx, by, bz, cx, cy, cz, a)
local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
area += math.sqrt(nx * nx + ny * ny + nz * nz) / 2
if nx * nrm(a, 0) + ny * nrm(a, 1) + nz * nrm(a, 2) <= 0 then
windBad += 1
end
end)
if math.abs(area - w.area) > 1e-3 * math.max(1, w.area) then
table.insert(bad, string.format("%s: %.4f vs %.4f", w.material, area, w.area))
end
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
local uv = Types.Scene.reader(p.attributes.TEXCOORD_0) :: any
local v = w.vecs
for i = 0, p.attributes.POSITION.count - 1 do
local x, y, z = pos(i, 0), pos(i, 1), pos(i, 2)
local su = x * v[1] + y * v[2] + z * v[3] + v[4]
local tv = x * v[5] + y * v[6] + z * v[7] + v[8]
if math.abs(uv(i, 0) - su) > 1e-3 or math.abs(uv(i, 1) - tv) > 1e-3 then
uvBad += 1
end
end
end
end
t:eq(#bad, 0, "side areas against qhull: " .. table.concat(bad, "; ", 1, math.min(#bad, 4)))
t:eq(uvBad, 0, "texture coordinates: ComputeAxisBase + the texture matrix")
t:eq(windBad, 0, "brush triangles counter-clockwise about the side normal")
t:note("%d brush sides with polygons match qhull; volumes %s", faces, table.concat(Fx.volumes :: any, ", "))
end
do
local p = byMaterial["textures/test/patchDef3"]
t:check(p, "patchDef3 primitive")
local w = Fx.patch3
t:eq(p.attributes.POSITION.count, w.width * w.height, "patchDef3: explicit subdivisions")
local pos = Types.Scene.reader(p.attributes.POSITION) :: any
local worst = 0
for i = 0, w.width * w.height - 1 do
for c = 0, 2 do
worst = math.max(worst, math.abs(pos(i, c) - w.points[i * 3 + c + 1]))
end
end
t:check(worst < 1e-3, string.format("patchDef3 grid against the Bezier evaluation (worst %.2g)", worst))
local p2 = byMaterial["textures/test/patchDef2"]
t:check(p2, "patchDef2 primitive")
local pos2 = Types.Scene.reader(p2.attributes.POSITION) :: any
local c = Fx.patch2.corners
t:check(pos2(0, 0) == c[1] and pos2(0, 1) == c[2] and math.abs(pos2(0, 2) - c[3]) < 1e-4, "patchDef2 first corner")
local n2 = p2.attributes.POSITION.count - 1
t:check(pos2(n2, 0) == c[4] and pos2(n2, 1) == c[5] and math.abs(pos2(n2, 2) - c[6]) < 1e-4, "patchDef2 last corner")
local nrm = Types.Scene.reader(p2.attributes.NORMAL) :: any
local agree = 0
local total = 0
tris(p2, function(ax, ay, az, bx, by, bz, cx, cy, cz, a)
local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
local d = (uy * vz - uz * vy) * nrm(a, 0) + (uz * vx - ux * vz) * nrm(a, 1) + (ux * vy - uy * vx) * nrm(a, 2)
total += 1
if d > 0 then
agree += 1
end
end)
t:eq(agree, total, "patch normals face the triangle winding")
end
do
local named: { [string]: any } = {}
for _, n in sc.nodes do
named[n.name] = n
end
t:eq(#sc.nodes, 1 + 4, "root + 4 entities")
t:check(named.worldspawn and named.worldspawn.mesh, "worldspawn mesh")
t:check(named.crate and named.crate.mesh and named.crate.extras.keys.model == "crate", "func_static: mesh and keys")
t:check(named.crate.translation == nil, "brush entities stay in world coordinates")
local l = named.light_1
t:check(l.translation[1] == 10 and l.translation[3] == 30, "light origin")
local q = l.rotation
t:check(math.abs(q[3] - math.sqrt(0.5)) < 1e-6 and math.abs(q[4] - math.sqrt(0.5)) < 1e-6, "rotation matrix rows: yaw 90")
local ps = named.info_player_start_1
t:check(math.abs(ps.rotation[3] - math.sqrt(0.5)) < 1e-6, "angle 90")
t:eq(ps.extras.classname, "info_player_start", "classname")
t:eq(sc.meta.entities[1].classname, "worldspawn", "meta.entities")
local lean = D3map.decode(Bytes.reader(buffer.fromstring(Fx.doom3)), { skip = { "textures/test/box_0", "TEXTURES/TEST/PATCHDEF2" } }) :: any
local seen = {}
for _, mesh in lean.meshes do
for _, p in mesh.primitives do
seen[lean.materials[p.material].name] = true
end
end
t:check(not seen["textures/test/box_0"] and not seen["textures/test/patchDef2"] and seen["textures/test/box_1"], "skip")
end
do
local function code(src: string, opts: any?): any
local _, e = D3map.decode(Bytes.reader(buffer.fromstring(src)), opts)
return e and e.code
end
t:eq(code("{ }"), Err.CORRUPT, "no Version")
t:eq(code("Version 2\n{ \"classname\" \"worldspawn\"\n{ brushDef3 { ( 0 0 1 0 ) ( ( 1 0 0 ) ( 0 1 0 ) ) \"x\" 0 0 0 }"), Err.CORRUPT, "truncated")
t:eq(code("Version 2\n{ \"classname\" \"worldspawn\" { patchDef2 { \"x\" ( 4 3 0 0 0 ) ( ) } } }"), Err.CORRUPT, "short patch")
t:eq(code(Fx.doom3, { maxPrimitives = 2 }), Err.LIMIT, "maxPrimitives")
t:eq(code("Version 2\n"), Err.CORRUPT, "no entities")
t:check(F.detect("Version 2\n{\n\"classname\" \"worldspawn\"\n}\n") == "d3map", "an empty map sniffs")
end
t:fuzz("decode", function(b: buffer)
return D3map.decode(Bytes.reader(b))
end, { buffer.fromstring(Fx.doom3) }, { mutations = 200 })
t:done()
+163
View File
@@ -0,0 +1,163 @@
# Doom 3 / Quake 4 .map fixtures (tools/fixtures.py). Doom 3's maps are not redistributable, so the map is written here
# in the editor's layout (the Doom 3 GPL source docs' idMapFile text, read for the layout; no code taken): a box and a
# random convex brush in worldspawn (every side its own material), a func_static with a box, a patchDef3 and a
# patchDef2, a light with a rotation matrix, a player start with an angle, and a Quake III brushDef (skipped). The
# reference: scipy's HalfspaceIntersection (qhull) per brush -> the area of every side; the side's texture vectors by
# Doom 3's ComputeAxisBase + texture matrix; the patchDef3 grid by evaluating the biquadratic Bezier sub-patches.
# tests/gen/d3map.luau { doom3 = <text>, quake4 = <text>, sides = { { material, area, vecs = { 8 } } },
# patch3 = { width, height, points = { x, y, z, ... } }, ... }
import json, math
REF = r"""
import json, sys
import numpy as np
from scipy.spatial import HalfspaceIntersection, ConvexHull
brushes = json.loads(sys.stdin.read())
out = []
for b in brushes:
hs = np.array([s["plane"] for s in b["sides"]], dtype=float)
hi = HalfspaceIntersection(hs, np.array(b["inside"], dtype=float))
pts = hi.intersections
vol = ConvexHull(pts).volume
for s in b["sides"]:
n, d = np.array(s["plane"][:3], dtype=float), s["plane"][3]
on = pts[np.abs(pts @ n + d) < 1e-6]
area = 0.0
if len(on) >= 3:
u = np.cross(n, [1, 0, 0] if abs(n[0]) < 0.9 else [0, 1, 0]); u /= np.linalg.norm(u)
v = np.cross(n, u)
q = np.stack([on @ u, on @ v], axis=1)
q = np.unique(np.round(q, 9), axis=0)
if len(q) >= 3:
area = ConvexHull(q).volume
out.append({"material": s["material"], "area": area})
out.append({"volume": vol})
print(json.dumps(out))
"""
def axis_base(n):
rot_y = -math.atan2(n[2], math.sqrt(n[1] * n[1] + n[0] * n[0]))
rot_z = math.atan2(n[1], n[0])
s = (-math.sin(rot_z), math.cos(rot_z), 0.0)
t = (-math.sin(rot_y) * math.cos(rot_z), -math.sin(rot_y) * math.sin(rot_z), -math.cos(rot_y))
return s, t
def vecs(n, m):
s, t = axis_base(n)
out = []
for i in range(2):
out += [s[k] * m[i][0] + t[k] * m[i][1] for k in range(3)] + [m[i][2]]
return out
def box(x0, y0, z0, x1, y1, z1):
return [((-1, 0, 0), x0), ((1, 0, 0), -x1), ((0, -1, 0), y0), ((0, 1, 0), -y1), ((0, 0, -1), z0), ((0, 0, 1), -z1)]
def g(v):
return repr(round(v, 9)).rstrip("0").rstrip(".") if isinstance(v, float) else str(v)
def bezier(ctrl, w, h, su, sv):
# ctrl[row][col] = (x, y, z, s, t); sub-patches of 3 x 3; su / sv segments per sub-patch
def b(t):
return ((1 - t) ** 2, 2 * t * (1 - t), t * t)
gw, gh = (w - 1) // 2 * su + 1, (h - 1) // 2 * sv + 1
pts = []
for gy in range(gh):
py, ty = min(gy // sv, (h - 1) // 2 - 1), None
ty = gy / sv - py
for gx in range(gw):
px = min(gx // su, (w - 1) // 2 - 1)
tx = gx / su - px
bu, bv = b(tx), b(ty)
p = [0.0] * 3
for j in range(3):
for i in range(3):
c = ctrl[py * 2 + j][px * 2 + i]
for k in range(3):
p[k] += bv[j] * bu[i] * c[k]
pts += p
return gw, gh, pts
def generate(ctx):
rng = ctx.rng(3)
brushes = []
sides = []
def brush(planes, inside, tag):
b = {"inside": inside, "sides": []}
for k, (n, d) in enumerate(planes):
m = [[rng.choice([1 / 64, 1 / 128, -1 / 128]), rng.uniform(-0.01, 0.01), rng.uniform(-1, 1)],
[rng.uniform(-0.01, 0.01), rng.choice([1 / 64, 1 / 128]), rng.uniform(-1, 1)]]
mat = "textures/test/%s_%d" % (tag, k)
b["sides"].append({"plane": [n[0], n[1], n[2], d], "material": mat, "m": m, "vecs": vecs(n, m)})
brushes.append(b)
return b
world = [brush(box(-128, -128, -16, 128, 128, 0), [0, 0, -8], "box")]
planes = []
cx, cy, cz = 200.0, 0.0, 64.0
for _ in range(12):
z = rng.uniform(-1, 1)
a = rng.uniform(0, 2 * math.pi)
n = (math.sqrt(1 - z * z) * math.cos(a), math.sqrt(1 - z * z) * math.sin(a), z)
r = rng.uniform(40, 64)
planes.append((n, -(n[0] * cx + n[1] * cy + n[2] * cz) - r))
for n, d in box(cx - 100, cy - 100, cz - 100, cx + 100, cy + 100, cz + 100):
planes.append((n, d))
world.append(brush(planes, [cx, cy, cz], "rnd"))
crate = brush(box(-16, 284, 0, 16, 316, 32), [0, 300, 16], "crate")
def side_text(s):
p = s["plane"]
m = s["m"]
return ' ( %s %s %s %s ) ( ( %s %s %s ) ( %s %s %s ) ) "%s" 0 0 0' % tuple(
[g(float(x)) for x in p] + [g(float(x)) for x in m[0]] + [g(float(x)) for x in m[1]] + [s["material"]])
def brush_text(i, b):
return "// primitive %d\n{\n brushDef3\n {\n%s\n }\n}" % (i, "\n".join(side_text(s) for s in b["sides"]))
# patchDef3: 3 x 3, a bump; patchDef2: 5 wide x 3 high, a half pipe
p3 = [[(x * 32.0, 300 + y * 32.0, 40 + (16.0 if x == 0 and y == 0 else 0.0), (x + 1) / 2, (y + 1) / 2) for x in (-1, 0, 1)] for y in (-1, 0, 1)]
p2 = [[(-64 + x * 32.0, 400 + y * 64.0, 64 * abs(math.cos(x * math.pi / 4)), x / 4, y / 2) for x in range(5)] for y in range(3)]
def patch_text(kind, ctrl, info):
h, w = len(ctrl), len(ctrl[0])
cols = []
for i in range(w):
cols.append(" ( " + " ".join("( %s )" % " ".join(g(float(v)) for v in ctrl[j][i]) for j in range(h)) + " )")
return '{\n %s\n {\n "textures/test/%s"\n ( %s )\n (\n%s\n )\n }\n}' % (kind, kind, " ".join(str(x) for x in info), "\n".join(cols))
def text(version):
out = ["Version %d" % version, "// entity 0", "{", '"classname" "worldspawn"']
for i, b in enumerate(world):
out.append(brush_text(i, b))
out.append("// primitive 2\n{\nbrushDef\n{\n( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) common/caulk 0 0 0\n}\n}")
out.append("}")
out += ["// entity 1", "{", '"classname" "func_static"', '"name" "crate"', '"origin" "0 300 16"', '"model" "crate"',
brush_text(0, crate), patch_text("patchDef3", p3, [3, 3, 4, 4, 0, 0, 0]),
patch_text("patchDef2", p2, [5, 3, 0, 0, 0]), "}"]
out += ["// entity 2", "{", '"classname" "light"', '"name" "light_1"', '"origin" "10 20 30"',
'"rotation" "0 1 0 -1 0 0 0 0 1"', '"light_radius" "300 300 300"', "}"]
out += ["// entity 3", "{", '"classname" "info_player_start"', '"name" "info_player_start_1"', '"origin" "-64 0 1"',
'"angle" "90"', "}"]
return "\n".join(out) + "\n"
ref = json.loads(ctx.python(["numpy", "scipy"], REF, input=json.dumps(
[{"inside": b["inside"], "sides": [{"plane": s["plane"], "material": s["material"]} for s in b["sides"]]} for b in brushes]).encode()))
vols = [r["volume"] for r in ref if "volume" in r]
areas = [r for r in ref if "volume" not in r]
k = 0
for b in brushes:
for s in b["sides"]:
assert areas[k]["material"] == s["material"]
sides.append({"material": s["material"], "area": areas[k]["area"], "vecs": s["vecs"]})
k += 1
gw, gh, pts = bezier([[c for c in row] for row in p3], 3, 3, 4, 4)
ctx.emit("d3map", {"doom3": text(2), "quake4": text(3), "sides": sides, "volumes": vols,
"patch3": {"width": gw, "height": gh, "points": pts},
"patch2": {"corners": list(p2[0][0][:3]) + list(p2[2][4][:3])}})
+30 -2
View File
@@ -1,5 +1,5 @@
# 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), a dmap-layout
# explains the inputs), a hand-written Doom 3 .map, and inputs made by the format fixtures' writers: the hand-written UDMF room (udmf.py), a dmap-layout
# .proc (proc.py), a VSWAP and a one-map GAMEMAPS + MAPHEAD with a random palette (wolf3d.py).
# tests/gen/docs_idtech.luau { files = { [name] = bytes }, vars = { udmfText = "room.udmf", ... } }
import importlib.util, os, struct
@@ -7,6 +7,33 @@ import importlib.util, os, struct
INPUTS = ["tools/docs_check.py", "tools/fixtures/udmf.py", "tools/fixtures/proc.py", "tools/fixtures/wolf3d.py"]
D3MAP = """Version 2
// entity 0
{
"classname" "worldspawn"
// primitive 0
{
brushDef3
{
( 0 0 -1 -16 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/base_floor/a_sofloor1_d" 0 0 0
( 0 0 1 0 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/base_floor/a_sofloor1_d" 0 0 0
( 0 -1 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
( 1 0 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
( 0 1 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
( -1 0 0 -128 ) ( ( 0.0078125 0 0 ) ( 0 0.0078125 0 ) ) "textures/common/caulk" 0 0 0
}
}
}
// entity 1
{
"classname" "info_player_start"
"name" "info_player_start_1"
"origin" "0 0 1"
"angle" "90"
}
"""
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"))
@@ -37,6 +64,7 @@ def generate(ctx):
body += struct.pack("<iiiHHHHH16s", *starts, *(len(pl) for pl in planes), 16, 16, b"Tiny map") + b"!ID!"
files["GAMEMAPS.WL6"] = bytes(body)
files["MAPHEAD.WL6"] = struct.pack("<H100i", W.TAG, head, *([0] * 99))
vars = {"udmfText": "room.udmf", "procText": "level.proc", "vswapBytes": "VSWAP.WL6", "wolfPaletteBytes": "wolf.pal",
files["room.map"] = D3MAP.encode()
vars = {"d3mapText": "room.map", "udmfText": "room.udmf", "procText": "level.proc", "vswapBytes": "VSWAP.WL6", "wolfPaletteBytes": "wolf.pal",
"gamemapsBytes": "GAMEMAPS.WL6", "mapheadBytes": "MAPHEAD.WL6"}
check.emit_inputs(ctx, files, vars)