ws-3d3-b: model/lwo (LightWave LWO2 / LWOB / Modo LXOB read: layers with pivots and parents, polygons, VMAP / VMAD uv / colour / normal / weight / morph maps, surfaces and image blocks); 54 assimp test models match assimp's counts, materials and world bounds

This commit is contained in:
4DBug committed 2026-10-31 14:03:52 -05:00
1 parent de4f14a343
commit 1aaf8fce68
7 files changed
+1473

No files matched your search

+12
View File
@@ -410,6 +410,18 @@ local list: { Entry } = {
return require("@formats/model/gltf")
end,
},
{
name = "lwo",
category = "model",
path = "model/lwo",
extensions = { "lwo", "lxo" },
mime = { "image/x-lwo", "model/x-lwo" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" },
caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true },
load = function()
return require("@formats/model/lwo")
end,
},
{
name = "obj",
category = "model",
+467
View File
@@ -0,0 +1,467 @@
--!strict
-- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z
-- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's
-- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its
-- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's),
-- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart,
-- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value.
-- Plain code (the caller wraps it in pcall).
local Types = require("@formats/Types")
local Parse = require("@formats/model/lwo/Parse")
local Build = {}
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point"
local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" }
-- ------------------------------------------------------------------------------------------------ materials
local function textureIndex(scene: Types.Scene, cache: { [string]: number }, path: string): number
local hit = cache[path]
if hit then
return hit
end
local norm = string.gsub(path, "\\", "/")
local base = string.match(norm, "([^/:]+)$") or norm
local ext = string.lower(string.match(base, "%.(%w+)$") or "")
table.insert(scene.textures, { name = base, uri = base, mime = MIME[ext], extras = { lwo = { path = path } } })
cache[path] = #scene.textures
return #scene.textures
end
local function material(scene: Types.Scene, m: Parse.Model, surf: Parse.Surface, uvSets: { [string]: number }, cache: { [string]: number }): Types.Material
local mat = Scene.material(surf.name)
local v = surf.values
local c = surf.color
local tran = math.clamp(v.TRAN or 0, 0, 1)
mat.baseColor = { c[1], c[2], c[3], 1 - tran }
if tran > 0 then
mat.alphaMode = "blend"
end
mat.metallic = 0
local gloss = v.GLOS
mat.roughness = if gloss and (v.SPEC or 0) > 0 then math.clamp(1 - gloss, 0, 1) else 1
local lumi = v.LUMI or 0
if lumi > 0 then
mat.emissive = { c[1] * lumi, c[2] * lumi, c[3] * lumi }
end
mat.doubleSided = surf.side == 3
local maps = {}
local blocks = table.clone(surf.blocks)
table.sort(blocks, function(a: Parse.Block, b: Parse.Block): boolean
return a.ordinal < b.ordinal
end)
for _, blk in blocks do
local path = if blk.file then blk.file elseif blk.clip then m.clips[blk.clip] else nil
local entry: { [string]: any } = { kind = blk.kind, channel = blk.channel, enabled = blk.enabled, opacity = blk.opacity, projection = blk.projection, axis = blk.axis, uvmap = blk.uvmap }
if path and (blk.kind == "IMAP" or blk.kind == "TEX") then
local ti = textureIndex(scene, cache, path)
entry.texture = ti
if blk.enabled then
local ref: Types.TextureRef = { texture = ti }
if blk.uvmap and uvSets[blk.uvmap] then
ref.texCoord = uvSets[blk.uvmap]
end
if blk.channel == "COLR" and not mat.baseColorTexture then
mat.baseColorTexture = ref
elseif blk.channel == "LUMI" and not mat.emissiveTexture then
mat.emissiveTexture = ref
if lumi <= 0 then
mat.emissive = { 1, 1, 1 }
end
end
end
end
table.insert(maps, entry)
end
local extras: { [string]: any } = { color = table.clone(c), side = surf.side, maps = maps, source = surf.source }
for k, x in v do
extras[string.lower(k)] = x
end
if surf.vcol then
extras.vcol = surf.vcol.name
end
mat.extras = { lwo = extras }
return mat
end
-- ------------------------------------------------------------------------------------------------ geometry
local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { Group }
local groups: { Group } = {}
local byKey: { [string]: Group } = {}
for i, poly in layer.polys do
local kind = poly.kind
local n = #poly.corners
if (kind == "FACE" or kind == "PTCH" or kind == "SUBD") and n > 0 then
local class = if n == 1 then "point" elseif n == 2 then "line" elseif kind == "FACE" then "poly" else "patch"
local mi = surfaceOf(poly.surf)
local key = mi .. class
local g = byKey[key]
if not g then
g = { material = mi, class = class, polys = {} }
byKey[key] = g
table.insert(groups, g)
end
table.insert(g.polys, i - 1)
end
end
local rank = { poly = 1, patch = 2, line = 3, point = 4 }
table.sort(groups, function(a: Group, b: Group): boolean
if a.material ~= b.material then
return a.material < b.material
end
return rank[a.class] < rank[b.class]
end)
return groups
end
-- the corners of a face in output order (winding reversed for the handedness change, first corner kept)
local function ordered(corners: { number }): { number }
local n = #corners
local out = table.create(n)
out[1] = corners[1]
for k = 2, n do
out[k] = corners[n - k + 2]
end
return out
end
type Attr = { map: Parse.Map, name: string, comps: number }
local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive
local pts, pivot = layer.pts, layer.pivot
local vertOf: { [number]: number } = {}
local srcPoint: { number } = {} -- vertex (1-based) -> point
local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none)
local indices: { number } = {}
local faces: { number } = {}
local madMaps: { Parse.Map } = {}
for _, a in attrs do
if next(a.map.mad) then
table.insert(madMaps, a.map)
end
end
for _, m in morphs do
if next(m.mad) then
table.insert(madMaps, m)
end
end
local function vertex(f: number, p: number): number
local own = false
for _, m in madMaps do
local row = m.mad[f]
if row and row[p] then
own = true
break
end
end
if not own then
local v = vertOf[p]
if v then
return v
end
end
table.insert(srcPoint, p)
table.insert(srcPoly, if own then f else -1)
local v = #srcPoint - 1
if not own then
vertOf[p] = v
end
return v
end
for _, f in g.polys do
local corners = ordered(layer.polys[f + 1].corners)
local n = #corners
local vs = table.create(n)
for k = 1, n do
vs[k] = vertex(f, corners[k])
end
if g.class == "poly" or g.class == "patch" then
if triangulate then
for k = 2, n - 1 do
table.insert(indices, vs[1])
table.insert(indices, vs[k])
table.insert(indices, vs[k + 1])
end
else
table.insert(faces, n)
table.move(vs, 1, n, #indices + 1, indices)
end
else
table.move(vs, 1, n, #indices + 1, indices)
end
end
local nv = #srcPoint
local pos = buffer.create(nv * 12)
for v = 1, nv do
local p = srcPoint[v] * 3
local o = (v - 1) * 12
writef32(pos, o, pts[p + 1] - pivot[1])
writef32(pos, o + 4, pts[p + 2] - pivot[2])
writef32(pos, o + 8, -(pts[p + 3] - pivot[3]))
end
local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) }
-- the value of map m for vertex v (1-based), or nil
local function value(m: Parse.Map, v: number): ({ number }?, number?)
local f = srcPoly[v]
if f >= 0 then
local row = m.mad[f]
local hit = row and row[srcPoint[v]]
if hit then
return hit, nil
end
end
local p = srcPoint[v]
if m.has[p] then
return nil, p * m.dims
end
return nil, nil
end
local names: { [string]: string } = {}
for _, a in attrs do
local m, comps = a.map, a.comps
local data = buffer.create(nv * comps * 4)
for v = 1, nv do
local o = (v - 1) * comps * 4
local direct, at = value(m, v)
local x: { number } = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2] or 0, m.vals[at + 3] or 0, m.vals[at + 4] or 1 } else {}
if m.kind == "uv" then
writef32(data, o, x[1] or 0)
writef32(data, o + 4, 1 - (x[2] or 0))
elseif m.kind == "color" then
writef32(data, o, x[1] or 1)
writef32(data, o + 4, x[2] or 1)
writef32(data, o + 8, x[3] or 1)
writef32(data, o + 12, if m.dims == 4 and x[4] then x[4] else 1)
elseif m.kind == "normal" then
writef32(data, o, x[1] or 0)
writef32(data, o + 4, x[2] or 0)
writef32(data, o + 8, -(x[3] or 0))
else
writef32(data, o, x[1] or 0)
end
end
attributes[a.name] = Scene.accessor(data, "f32", comps, nv)
names[a.name] = m.name
end
local prim: Types.Primitive = { attributes = attributes, mode = "triangles" }
if #morphs > 0 then
local targets = {}
local targetNames = {}
for _, m in morphs do
local d = buffer.create(nv * 12)
for v = 1, nv do
local direct, at = value(m, v)
local x: { number }? = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2], m.vals[at + 3] } else nil
if x then
local p = srcPoint[v] * 3
local dx, dy, dz = x[1], x[2], x[3]
if m.kind == "spot" then
dx, dy, dz = dx - pts[p + 1], dy - pts[p + 2], dz - pts[p + 3]
end
writef32(d, (v - 1) * 12, dx)
writef32(d, (v - 1) * 12 + 4, dy)
writef32(d, (v - 1) * 12 + 8, -dz)
end
end
table.insert(targets, { POSITION = Scene.accessor(d, "f32", 3, nv) })
table.insert(targetNames, m.name)
end
prim.targets = targets
names._targets = table.concat(targetNames, "\n")
end
local ib = buffer.create(#indices * 4)
for k, x in indices do
writeu32(ib, (k - 1) * 4, x)
end
prim.indices = Scene.accessor(ib, "u32", 1, #indices)
if g.class == "line" then
prim.mode = "lines"
elseif g.class == "point" then
prim.mode = "points"
elseif not triangulate then
prim.mode = "polygons"
local fb = buffer.create(#faces * 4)
for k, x in faces do
writeu32(fb, (k - 1) * 4, x)
end
prim.faces = Scene.accessor(fb, "u32", 1, #faces)
end
prim.material = g.material
local extras: { [string]: any } = { maps = names }
if g.class == "patch" then
extras.subdivision = true
end
prim.extras = { lwo = extras }
return prim
end
-- ------------------------------------------------------------------------------------------------ scene
function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.Scene?, string?)
local triangulate = not (opts and opts.triangulate == false)
local scene = Scene.new()
scene.meta.up = "y"
scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped }
-- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index
local uvSets: { [string]: number } = {}
local nuv = 0
for _, layer in m.layers do
for _, map in layer.maps do
if map.kind == "uv" and uvSets[map.name] == nil then
uvSets[map.name] = nuv
nuv += 1
end
end
end
-- materials: one per surface, then one per tag without a surface, then a default one
local texCache: { [string]: number } = {}
local bySurfName: { [string]: number } = {}
for i, surf in m.surfaces do
scene.materials[i] = material(scene, m, surf, uvSets, texCache)
if bySurfName[surf.name] == nil then
bySurfName[surf.name] = i
end
local low = string.lower(surf.name)
if bySurfName[low] == nil then
bySurfName[low] = i
end
end
local tagMat: { [number]: number } = {}
local default: number? = nil
local function surfaceOf(tag: number?): number
if tag ~= nil then
local hit = tagMat[tag]
if hit then
return hit
end
local name = m.tags[tag + 1]
if name then
local mi = bySurfName[name] or bySurfName[string.lower(name)]
if not mi then
table.insert(scene.materials, Scene.material(name))
mi = #scene.materials
bySurfName[name] = mi
end
tagMat[tag] = mi
return mi
end
end
if not default then
local mat = Scene.material("Default")
mat.baseColor = { 0.6, 0.6, 0.6, 1 }
mat.metallic = 0
table.insert(scene.materials, mat)
default = #scene.materials
end
return default :: number
end
-- nodes and meshes
local nodeOf: { [number]: number } = {}
local layerOfNode: { Parse.Layer } = {}
for _, layer in m.layers do
local hasGeometry = #layer.polys > 0
if not (layer.implicit and not hasGeometry) then
local node: Types.Node = { name = layer.name, children = {} }
table.insert(scene.nodes, node)
local ni = #scene.nodes
layerOfNode[ni] = layer
if nodeOf[layer.index] == nil then
nodeOf[layer.index] = ni
end
node.extras = { lwo = { index = layer.index, parent = layer.parent, pivot = table.clone(layer.pivot) } }
local groups = groupLayer(layer, surfaceOf)
if #groups > 0 then
local attrs: { Attr } = {}
local morphs: { Parse.Map } = {}
local hasUv = {}
local maxUv = -1
for _, map in layer.maps do
if map.kind == "uv" then
hasUv[uvSets[map.name]] = map
maxUv = math.max(maxUv, uvSets[map.name])
elseif map.kind == "morph" or map.kind == "spot" then
table.insert(morphs, map)
end
end
local empty: Parse.Map = { kind = "uv", name = "", dims = 2, vals = {}, has = {}, mad = {} }
for k = 0, maxUv do
table.insert(attrs, { map = hasUv[k] or empty, name = "TEXCOORD_" .. k, comps = 2 })
end
local nw, nc, hasNormal = 0, 0, false
for _, map in layer.maps do
if map.kind == "normal" and not hasNormal then
hasNormal = true
table.insert(attrs, { map = map, name = "NORMAL", comps = 3 })
elseif map.kind == "weight" then
table.insert(attrs, { map = map, name = "_WEIGHT_" .. nw, comps = 1 })
nw += 1
end
end
local prims = {}
for _, g in groups do
local mat = scene.materials[g.material]
local vcol = mat and mat.extras and mat.extras.lwo and mat.extras.lwo.vcol
local pa = table.clone(attrs)
nc = 0
for _, map in layer.maps do
if map.kind == "color" then
if map.name == vcol then
table.insert(pa, { map = map, name = "COLOR_0", comps = 4 })
else
table.insert(pa, { map = map, name = "_COLOR_" .. nc, comps = 4 })
nc += 1
end
end
end
table.insert(prims, primitive(layer, g, pa, morphs, triangulate))
end
local mesh: Types.Mesh = { name = layer.name, primitives = prims }
if #morphs > 0 then
mesh.weights = table.create(#morphs, 0)
local tn = {}
for _, mp in morphs do
table.insert(tn, mp.name)
end
mesh.extras = { targetNames = tn }
end
table.insert(scene.meshes, mesh)
node.mesh = #scene.meshes
end
end
end
-- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped)
local parentOf: { [number]: number } = {}
for ni, layer in layerOfNode do
local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil
if pi and pi ~= ni then
local up, steps = pi, 0
while up and up ~= ni and steps <= #scene.nodes do
up = parentOf[up]
steps += 1
end
if up ~= ni then
parentOf[ni] = pi
end
end
end
for ni = 1, #scene.nodes do
local layer = layerOfNode[ni]
local pi = parentOf[ni]
local pp = if pi then layerOfNode[pi].pivot else { 0, 0, 0 }
local t = { layer.pivot[1] - pp[1], layer.pivot[2] - pp[2], -(layer.pivot[3] - pp[3]) }
if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then
scene.nodes[ni].translation = t
end
if pi then
table.insert(scene.nodes[pi].children, ni)
else
table.insert(scene.roots, ni)
end
end
return scene, nil
end
return Build
+551
View File
@@ -0,0 +1,551 @@
--!strict
-- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build
-- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave
-- 5.x), checked against what assimp's LWO importer reads (no code taken).
-- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are
-- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS
-- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo
-- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural
-- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF).
-- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN,
-- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks.
-- Plain code (the caller wraps it in pcall); bad data returns nil, message.
local Bytes = require("@formats/core/Bytes")
local Chunks = require("@formats/containers/Chunks")
local Parse = {}
export type Map = {
kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot"
name: string,
dims: number,
vals: { number }, -- per point: vals[point * dims + c + 1]
has: { [number]: boolean },
mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values
}
export type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices
export type Layer = {
index: number,
name: string?,
parent: number?,
pivot: { number },
pts: { number }, -- x, y, z flat
polys: { Poly },
maps: { Map },
implicit: boolean?, -- the layer before any LAYR
}
export type Block = {
kind: string, -- IMAP / PROC / GRAD / SHDR, or "TEX" (LWOB)
ordinal: string,
channel: string, -- COLR, DIFF, LUMI, SPEC, GLOS, REFL, TRAN, RIND, TRNL, BUMP
enabled: boolean,
opacity: number,
projection: number?, -- 0 planar, 1 cylindrical, 2 spherical, 3 cubic, 4 front, 5 UV
axis: number?,
clip: number?,
file: string?, -- LWOB: the TIMG path
uvmap: string?,
wrap: { number }?,
negative: boolean?,
}
export type Surface = {
name: string,
values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND
color: { number },
side: number,
vcol: { name: string, kind: string, intensity: number }?,
blocks: { Block },
source: string?,
}
export type Model = {
version: string, -- "LWO2" | "LWOB" | "LXOB"
tags: { string },
layers: { Layer },
surfaces: { Surface },
clips: { [number]: string }, -- clip index -> path
skipped: { [string]: number },
corners: number,
}
local MAP_KINDS: { [string]: string } = {
TXUV = "uv",
RGB = "color",
RGBA = "color",
WGHT = "weight",
MNVW = "weight",
NORM = "normal",
MORF = "morph",
SPOT = "spot",
}
-- ------------------------------------------------------------------------------------------------ primitives
-- S0: a NUL-terminated string padded to an even length
local function s0(r: Bytes.Reader): string
local start = r.pos
local s = r:cstring()
if (r.pos - start) % 2 == 1 and r.pos < r.limit then
r.pos += 1
end
return s
end
-- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte)
local function vx(r: Bytes.Reader): number
if r:peekU8() == 0xFF then
return r:u32be() - 0xFF000000
end
return r:u16be()
end
local function id4(r: Bytes.Reader): string
local s = r:string(4)
return (string.gsub(s, " +$", ""))
end
-- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body)
local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ())
while p + 6 <= e do
local id = buffer.readstring(buf, p, 4)
local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5)
local body = p + 6
local avail = math.min(n, e - body)
f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail))
p = body + n + (n % 2)
end
end
-- ------------------------------------------------------------------------------------------------ geometry
local function newLayer(index: number): Layer
return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} }
end
local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string?
local n = r:remaining() // 12
if #layer.pts // 3 + n > limit then
return "limit: more than " .. limit .. " points"
end
local pts = layer.pts
local k = #pts
for _ = 1, n * 3 do
k += 1
pts[k] = r:f32be()
end
return nil
end
-- POLS (LWO2): returns nil or an error
local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string?
local polys = layer.polys
local npts = #layer.pts // 3
while r:remaining() >= 2 do
local n = bit32.band(r:u16be(), 0x3FF)
local corners = table.create(n)
for i = 1, n do
local p = vx(r) + ptBase
if p >= npts and not r.err then
return "polygon point index " .. p .. " out of range (" .. npts .. " points)"
end
corners[i] = p
end
if r.err then
return "truncated polygon list"
end
budget[1] -= n
if budget[1] < 0 then
return "limit: too many polygon corners"
end
table.insert(polys, { kind = kind, surf = nil, corners = corners })
end
return nil
end
-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count)
local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): string?
local polys = layer.polys
local npts = #layer.pts // 3
while r:remaining() >= 4 do
local n = r:u16be()
local corners = table.create(n)
for i = 1, n do
local p = r:u16be()
if p >= npts and not r.err then
return "polygon point index " .. p .. " out of range (" .. npts .. " points)"
end
corners[i] = p
end
local surf = r:i16be()
if r.err then
return "truncated polygon list"
end
if surf < 0 then
surf = -surf
r:u16be() -- the detail polygon count: they follow as ordinary records
end
budget[1] -= n
if budget[1] < 0 then
return "limit: too many polygon corners"
end
if n > 0 then
table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners })
end
end
return nil
end
local function findMap(layer: Layer, kind: string, name: string, dims: number): Map
for _, m in layer.maps do
if m.kind == kind and m.name == name then
return m
end
end
local m: Map = { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} }
table.insert(layer.maps, m)
return m
end
local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: number, polyBase: number, skipped: { [string]: number })
local typ = id4(r)
local dims = r:u16be()
local name = s0(r)
local kind = MAP_KINDS[typ]
if r.err or not kind then
skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1
return
end
local want = if kind == "uv" then 2 elseif kind == "color" then 4 elseif kind == "weight" then 1 else 3
if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then
skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1
return
end
local m = findMap(layer, kind, name, want)
local npts = #layer.pts // 3
local npolys = #layer.polys
local vals, has, mad = m.vals, m.has, m.mad
while r:remaining() >= 2 do
local p = vx(r) + ptBase
local f = if perPoly then vx(r) + polyBase else -1
local v = table.create(want, 1)
for c = 1, dims do
local x = r:f32be()
if c <= want then
v[c] = x
end
end
if r.err then
break
end
if p < npts then
if perPoly then
if f < npolys then
local row = mad[f]
if not row then
row = {}
mad[f] = row
end
row[p] = v
end
else
has[p] = true
for c = 1, want do
vals[p * want + c] = v[c]
end
end
end
end
end
local function readPtag(r: Bytes.Reader, layer: Layer, polyBase: number)
local typ = id4(r)
if typ ~= "SURF" and typ ~= "MATR" then
return
end
local polys = layer.polys
while r:remaining() >= 4 do
local f = vx(r) + polyBase
local tag = r:u16be()
if r.err then
break
end
local poly = polys[f + 1]
if poly then
poly.surf = tag
end
end
end
-- ------------------------------------------------------------------------------------------------ surfaces
local function newSurface(name: string): Surface
return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil }
end
local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true }
local function readBlock(r: Bytes.Reader, surf: Surface)
-- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks
if r:remaining() < 6 then
return
end
local kind = id4(r)
local hn = r:u16be()
local hend = math.min(r.pos + hn, r.limit)
local blk: Block = { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 }
local hr = Bytes.reader(r.buf, r.pos, hend - r.pos)
blk.ordinal = s0(hr)
subchunks(r.buf, hr.pos, hend, function(id: string, sr: Bytes.Reader)
if id == "CHAN" then
blk.channel = id4(sr)
elseif id == "ENAB" then
blk.enabled = sr:u16be() ~= 0
elseif id == "OPAC" then
sr:u16be()
blk.opacity = sr:f32be()
elseif id == "NEGA" then
blk.negative = sr:u16be() ~= 0
elseif id == "AXIS" then
blk.axis = sr:u16be()
end
end)
subchunks(r.buf, hend + (hn % 2), r.limit, function(id: string, sr: Bytes.Reader)
if id == "PROJ" then
blk.projection = sr:u16be()
elseif id == "AXIS" then
blk.axis = sr:u16be()
elseif id == "IMAG" then
blk.clip = vx(sr)
elseif id == "VMAP" then
blk.uvmap = s0(sr)
elseif id == "WRAP" then
blk.wrap = { sr:u16be(), sr:u16be() }
end
end)
table.insert(surf.blocks, blk)
end
local function readSurface(r: Bytes.Reader, surfaces: { Surface })
local name = s0(r)
local source = s0(r)
local surf = newSurface(name)
if source ~= "" then
for _, s in surfaces do
if s.name == source then
surf.values = table.clone(s.values)
surf.color = table.clone(s.color)
surf.side = s.side
surf.vcol = s.vcol
surf.blocks = table.clone(s.blocks)
break
end
end
surf.source = source
end
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "COLR" then
local c = { sr:f32be(), sr:f32be(), sr:f32be() }
if not sr.err then
surf.color = c
end
elseif SURF_VALUES[id] then
local v = sr:f32be()
if not sr.err then
surf.values[id] = v
end
elseif id == "SIDE" then
surf.side = sr:u16be()
elseif id == "VCOL" then
local intensity = sr:f32be()
vx(sr)
local kind = id4(sr)
local vname = s0(sr)
if not sr.err then
surf.vcol = { name = vname, kind = kind, intensity = intensity }
end
elseif id == "BLOK" then
readBlock(sr, surf)
end
end)
table.insert(surfaces, surf)
end
-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks
local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" }
local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" }
local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" }
local B_PROJ: { [string]: number } = { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 }
local function readSurfaceB(r: Bytes.Reader, surfaces: { Surface })
local surf = newSurface(s0(r))
local tex: Block? = nil
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "COLR" then
local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 }
if not sr.err then
surf.color = c
end
elseif B_VALUES[id] then
local v = sr:u16be()
if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then
surf.values[B_VALUES[id]] = v / 256
end
elseif B_FLOATS[id] then
local v = sr:f32be()
if not sr.err then
surf.values[B_FLOATS[id]] = v
surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one
end
elseif id == "GLOS" then
local v = sr:u16be()
if not sr.err then
-- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness
surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1)
end
elseif id == "SMAN" then
surf.values.SMAN = sr:f32be()
elseif id == "FLAG" then
local fl = sr:u16be()
if bit32.band(fl, 0x100) ~= 0 then
surf.side = 3
end
elseif B_TEX[id] then
local desc = sr:cstring()
local proj: number? = nil
for word, v in B_PROJ do
if string.find(desc, word, 1, true) then
proj = v
end
end
local blk: Block = { kind = if string.find(desc, "Image Map", 1, true) then "TEX" else "PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj }
table.insert(surf.blocks, blk)
tex = blk
elseif id == "TIMG" and tex then
local path = sr:cstring()
if path ~= "" and path ~= "(none)" then
tex.file = path
end
elseif id == "TFLG" and tex then
local fl = sr:u16be()
tex.axis = if bit32.band(fl, 1) ~= 0 then 0 elseif bit32.band(fl, 2) ~= 0 then 1 else 2
tex.negative = bit32.band(fl, 16) ~= 0
elseif id == "TVAL" and tex then
tex.opacity = sr:u16be() / 256
end
end)
for k in surf.values do
if string.sub(k, -1) == "!" then
surf.values[k] = nil
end
end
table.insert(surfaces, surf)
end
local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [number]: number })
local index = r:u32be()
if r.err then
return
end
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "STIL" then
clips[index] = s0(sr)
elseif id == "ISEQ" then
local digits = sr:u8()
sr:u8()
local offset = sr:i16be()
sr:u16be()
local start = sr:i16be()
sr:u16be()
local prefix = s0(sr)
local suffix = s0(sr)
if not sr.err then
clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix
end
elseif id == "XREF" then
refs[index] = sr:u32be()
end
end)
end
-- ------------------------------------------------------------------------------------------------ the file
-- parse(buf, from, limit, opts) -> Model | nil, message
function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?)
local version = buffer.readstring(buf, from + 8, 4)
local declared = bit32.byteswap(buffer.readu32(buf, from + 4))
local e = math.min(limit, from + 8 + declared)
local model: Model = { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 }
local layer = newLayer(0)
layer.implicit = true
table.insert(model.layers, layer)
local ptBase, polyBase = 0, 0
local budget = { maxCorners }
local refs: { [number]: number } = {}
local lwob = version == "LWOB"
local list = Chunks.walk(buf, from + 12, e, Chunks.IFF)
for _, c in list do
local id = c.id
local r = Bytes.reader(buf, c.offset, c.avail)
local err: string? = nil
if id == "TAGS" or id == "SRFS" then
while r:remaining() > 0 do
table.insert(model.tags, s0(r))
end
elseif id == "LAYR" and not lwob then
local index = r:u16be()
r:u16be() -- flags (hidden)
local px, py, pz = r:f32be(), r:f32be(), r:f32be()
local name = s0(r)
local parent: number? = if r:remaining() >= 2 then r:u16be() else nil
if r.err then
return nil, "truncated LAYR chunk"
end
if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then
table.remove(model.layers, #model.layers)
end
layer = newLayer(index)
layer.name = name
layer.parent = if parent == 0xFFFF then nil else parent
layer.pivot = { px, py, pz }
table.insert(model.layers, layer)
ptBase, polyBase = 0, 0
elseif id == "PNTS" then
ptBase = #layer.pts // 3
err = readPoints(r, layer, maxCorners)
elseif id == "POLS" then
polyBase = #layer.polys
if lwob then
err = readPolysB(r, layer, budget)
else
local kind = id4(r)
if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then
err = readPolys(r, layer, kind, ptBase, budget)
else
-- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry
local before = #layer.polys
err = readPolys(r, layer, kind, ptBase, budget)
model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before
end
end
elseif id == "VMAP" or id == "VMAD" then
readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped)
elseif id == "PTAG" then
readPtag(r, layer, polyBase)
elseif id == "SURF" then
if lwob then
readSurfaceB(r, model.surfaces)
else
readSurface(r, model.surfaces)
end
elseif id == "CLIP" then
readClip(r, model.clips, refs)
end
if err then
return nil, err
end
end
for index, target in refs do
if model.clips[index] == nil and model.clips[target] then
model.clips[index] = model.clips[target]
end
end
model.corners = maxCorners - budget[1]
return model, nil
end
return Parse
+86
View File
@@ -0,0 +1,86 @@
--!strict
-- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from
-- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models.
-- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH /
-- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and
-- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD:
-- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the
-- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has
-- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces
-- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE ->
-- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture,
-- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path:
-- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding
-- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false.
-- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar /
-- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Parse = require("@formats/model/lwo/Parse")
local Build = require("@formats/model/lwo/Build")
-- ------------------------------------------------------------------------------------------------ contract
local Lwo = {
name = "lwo",
category = "model",
extensions = { "lwo", "lxo" },
mime = { "image/x-lwo", "model/x-lwo" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" },
caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
maxVertices: number?, -- refuse more points / polygon corners (default 2^25)
}
-- ------------------------------------------------------------------------------------------------ constants
local VERSIONS = { LWO2 = true, LWOB = true, LXOB = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Lwo.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "FORM" then
return 0
end
local v = r:peek(4, 8)
return if VERSIONS[v] then 1 elseif v == "LWO3" then 0.8 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Lwo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
if r.limit - r.base < 12 then
return nil, Err.new(Err.TRUNCATED, "shorter than the FORM header", r.base)
end
if r:peek(4) ~= "FORM" then
return nil, Err.new(Err.CORRUPT, "not an IFF FORM", r.base)
end
local v = r:peek(4, 8)
if v == "LWO3" then
return nil, Err.new(Err.UNSUPPORTED, "LWO3 (LightWave 2018+) objects", r.base + 8)
end
if not VERSIONS[v] then
return nil, Err.new(Err.CORRUPT, "not a LightWave object (FORM type " .. string.format("%q", v) .. ")", r.base + 8)
end
local maxCorners = opts and opts.maxVertices or 2 ^ 25
local ok, model, msg = pcall(Parse.model, r.buf, r.base, r.limit, maxCorners)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad chunk data: " .. tostring(model))
end
if not model then
return nil, Err.from(msg)
end
local ok2, scene, msg2 = pcall(Build.scene, model, opts)
if not ok2 then
return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg2)
end
return scene, nil
end
return Lwo