--!strict -- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice, -- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does. local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") local Xform = require("@rosetta/model/fbx/Xform") local Mat4 = require("@rosetta/codecs/model/Mat4") local Read = {} type Node = { name: string, props: { any }, children: { Node } } type Array = { array: true, type: string, count: number, data: buffer } type Obj = { id: any, node: Node, name: string, class: string, sub: string, props: { [string]: { any } } } type Conn = { id: any, prop: string? } export type Fetch = (uri: string) -> buffer? local TICKS = 46186158000 -- FBX time units per second Read.TICKS = TICKS -- ------------------------------------------------------------------------------------------------ tree helpers local function child(n: Node?, name: string): Node? if not n then return nil end for _, c in n.children do if c.name == name then return c end end return nil end Read.child = child local function value(n: Node?, name: string): any local c = child(n, name) return c and c.props[1] end local function isArray(v: any): boolean return type(v) == "table" and v.array == true end -- old ASCII files have inline numbers local function array(n: Node?, name: string): Array? local c = child(n, name) if not c then return nil end local p = c.props[1] if isArray(p) then return p end local count = 0 for _, v in c.props do if type(v) == "number" then count += 1 end end if count == 0 then return nil end local data = buffer.create(count * 8) local k = 0 for _, v in c.props do if type(v) == "number" then buffer.writef64(data, k * 8, v) k += 1 end end return { array = true, type = "d", count = count, data = data } end local function at(a: Array, i: number): number if i < 0 or i >= a.count then return 0 end return buffer.readf64(a.data, i * 8) end -- "Name\0\1Class" (binary) / "Class::Name" (ASCII) local function objectName(s: any): string if type(s) ~= "string" then return "" end local nm = string.match(s, "^(.-)%z\1") if nm then return nm end local _, rest = string.match(s, "^(%w+)::(.*)$") if rest then return rest end return s end Read.objectName = objectName -- Properties70: P: name, type, label, flags, values... local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } } local out = into or {} local p70 = child(n, "Properties70") if p70 then for _, p in p70.children do local nm = p.props[1] if p.name == "P" and type(nm) == "string" then local v = { p.props[2] } for k = 5, #p.props do v[k - 3] = p.props[k] end out[nm] = v end end end return out end Read.properties = properties local function pnum(props: { [string]: { any } }, name: string, default: number): number local p = props[name] local v = p and p[2] if type(v) == "number" then return v elseif type(v) == "boolean" then return if v then 1 else 0 end return default end local function pvec(props: { [string]: { any } }, name: string, default: { number }): { number } local p = props[name] if p and type(p[2]) == "number" and type(p[3]) == "number" and type(p[4]) == "number" then return { p[2], p[3], p[4] } end return table.clone(default) end local function pstr(props: { [string]: { any } }, name: string): string? local p = props[name] local v = p and p[2] return if type(v) == "string" then v else nil end -- ------------------------------------------------------------------------------------------------ scene function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) local triangulate = not (opts and opts.triangulate == false) local flipV = not (opts and opts.flipV == false) local sampleRate = opts and type(opts.sampleRate) == "number" and opts.sampleRate > 0 and opts.sampleRate or nil local maxVertices = opts and opts.maxVertices or 2 ^ 25 local scene = Types.Scene.new() -- Definitions/ObjectType/PropertyTemplate local templates: { [string]: { [string]: { any } } } = {} local defs = child(root, "Definitions") if defs then for _, ot in defs.children do if ot.name == "ObjectType" and type(ot.props[1]) == "string" then local pt = child(ot, "PropertyTemplate") if pt then templates[ot.props[1]] = properties(pt) end end end end local objects: { [any]: Obj } = {} local order: { Obj } = {} local objs = child(root, "Objects") if not objs then return nil, Err.new(Err.CORRUPT, "no Objects section") end for _, n in objs.children do local id = n.props[1] if (type(id) == "number" or type(id) == "string") and objects[id] == nil then local base = templates[n.name] local props = properties(n, if base then table.clone(base) else nil) local o: Obj = { id = id, node = n, name = objectName(n.props[2]), class = n.name, sub = if type(n.props[3]) == "string" then n.props[3] else "", props = props } objects[id] = o table.insert(order, o) end end local kids: { [any]: { Conn } } = {} local parents: { [any]: { Conn } } = {} local conns = child(root, "Connections") if conns then for _, c in conns.children do if c.name == "C" or c.name == "Connect" then local src, dst = c.props[2], c.props[3] local prop = if type(c.props[4]) == "string" then c.props[4] else nil if src ~= nil and dst ~= nil and type(src) ~= "table" and type(dst) ~= "table" then kids[dst] = kids[dst] or {} table.insert(kids[dst], { id = src, prop = prop }) parents[src] = parents[src] or {} table.insert(parents[src], { id = dst, prop = prop }) end end end end local function sources(id: any, class: string?, sub: string?): { Obj } local out = {} for _, c in kids[id] or {} do local o = objects[c.id] if o and (class == nil or o.class == class) and (sub == nil or o.sub == sub) then table.insert(out, o) end end return out end local function sourcesProp(id: any): { { obj: Obj, prop: string? } } local out = {} for _, c in kids[id] or {} do local o = objects[c.id] if o then table.insert(out, { obj = o, prop = c.prop }) end end return out end local function targets(id: any, class: string?): { { obj: Obj, prop: string? } } local out = {} for _, c in parents[id] or {} do local o = objects[c.id] if o and (class == nil or o.class == class) then table.insert(out, { obj = o, prop = c.prop }) end end return out end local gs = properties(child(root, "GlobalSettings")) local upAxis = pnum(gs, "UpAxis", 1) local unitScale = pnum(gs, "UnitScaleFactor", 1) scene.meta.up = if upAxis == 2 then "z" else "y" scene.meta.unit = unitScale / 100 local frameRates = { [1] = 120, [2] = 100, [3] = 60, [4] = 50, [5] = 48, [6] = 30, [7] = 30, [8] = 29.97, [9] = 29.97, [10] = 25, [11] = 24, [13] = 96, [14] = 72, [15] = 59.94, [17] = 119.88 } local timeMode = pnum(gs, "TimeMode", 0) local fps = if timeMode == 14 then pnum(gs, "CustomFrameRate", 24) else frameRates[timeMode] or 24 -- ------------------------------------------------------------------------------------------ textures local textureIndex: { [any]: number } = {} local function mimeOf(data: buffer?, name: string?): string? if data and buffer.len(data) >= 4 then local h = buffer.readstring(data, 0, 4) if h == "\137PNG" then return "image/png" elseif string.sub(h, 1, 3) == "\255\216\255" then return "image/jpeg" elseif string.sub(h, 1, 2) == "BM" then return "image/bmp" elseif h == "DDS " then return "image/vnd-ms.dds" elseif h == "RIFF" then return "image/webp" end end local ext = name and string.lower(string.match(name, "%.(%w+)$") or "") or "" local M = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", webp = "image/webp", gif = "image/gif", psd = "image/vnd.adobe.photoshop" } return M[ext] end local function content(v: Node?): buffer? if not v then return nil end local c = child(v, "Content") if not c then return nil end for _, p in c.props do if type(p) == "buffer" and buffer.len(p) > 0 then return p end end -- ASCII: base64, possibly split into several strings local parts = {} for _, p in c.props do if type(p) == "string" then table.insert(parts, p) end end local s = table.concat(parts) if #s > 0 then local d = Base64.decode(s) if d and buffer.len(d) > 0 then return d end end return nil end local function texture(o: Obj): number local have = textureIndex[o.id] if have then return have end local n = o.node local rel = value(n, "RelativeFilename") local file = value(n, "FileName") or value(n, "Filename") local data: buffer? = nil local video: Obj? = sources(o.id, "Video")[1] if video then data = content(video.node) rel = rel or value(video.node, "RelativeFilename") file = file or value(video.node, "Filename") or value(video.node, "FileName") end local uri: string? = nil if type(rel) == "string" and rel ~= "" then uri = (string.gsub(rel, "\\", "/")) elseif type(file) == "string" and file ~= "" then uri = (string.gsub(file, "\\", "/")) end if not data and uri then data = fetch(uri :: string) if not data then local base = string.match(uri :: string, "([^/]+)$") if base and base ~= uri then data = fetch(base) end end end local tex: Types.Texture = { name = o.name, data = data, uri = if data and video and content(video.node) then nil else uri, mime = mimeOf(data, uri) } local wrapU, wrapV = pnum(o.props, "WrapModeU", 0), pnum(o.props, "WrapModeV", 0) if wrapU ~= 0 or wrapV ~= 0 then tex.sampler = { wrapS = if wrapU == 1 then "clamp" else "repeat", wrapT = if wrapV == 1 then "clamp" else "repeat" } end tex.extras = { fbx = { uri = uri, uvSet = pstr(o.props, "UVSet") } } table.insert(scene.textures, tex) textureIndex[o.id] = #scene.textures return #scene.textures end local function texRef(o: Obj): Types.TextureRef? local tobj = o if o.class == "LayeredTexture" then local t = sources(o.id, "Texture")[1] if not t then return nil end tobj = t end local ref: Types.TextureRef = { texture = texture(tobj) } local tr, sc = pvec(tobj.props, "Translation", { 0, 0, 0 }), pvec(tobj.props, "Scaling", { 1, 1, 1 }) local rot = pvec(tobj.props, "Rotation", { 0, 0, 0 }) if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot[3] ~= 0 then ref.transform = { offset = { tr[1], tr[2] }, scale = { sc[1], sc[2] }, rotation = rot[3] * math.pi / 180 } end return ref end -- ------------------------------------------------------------------------------------------ materials local materialIndex: { [any]: number } = {} local function material(o: Obj): number local have = materialIndex[o.id] if have then return have end local p = o.props local m = Types.Scene.material(o.name) local shading = value(o.node, "ShadingModel") local diffuse = pvec(p, "DiffuseColor", pvec(p, "Diffuse", { 0.8, 0.8, 0.8 })) local dfac = pnum(p, "DiffuseFactor", 1) local emissive = pvec(p, "EmissiveColor", pvec(p, "Emissive", { 0, 0, 0 })) local efac = pnum(p, "EmissiveFactor", 1) local shininess = pnum(p, "ShininessExponent", pnum(p, "Shininess", 20)) local opacity: number if p.Opacity then opacity = pnum(p, "Opacity", 1) else local tc = pvec(p, "TransparentColor", { 1, 1, 1 }) opacity = 1 - pnum(p, "TransparencyFactor", 0) * (tc[1] + tc[2] + tc[3]) / 3 end opacity = math.clamp(opacity, 0, 1) m.baseColor = { diffuse[1] * dfac, diffuse[2] * dfac, diffuse[3] * dfac, opacity } m.emissive = { emissive[1] * efac, emissive[2] * efac, emissive[3] * efac } m.metallic = 0 m.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) if opacity < 1 then m.alphaMode = "blend" end local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] if pbr then local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|" local bc = pbr if type(bc[2]) == "number" then m.baseColor = { bc[2], bc[3] or 1, bc[4] or 1, if type(bc[5]) == "number" then bc[5] else 1 } end m.metallic = pnum(p, prefix .. "metalness", 0) m.roughness = pnum(p, prefix .. "roughness", 1) if pnum(p, prefix .. "useGlossiness", 0) == 1 or pnum(p, prefix .. "roughness_inv", 0) == 1 then m.roughness = 1 - pnum(p, prefix .. "glossiness", 1 - m.roughness) end local ec = p[prefix .. "emit_color"] or p[prefix .. "emission_color"] if ec and type(ec[2]) == "number" then local k = pnum(p, prefix .. "emission", 1) m.emissive = { ec[2] * k, (ec[3] or 0) * k, (ec[4] or 0) * k } end end local extras: { [string]: any } = { shadingModel = if type(shading) == "string" then string.lower(shading) else pstr(p, "ShadingModel"), diffuse = diffuse, diffuseFactor = dfac, ambient = pvec(p, "AmbientColor", pvec(p, "Ambient", { 0, 0, 0 })), ambientFactor = pnum(p, "AmbientFactor", 1), specular = pvec(p, "SpecularColor", pvec(p, "Specular", { 0.2, 0.2, 0.2 })), specularFactor = pnum(p, "SpecularFactor", 1), shininess = shininess, emissive = emissive, emissiveFactor = efac, opacity = opacity, reflection = pvec(p, "ReflectionColor", { 0, 0, 0 }), reflectionFactor = pnum(p, "ReflectionFactor", 0), bumpFactor = pnum(p, "BumpFactor", 1), textures = {}, } for _, s in sourcesProp(o.id) do local cls = s.obj.class if (cls == "Texture" or cls == "LayeredTexture") and s.prop then local ref = texRef(s.obj) if ref then local prop = s.prop :: string local lp = string.lower(prop) extras.textures[prop] = ref.texture if lp == "diffusecolor" or string.find(lp, "base_?color_map") or lp == "maya|basecolor" or lp == "maya|texturebasecolor" then m.baseColorTexture = m.baseColorTexture or ref elseif lp == "normalmap" or lp == "bump" or string.find(lp, "norm_map") or string.find(lp, "bump_map") or lp == "maya|normalcamera" then m.normalTexture = m.normalTexture or ref elseif lp == "emissivecolor" or string.find(lp, "emit_color_map") or string.find(lp, "emission_map") then m.emissiveTexture = m.emissiveTexture or ref if m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then m.emissive = { 1, 1, 1 } end elseif string.find(lp, "ao_map") then m.occlusionTexture = m.occlusionTexture or ref end end end end if not next(extras.textures) then extras.textures = nil end m.extras = { fbx = extras } table.insert(scene.materials, m) materialIndex[o.id] = #scene.materials return #scene.materials end -- ------------------------------------------------------------------------------------------ nodes local models: { Obj } = {} local nodeOf: { [any]: number } = {} for _, o in order do if o.class == "Model" then table.insert(models, o) local nd: Types.Node = { name = o.name, children = {} } table.insert(scene.nodes, nd) nodeOf[o.id] = #scene.nodes end end if #models > maxVertices then return nil, Err.new(Err.LIMIT, "too many models") end local function xprops(o: Obj, over: { [string]: { number } }?): Xform.Props local p = o.props local function g(name: string, key: string, default: { number }): { number } if over and over[key] then return over[key] end return pvec(p, name, default) end return { T = g("Lcl Translation", "T", { 0, 0, 0 }), R = g("Lcl Rotation", "R", { 0, 0, 0 }), S = g("Lcl Scaling", "S", { 1, 1, 1 }), Rpre = pvec(p, "PreRotation", { 0, 0, 0 }), Rpost = pvec(p, "PostRotation", { 0, 0, 0 }), Roff = pvec(p, "RotationOffset", { 0, 0, 0 }), Rp = pvec(p, "RotationPivot", { 0, 0, 0 }), Soff = pvec(p, "ScalingOffset", { 0, 0, 0 }), Sp = pvec(p, "ScalingPivot", { 0, 0, 0 }), order = pnum(p, "RotationOrder", 0), } end local localM: { [number]: Mat4.M4 } = {} for _, o in models do local ni = nodeOf[o.id] local nd = scene.nodes[ni] local m = Xform.localMatrix(xprops(o)) localM[ni] = m local t, r, s = Mat4.decompose(m) if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then nd.translation = t end if r[1] ~= 0 or r[2] ~= 0 or r[3] ~= 0 or r[4] ~= 1 then nd.rotation = r end if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then nd.scale = s end nd.extras = { fbx = { type = o.sub, id = o.id } } local parentModel: Obj? = nil for _, t2 in targets(o.id, "Model") do parentModel = t2.obj break end local pi = parentModel and nodeOf[parentModel.id] if pi and pi ~= ni then table.insert(scene.nodes[pi].children, ni) else table.insert(scene.roots, ni) end end -- break parent cycles: cut children already placed do local placed: { [number]: boolean } = {} local function visit(i: number) placed[i] = true local nd = scene.nodes[i] local keepKids = {} for _, c in nd.children do if not placed[c] then table.insert(keepKids, c) visit(c) end end nd.children = keepKids end for _, r in scene.roots do visit(r) end for i in scene.nodes do if not placed[i] then table.insert(scene.roots, i) visit(i) end end end local worldM: { [number]: Mat4.M4 } = {} local function world(i: number, parent: Mat4.M4) worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) for _, c in scene.nodes[i].children do if not worldM[c] then world(c, worldM[i]) end end end for _, r in scene.roots do world(r, Mat4.identity()) end -- ------------------------------------------------------------------------------------------ meshes local corners = 0 local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?) local skin = sources(geo.id, "Deformer", "Skin")[1] if not skin then return nil, nil end local perCp: { { { number } } } = {} local joints: { number } = {} local ibms: { Mat4.M4 } = {} for _, cl in sources(skin.id, "Deformer", "Cluster") do local bone = sources(cl.id, "Model")[1] local bi = bone and nodeOf[bone.id] if bi then local ji = #joints + 1 joints[ji] = bi local idx, w = array(cl.node, "Indexes"), array(cl.node, "Weights") local T, TL = array(cl.node, "Transform"), array(cl.node, "TransformLink") local tm = Mat4.identity() if T and T.count >= 16 then for k = 1, 16 do tm[k] = at(T, k - 1) end end local tl: Mat4.M4? = nil if TL and TL.count >= 16 then tl = {} for k = 1, 16 do (tl :: any)[k] = at(TL, k - 1) end else tl = worldM[bi] end local inv = Mat4.inverse(tl :: Mat4.M4) or Mat4.identity() ibms[ji] = Mat4.mul(inv, tm) if idx and w then for k = 0, math.min(idx.count, w.count) - 1 do local cp = at(idx, k) local wt = at(w, k) if cp >= 0 and cp == math.floor(cp) and cp < maxVertices and wt > 0 then local l = perCp[cp + 1] if not l then l = {} perCp[cp + 1] = l end table.insert(l, { ji - 1, wt }) end end end end end if #joints == 0 then return nil, nil end local ibm = buffer.create(#joints * 64) for j, m in ibms do for k = 1, 16 do buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) end end local acc = Types.Scene.accessor(ibm, "f32", 16, #joints) acc.matrix = true return perCp, { name = skin.name, joints = joints, inverseBindMatrices = acc } end type Shape = { name: string, channel: Obj, weight: number, idx: Array?, dv: Array?, dn: Array? } local function shapesOf(geo: Obj): { Shape } local out = {} for _, bs in sources(geo.id, "Deformer", "BlendShape") do for _, ch in sources(bs.id, "Deformer", "BlendShapeChannel") do local shapes = sources(ch.id, "Geometry") local sh = shapes[#shapes] -- in-betweens: the full (last) shape if sh then table.insert(out, { name = ch.name ~= "" and ch.name or sh.name, channel = ch, weight = pnum(ch.props, "DeformPercent", 0) / 100, idx = array(sh.node, "Indexes"), dv = array(sh.node, "Vertices"), dn = array(sh.node, "Normals"), }) end end end return out end local meshCache: { [string]: number } = {} local shapeChannels: { [number]: { Obj } } = {} local nodeSkin: { [number]: number } = {} local skinCache: { [any]: number } = {} local function buildMesh(geo: Obj, mats: { number }, G: Mat4.M4?): (number?, Err.Err?) local g = geo.node local verts = array(g, "Vertices") local pvi = array(g, "PolygonVertexIndex") if not verts or not pvi then return nil, nil end local ncp = verts.count // 3 local nc = pvi.count corners += nc if corners > maxVertices or ncp > maxVertices then return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") end local cp = table.create(nc, 0) local polyOf = table.create(nc, 0) local starts: { number } = { 0 } local np = 0 for c = 0, nc - 1 do local v = at(pvi, c) local last = v < 0 if last then v = -v - 1 end if v >= ncp or v ~= math.floor(v) then v = 0 end cp[c + 1] = v polyOf[c + 1] = np if last then np += 1 starts[np + 1] = c + 1 end end if starts[np + 1] ~= nc then -- the last polygon has no end marker np += 1 starts[np + 1] = nc end type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number } local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem } local out: { Elem } = {} for _, c in g.children do if c.name == kind then local data = array(c, dataName) local mapping = value(c, "MappingInformationType") local ref = value(c, "ReferenceInformationType") local index = if ref == "IndexToDirect" or ref == "Index" then array(c, indexName) or array(c, dataName .. "Index") else nil if kind == "LayerElementMaterial" then index = data end if data and type(mapping) == "string" then table.insert(out, { data = data, index = index, mapping = mapping, comps = comps, name = value(c, "Name"), order = if type(c.props[1]) == "number" then c.props[1] else #out }) end end end table.sort(out, function(a: Elem, b: Elem): boolean return a.order < b.order end) return out end local function lookup(e: Elem, c: number): number local m = e.mapping local i if m == "ByPolygonVertex" then i = c elseif m == "ByVertice" or m == "ByVertex" then i = cp[c + 1] elseif m == "ByPolygon" then i = polyOf[c + 1] elseif m == "AllSame" then i = 0 else return -1 end if e.index and e.data ~= e.index then if i >= (e.index :: Array).count then return -1 end i = at(e.index :: Array, i) end if i < 0 or (i + 1) * e.comps > e.data.count then return -1 end return i end local normals = elems("LayerElementNormal", "Normals", "NormalsIndex", 3) local uvs = elems("LayerElementUV", "UV", "UVIndex", 2) local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] -- "NormalsIndex" / "NormalIndex" for _, e in normals do if not e.index then local c = nil for _, x in g.children do if x.name == "LayerElementNormal" then c = x break end end local r = c and value(c, "ReferenceInformationType") if r == "IndexToDirect" then e.index = array(c, "NormalIndex") end end end local groups: { [number]: { number } } = {} local slots: { number } = {} for p = 0, np - 1 do local slot = 0 if matEl then local c0 = starts[p + 1] local i = if matEl.mapping == "AllSame" then 0 else p if matEl.mapping == "ByPolygonVertex" then i = c0 end slot = at(matEl.data, i) if slot < 0 or slot ~= math.floor(slot) then slot = 0 end end local grp = groups[slot] if not grp then grp = {} groups[slot] = grp table.insert(slots, slot) end table.insert(grp, p) end table.sort(slots) local perCp, skin = skinOf(geo) local shapes = shapesOf(geo) local N3: Mat4.M4? = nil -- inverse transpose of G if G then local inv = Mat4.inverse(G) if inv then N3 = { inv[1], inv[5], inv[9], 0, inv[2], inv[6], inv[10], 0, inv[3], inv[7], inv[11], 0, 0, 0, 0, 1 } end end local mesh: Types.Mesh = { name = geo.name, primitives = {} } local function v3(dst: buffer, o: number, x: number, y: number, z: number, M: Mat4.M4?, w: number) if M then x, y, z = M[1] * x + M[5] * y + M[9] * z + M[13] * w, M[2] * x + M[6] * y + M[10] * z + M[14] * w, M[3] * x + M[7] * y + M[11] * z + M[15] * w end buffer.writef32(dst, o, x) buffer.writef32(dst, o + 4, y) buffer.writef32(dst, o + 8, z) end local skipped = 0 for _, slot in slots do local polys = groups[slot] local nv = 0 local ntri = 0 for _, p in polys do local k = starts[p + 2] - starts[p + 1] if k >= 3 or not triangulate then nv += k ntri += math.max(k - 2, 0) else skipped += 1 end end if nv > 0 then local pos = buffer.create(nv * 12) local nrm = if normals[1] then buffer.create(nv * 12) else nil local tan = if tangents[1] then buffer.create(nv * 16) else nil local uvb: { buffer } = {} for k = 1, #uvs do uvb[k] = buffer.create(nv * 8) end local colb: { buffer } = {} for k = 1, #colors do colb[k] = buffer.create(nv * 16) end local joints = if perCp then buffer.create(nv * 8) else nil local weights = if perCp then buffer.create(nv * 16) else nil local tgt: { { [string]: Types.Accessor } } = {} local shapeData: { { pos: buffer, nrm: buffer?, map: { [number]: number } } } = {} for si, sh in shapes do local map: { [number]: number } = {} if sh.idx then for k = 0, sh.idx.count - 1 do map[at(sh.idx, k)] = k end end shapeData[si] = { pos = buffer.create(nv * 12), nrm = if sh.dn and nrm then buffer.create(nv * 12) else nil, map = map } end local faces = if not triangulate then buffer.create(#polys * 4) else nil local idx = buffer.create((if triangulate then ntri * 3 else nv) * 4) local v = 0 local ti = 0 local fi = 0 for _, p in polys do local c0, c1 = starts[p + 1], starts[p + 2] local k = c1 - c0 if k >= 3 or not triangulate then local first = v for c = c0, c1 - 1 do local i = cp[c + 1] v3(pos, v * 12, at(verts, i * 3), at(verts, i * 3 + 1), at(verts, i * 3 + 2), G, 1) if nrm then local d = lookup(normals[1], c) local e = normals[1].data if d >= 0 then v3(nrm, v * 12, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), N3, 0) end end if tan then local d = lookup(tangents[1], c) local e = tangents[1].data if d >= 0 then v3(tan, v * 16, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), G, 0) buffer.writef32(tan, v * 16 + 12, 1) end end for u, e in uvs do local d = lookup(e, c) if d >= 0 then local uu, vv = at(e.data, d * 2), at(e.data, d * 2 + 1) buffer.writef32(uvb[u], v * 8, uu) buffer.writef32(uvb[u], v * 8 + 4, if flipV then 1 - vv else vv) end end for u, e in colors do local d = lookup(e, c) local b = colb[u] if d >= 0 then for q = 0, 3 do buffer.writef32(b, v * 16 + q * 4, at(e.data, d * 4 + q)) end else buffer.writef32(b, v * 16 + 12, 1) end end if perCp and joints and weights then local l = perCp[i + 1] if l then if #l > 4 then table.sort(l, function(a: { number }, b: { number }): boolean return a[2] > b[2] end) end local sum = 0 for q = 1, math.min(#l, 4) do sum += l[q][2] end for q = 1, math.min(#l, 4) do buffer.writeu16(joints, v * 8 + (q - 1) * 2, l[q][1]) buffer.writef32(weights, v * 16 + (q - 1) * 4, if sum > 0 then l[q][2] / sum else 0) end end end for si, sd in shapeData do local sh = shapes[si] local k2 = sd.map[i] if k2 and sh.dv then v3(sd.pos, v * 12, at(sh.dv, k2 * 3), at(sh.dv, k2 * 3 + 1), at(sh.dv, k2 * 3 + 2), G, 0) if sd.nrm and sh.dn then v3(sd.nrm, v * 12, at(sh.dn, k2 * 3), at(sh.dn, k2 * 3 + 1), at(sh.dn, k2 * 3 + 2), N3, 0) end end end if not triangulate then buffer.writeu32(idx, v * 4, v) end v += 1 end if triangulate then for q = 1, k - 2 do buffer.writeu32(idx, ti * 4, first) buffer.writeu32(idx, ti * 4 + 4, first + q) buffer.writeu32(idx, ti * 4 + 8, first + q + 1) ti += 3 end elseif faces then buffer.writeu32(faces, fi * 4, k) fi += 1 end end end local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } if nrm then attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) end if tan then attrs.TANGENT = Types.Scene.accessor(tan, "f32", 4, nv) end for u, b in uvb do attrs["TEXCOORD_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 2, nv) end for u, b in colb do attrs["COLOR_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 4, nv) end if joints and weights then attrs.JOINTS_0 = Types.Scene.accessor(joints, "u16", 4, nv) attrs.WEIGHTS_0 = Types.Scene.accessor(weights, "f32", 4, nv) end for si, sd in shapeData do local t: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(sd.pos, "f32", 3, nv) } if sd.nrm then t.NORMAL = Types.Scene.accessor(sd.nrm, "f32", 3, nv) end tgt[si] = t end local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, if triangulate then ntri * 3 else nv), mode = if triangulate then "triangles" else "polygons", faces = if faces then Types.Scene.accessor(faces, "u32", 1, #polys) else nil, material = mats[slot + 1], targets = if #tgt > 0 then tgt else nil, } table.insert(mesh.primitives, prim) end end if #mesh.primitives == 0 then return nil, nil end local names = {} for k, uv in uvs do names[k] = uv.name end mesh.extras = { fbx = { id = geo.id, uvSets = names, skippedPolygons = if skipped > 0 then skipped else nil } } if #shapes > 0 then local w, tn, chans = {}, {}, {} for si, sh in shapes do w[si] = sh.weight tn[si] = sh.name chans[si] = sh.channel end mesh.weights = w ;(mesh.extras :: any).targetNames = tn table.insert(scene.meshes, mesh) shapeChannels[#scene.meshes] = chans else table.insert(scene.meshes, mesh) end local mi = #scene.meshes if skin then skinCache[geo.id] = skinCache[geo.id] or (function(): number table.insert(scene.skins, skin) return #scene.skins end)() end return mi, nil end local orient = math.sqrt(0.5) for _, o in models do local ni = nodeOf[o.id] local nd = scene.nodes[ni] local mats: { number } = {} for _, m in sources(o.id, "Material") do table.insert(mats, material(m)) end -- geometric transform: not inherited, baked into the mesh local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) local G: Mat4.M4? = nil if gt[1] ~= 0 or gt[2] ~= 0 or gt[3] ~= 0 or gr[1] ~= 0 or gr[2] ~= 0 or gr[3] ~= 0 or gsc[1] ~= 1 or gsc[2] ~= 1 or gsc[3] ~= 1 then G = Mat4.mul(Mat4.translation(gt[1], gt[2], gt[3]), Mat4.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Mat4.scaling(gsc[1], gsc[2], gsc[3]))) end for _, geo in sources(o.id, "Geometry") do if geo.sub == "Mesh" or geo.sub == "" then local key = tostring(geo.id) .. "|" .. table.concat(mats, ",") .. "|" .. (if G then table.concat(G :: any, ",") else "") local mi = meshCache[key] if mi == nil then local m, err = buildMesh(geo, mats, G) if err then return nil, err end if m then meshCache[key] = m mi = m end end if mi then if nd.mesh == nil then nd.mesh = mi if skinCache[geo.id] then nd.skin = skinCache[geo.id] end nd.weights = scene.meshes[mi].weights and table.clone(scene.meshes[mi].weights :: { number }) else -- a second geometry on the same model: a child node table.insert(scene.nodes, { name = o.name, children = {}, mesh = mi, skin = skinCache[geo.id] }) table.insert(nd.children, #scene.nodes) end nodeSkin[ni] = skinCache[geo.id] end end end -- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis for _, a in sources(o.id, "NodeAttribute") do local p = a.props if a.sub == "Camera" then local ortho = pnum(p, "CameraProjectionType", 0) == 1 local aw, ah = pnum(p, "AspectWidth", 0), pnum(p, "AspectHeight", 0) local fw, fh = pnum(p, "FilmWidth", 0.816), pnum(p, "FilmHeight", 0.612) local aspect = if aw > 0 and ah > 0 then aw / ah elseif fh > 0 then fw / fh else 4 / 3 local cam: Types.Camera local near, far = pnum(p, "NearPlane", 10), pnum(p, "FarPlane", 4000) if ortho then local zoom = pnum(p, "OrthoZoom", 1) cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } :: Types.Camera else local focal = pnum(p, "FocalLength", 0) local hfov if focal > 0 and fw > 0 then hfov = 2 * math.atan(fw * 25.4 / (2 * focal)) else hfov = pnum(p, "FieldOfView", 40) * math.pi / 180 end local yfov = 2 * math.atan(math.tan(hfov / 2) / aspect) cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } :: Types.Camera end table.insert(scene.cameras, cam) table.insert(scene.nodes, { name = o.name .. "_camera", children = {}, camera = #scene.cameras, rotation = { 0, -orient, 0, orient }, extras = { fbx = { orientation = "camera" } } }) table.insert(nd.children, #scene.nodes) elseif a.sub == "Light" then local lt = pnum(p, "LightType", 0) local col = pvec(p, "Color", { 1, 1, 1 }) local light: Types.Light = { name = a.name ~= "" and a.name or o.name, type = if lt == 1 then "directional" elseif lt == 2 then "spot" else "point", color = col, intensity = pnum(p, "Intensity", 100) / 100, } if lt == 2 then local outer = pnum(p, "OuterAngle", pnum(p, "Cone angle", 45)) local inner = pnum(p, "InnerAngle", pnum(p, "HotSpot", 0)) light.outerCone = math.clamp(outer / 2, 0, 90) * math.pi / 180 light.innerCone = math.clamp(math.min(inner, outer) / 2, 0, 90) * math.pi / 180 end if pnum(p, "EnableFarAttenuation", 0) == 1 then light.range = pnum(p, "FarAttenuationEnd", 0) end table.insert(scene.lights, light) table.insert(scene.nodes, { name = o.name .. "_light", children = {}, light = #scene.lights, rotation = { -orient, 0, 0, orient }, extras = { fbx = { orientation = "light", lightType = lt } } }) table.insert(nd.children, #scene.nodes) end end end -- ------------------------------------------------------------------------------------------ animation type Curve = { times: { number }, values: { number }, flags: { number }, slopes: { { number } }? } local curveCache: { [any]: Curve } = {} local function curve(o: Obj): Curve? local have = curveCache[o.id] if have then return have end local kt, kv = array(o.node, "KeyTime"), array(o.node, "KeyValueFloat") if not kt or not kv then return nil end local n = math.min(kt.count, kv.count) if n == 0 then return nil end local times, values = table.create(n, 0), table.create(n, 0) for k = 0, n - 1 do times[k + 1] = at(kt, k) / TICKS values[k + 1] = at(kv, k) end -- expanded through KeyAttrRefCount local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") local flags = table.create(n, 4) local slopes: { { number } } = {} if fl and rc then local key = 1 for a = 0, math.min(fl.count, rc.count) - 1 do local f = at(fl, a) local cnt = at(rc, a) for _ = 1, math.min(cnt, n - key + 1) do flags[key] = f if df and df.count >= (a + 1) * 4 then slopes[key] = { at(df, a * 4), at(df, a * 4 + 1) } end key += 1 end end end local c: Curve = { times = times, values = values, flags = flags, slopes = slopes } curveCache[o.id] = c return c end local function eval(c: Curve, t: number): number local ts, vs = c.times, c.values local n = #ts if t <= ts[1] then return vs[1] elseif t >= ts[n] then return vs[n] end local lo, hi = 1, n while hi - lo > 1 do local mid = (lo + hi) // 2 if ts[mid] <= t then lo = mid else hi = mid end end local dt = ts[hi] - ts[lo] if dt <= 0 then return vs[hi] end local u = (t - ts[lo]) / dt local f = bit32.band(c.flags[lo] or 4, 0x0E) if f == 2 then return vs[lo] elseif f == 8 and c.slopes and c.slopes[lo] then local s = (c.slopes :: { { number } })[lo] local m0, m1 = s[1] * dt, s[2] * dt local u2, u3 = u * u, u * u * u return (2 * u3 - 3 * u2 + 1) * vs[lo] + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * vs[hi] + (u3 - u2) * m1 end return vs[lo] + (vs[hi] - vs[lo]) * u end local function allConstant(cs: { Curve }): boolean for _, c in cs do for k = 1, #c.times - 1 do if bit32.band(c.flags[k] or 4, 0x0E) ~= 2 then return false end end end return true end local function sampleTimes(cs: { Curve }): { number } local set: { [number]: boolean } = {} local out: { number } = {} local tmin, tmax = math.huge, -math.huge for _, c in cs do for _, t in c.times do tmin, tmax = math.min(tmin, t), math.max(tmax, t) if not set[t] then set[t] = true table.insert(out, t) end end end if sampleRate and tmax > tmin then local steps = math.min(math.ceil((tmax - tmin) * sampleRate), 100000) for k = 0, steps do local t = tmin + (tmax - tmin) * k / steps if not set[t] then set[t] = true table.insert(out, t) end end end table.sort(out) return out end local function f32acc(vals: { number }, comps: number): Types.Accessor local n = #vals // comps local b = buffer.create(#vals * 4) for k, v in vals do buffer.writef32(b, (k - 1) * 4, v) end return Types.Scene.accessor(b, "f32", comps, n) end local PROPS = { ["Lcl Translation"] = "T", ["Lcl Rotation"] = "R", ["Lcl Scaling"] = "S" } for _, stack in order do if stack.class == "AnimationStack" then local anim: Types.Animation = { name = stack.name, channels = {} } type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } } local tracks: { [any]: Track } = {} local trackOrder: { any } = {} local morph: { [any]: Curve } = {} local layers = sources(stack.id, "AnimationLayer") for _, layer in layers do for _, cn in sources(layer.id, "AnimationCurveNode") do for _, tgt in targets(cn.id) do local key = tgt.prop and PROPS[tgt.prop] if key and tgt.obj.class == "Model" and nodeOf[tgt.obj.id] then local tr = tracks[tgt.obj.id] if not tr then tr = { curves = {}, defaults = {} } tracks[tgt.obj.id] = tr table.insert(trackOrder, tgt.obj.id) end if not tr.curves[key] then local axes: { [number]: Curve } = {} for _, s in sourcesProp(cn.id) do if s.obj.class == "AnimationCurve" and s.prop then local ax = if string.find(s.prop, "X$") then 1 elseif string.find(s.prop, "Y$") then 2 elseif string.find(s.prop, "Z$") then 3 else nil local c = ax and curve(s.obj) if ax and c then axes[ax] = c end end end if next(axes) then tr.curves[key] = axes tr.defaults[key] = { pnum(cn.props, "d|X", 0), pnum(cn.props, "d|Y", 0), pnum(cn.props, "d|Z", 0) } end end elseif tgt.prop == "DeformPercent" and tgt.obj.class == "Deformer" then for _, s in sources(cn.id, "AnimationCurve") do local c = curve(s) if c and not morph[tgt.obj.id] then morph[tgt.obj.id] = c end end end end end end for _, id in trackOrder do local tr = tracks[id] local o = objects[id] local ni = nodeOf[id] local cs: { Curve } = {} for _, axes in tr.curves do for _, c in pairs(axes) do table.insert(cs, c) end end local times = sampleTimes(cs) if #times > 0 then local base = xprops(o) local T, R, S = {}, {}, {} local prevQ: { number }? = nil for _, t in times do local over: { [string]: { number } } = {} for key, axes in tr.curves do local stat = (base :: any)[key] local v = table.clone(stat) for ax = 1, 3 do local c = axes[ax] if c then v[ax] = eval(c, t) end end over[key] = v end local tt, rr, ss = Mat4.decompose(Xform.localMatrix(xprops(o, over))) if prevQ and rr[1] * prevQ[1] + rr[2] * prevQ[2] + rr[3] * prevQ[3] + rr[4] * prevQ[4] < 0 then rr = { -rr[1], -rr[2], -rr[3], -rr[4] } end prevQ = rr table.move(tt, 1, 3, #T + 1, T) table.move(rr, 1, 4, #R + 1, R) table.move(ss, 1, 3, #S + 1, S) end local input = f32acc(times, 1) local interp: any = if allConstant(cs) then "STEP" else "LINEAR" local nd = scene.nodes[ni] local function varies(vals: { number }, comps: number, rest: { number }): boolean for k = 0, #vals // comps - 1 do for q = 1, comps do if math.abs(vals[k * comps + q] - rest[q]) > 1e-6 then return true end end end return false end if tr.curves.T or varies(T, 3, nd.translation or { 0, 0, 0 }) then table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp } :: Types.Channel) end if tr.curves.R or varies(R, 4, nd.rotation or { 0, 0, 0, 1 }) then table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp } :: Types.Channel) end if tr.curves.S or varies(S, 3, nd.scale or { 1, 1, 1 }) then table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp } :: Types.Channel) end end end if next(morph) then for ni, nd in scene.nodes do local chans = nd.mesh and shapeChannels[nd.mesh] if chans then local cs: { Curve } = {} for _, ch in chans do if morph[ch.id] then table.insert(cs, morph[ch.id]) end end if #cs > 0 then local times = sampleTimes(cs) local out = {} for _, t in times do for _, ch in chans do local c = morph[ch.id] table.insert(out, (if c then eval(c, t) else pnum(ch.props, "DeformPercent", 0)) / 100) end end local acc = f32acc(out, 1) table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = if allConstant(cs) then "STEP" else "LINEAR" } :: Types.Channel) end end end end if #anim.channels > 0 then table.insert(scene.animations, anim) end end end -- ------------------------------------------------------------------------------------------ meta local header = child(root, "FBXHeaderExtension") local creator = value(root, "Creator") or value(header, "Creator") scene.meta.source = { format = "fbx", version = version, creator = if type(creator) == "string" then creator else nil, upAxis = upAxis, upAxisSign = pnum(gs, "UpAxisSign", 1), frontAxis = pnum(gs, "FrontAxis", 2), frontAxisSign = pnum(gs, "FrontAxisSign", 1), coordAxis = pnum(gs, "CoordAxis", 0), coordAxisSign = pnum(gs, "CoordAxisSign", 1), unitScaleFactor = unitScale, originalUnitScaleFactor = pnum(gs, "OriginalUnitScaleFactor", unitScale), frameRate = fps, } local _ = nodeSkin return scene, nil end return Read