Files
rosetta/src/Formats/model/lwo/Build.luau
T

470 lines
15 KiB
Luau

--!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: { [string]: number } = { 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) :: { number }
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) :: { number }
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: { { [string]: Types.Accessor } } = {}
local targetNames: { string } = {}
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
local tgt: { [string]: Types.Accessor } = { POSITION = Scene.accessor(d, "f32", 3, nv) }
table.insert(targets, tgt)
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 ex: any = mat and mat.extras
local vcol = ex and ex.lwo and ex.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