--!strict -- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types -- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f). -- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one -- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals -- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material; -- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets -> -- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Xform = require("@formats/model/fbx/Xform") local Write = {} type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } local TICKS = 46186158000 local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } } local function N(name: string, types: string, props: { any }, children: { WNode }?): WNode return { name = name, types = types, props = props, children = children } end local function arr(t: string, list: { number }): any local n = #list local d = buffer.create(n * 8) for k = 1, n do buffer.writef64(d, (k - 1) * 8, list[k]) end return { array = true, type = t, count = n, data = d } end -- P: name, type, label, flags, values (vt: one type character per value) local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } end local function Pvec(name: string, ptype: string, label: string, v: { number }): WNode return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3]) end local function Pcolor(name: string, v: { number }): WNode return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0) end local function Pnum(name: string, v: number): WNode return P(name, "Number", "", "A", "D", v) end local function Pint(name: string, v: number): WNode return P(name, "int", "Integer", "", "I", v) end local function Penum(name: string, v: number): WNode return P(name, "enum", "", "", "I", v) end local function Pdouble(name: string, v: number): WNode return P(name, "double", "Number", "", "D", v) end local function Ptime(name: string, v: number): WNode return P(name, "KTime", "Time", "", "L", v) end local function cls(name: string?, class: string): string return (name or "") .. "\0\1" .. class end local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> number)? if not acc then return nil end return Types.Scene.reader(acc) end -- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based) local function faces(prim: Types.Primitive): { { number } }? local pos = prim.attributes.POSITION if not pos then return nil end local n = pos.count local idx = accessorReader(prim.indices) local count = if prim.indices then prim.indices.count else n local function I(k: number): number return if idx then idx(k, 0) else k end local out: { { number } } = {} local mode = prim.mode or "triangles" if mode == "triangles" then for k = 0, count // 3 - 1 do table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) }) end elseif mode == "polygons" and prim.faces then local f = accessorReader(prim.faces) local p = 0 if f then for k = 0, prim.faces.count - 1 do local sz = f(k, 0) if p + sz > count then break end local poly = table.create(sz) for q = 0, sz - 1 do poly[q + 1] = I(p + q) end p += sz table.insert(out, poly) end end elseif mode == "triangle_strip" then for k = 0, count - 3 do local a, b, c = I(k), I(k + 1), I(k + 2) if k % 2 == 1 then a, b = b, a end table.insert(out, { a, b, c }) end elseif mode == "triangle_fan" then for k = 1, count - 2 do table.insert(out, { I(0), I(k), I(k + 1) }) end else return nil -- points / lines: not written end for _, f in out do for q, v in f do if v < 0 or v >= n then f[q] = 0 end end end return out end function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local flipV = not (opts and opts.flipV == false) local embed = not (opts and opts.embedTextures == false) local nextId = 1000000 local function id(): number nextId += 1 return nextId end local objects: { WNode } = {} local conns: { WNode } = {} local counts: { [string]: number } = {} local function add(class: string, node: WNode) table.insert(objects, node) counts[class] = (counts[class] or 0) + 1 end local function OO(child: number, parent: number) table.insert(conns, N("C", "SLL", { "OO", child, parent })) end local function OP(child: number, parent: number, prop: string) table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop })) end local nodes = scene.nodes or {} -- ------------------------------------------------------------------------------------------ textures local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" } local texIds: { [number]: number } = {} local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" for ti, tex in scene.textures or {} do local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png")) local tname = tex.name or ("Texture" .. ti) local vid, tid = id(), id() local vchildren = { N("Type", "S", { "Clip" }), N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }), N("UseMipMap", "I", { 0 }), N("Filename", "S", { file }), N("RelativeFilename", "S", { file }), } if embed and tex.data then table.insert(vchildren, N("Content", "R", { tex.data })) end add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren)) local tp = { P("UseMaterial", "bool", "", "", "I", 1) } local smp = tex.sampler if smp and smp.wrapS == "clamp" then table.insert(tp, Penum("WrapModeU", 1)) end if smp and smp.wrapT == "clamp" then table.insert(tp, Penum("WrapModeV", 1)) end add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, { N("Type", "S", { "TextureVideoClip" }), N("Version", "I", { 202 }), N("TextureName", "S", { cls(tname, "Texture") }), N("Properties70", "", {}, tp), N("Media", "S", { cls(tname, "Video") }), N("FileName", "S", { file }), N("RelativeFilename", "S", { file }), N("ModelUVTranslation", "DD", { 0, 0 }), N("ModelUVScaling", "DD", { 1, 1 }), N("Texture_Alpha_Source", "S", { "None" }), N("Cropping", "IIII", { 0, 0, 0, 0 }), })) OO(vid, tid) texIds[ti] = tid end -- ------------------------------------------------------------------------------------------ materials local matIds: { [number]: number } = {} for mi, m in scene.materials or {} do local x = m.extras and (m.extras :: any).fbx or {} local bc = m.baseColor or { 1, 1, 1, 1 } local alpha = bc[4] or 1 local rough = math.clamp(m.roughness or 1, 0.02, 1) local shin = if type(x.shininess) == "number" then x.shininess else 2 / (rough * rough) - 2 local em = m.emissive or { 0, 0, 0 } local spec = if type(x.specular) == "table" then x.specular else { 0.2, 0.2, 0.2 } local pid = id() local props = { Pcolor("AmbientColor", if type(x.ambient) == "table" then x.ambient else { 0, 0, 0 }), Pnum("AmbientFactor", if type(x.ambientFactor) == "number" then x.ambientFactor else 1), Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }), Pnum("DiffuseFactor", 1), Pcolor("EmissiveColor", em), Pnum("EmissiveFactor", 1), Pcolor("SpecularColor", spec), Pnum("SpecularFactor", if type(x.specularFactor) == "number" then x.specularFactor else 1), Pnum("Shininess", shin), Pnum("ShininessExponent", shin), Pcolor("TransparentColor", { 1, 1, 1 }), Pnum("TransparencyFactor", 1 - alpha), Pnum("Opacity", alpha), Pcolor("ReflectionColor", if type(x.reflection) == "table" then x.reflection else { 0, 0, 0 }), Pnum("ReflectionFactor", if type(x.reflectionFactor) == "number" then x.reflectionFactor else 0), } add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, { N("Version", "I", { 102 }), N("ShadingModel", "S", { if type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" then x.shadingModel else "phong" }), N("MultiLayer", "I", { 0 }), N("Properties70", "", {}, props), })) matIds[mi] = pid local function link(ref: Types.TextureRef?, prop: string) local t = ref and texIds[ref.texture] if t then OP(t, pid, prop) end end link(m.baseColorTexture, "DiffuseColor") link(m.normalTexture, "NormalMap") link(m.emissiveTexture, "EmissiveColor") -- the other textures the FBX material had (specular, metalness, ... maps), under their property names local linked = { [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, [m.normalTexture and m.normalTexture.texture or -1] = true, [m.emissiveTexture and m.emissiveTexture.texture or -1] = true, } if type(x.textures) == "table" then local props = {} for prop in x.textures do table.insert(props, prop) end table.sort(props) for _, prop in props do local ti = x.textures[prop] if type(ti) == "number" and not linked[ti] and texIds[ti] then linked[ti] = true OP(texIds[ti], pid, prop) end end end end -- ------------------------------------------------------------------------------------------ models local modelIds: { [number]: number } = {} local skip: { [number]: boolean } = {} local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there) local parentOf: { [number]: number } = {} for i, nd in nodes do for _, c in nd.children or {} do if parentOf[c] == nil and c ~= i then parentOf[c] = i end end end local jointSet: { [number]: boolean } = {} for _, s in scene.skins or {} do for _, j in s.joints do jointSet[j] = true end end for i, nd in nodes do local o = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.orientation local p = parentOf[i] if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then skip[i] = true attrHost[i] = p end end -- world matrices (rest pose) for clusters and the bind pose local worldM: { [number]: Xform.M4 } = {} local visiting: { [number]: boolean } = {} local function world(i: number): Xform.M4 if worldM[i] then return worldM[i] end if visiting[i] then return Xform.identity() end visiting[i] = true local nd = nodes[i] local l = if nd.matrix and #nd.matrix == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale) local p = parentOf[i] local w = if p then Xform.mul(world(p), l) else l worldM[i] = w return w end local function trs(nd: Types.Node): ({ number }, { number }, { number }) if nd.matrix and #nd.matrix == 16 then return Xform.decompose(nd.matrix) end return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } end local function model(name: string, sub: string, t: { number }, r: { number }, s: { number }): number local mid = id() add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, { N("Version", "I", { 232 }), N("Properties70", "", {}, { Penum("RotationOrder", 0), Penum("InheritType", 1), Pint("DefaultAttributeIndex", 0), Pvec("Lcl Translation", "Lcl Translation", "", t), Pvec("Lcl Rotation", "Lcl Rotation", "", r), Pvec("Lcl Scaling", "Lcl Scaling", "", s), }), N("Shading", "C", { true }), N("Culling", "S", { "CullingOff" }), })) return mid end local function attribute(nd: Types.Node, mid: number, nodeName: string) if nd.camera and scene.cameras[nd.camera] then local c = scene.cameras[nd.camera] local aid = id() local aspect = c.aspect or 4 / 3 local fh = 0.612 local fw = fh * aspect local props if c.type == "orthographic" then props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) } else local yfov = c.yfov or 0.8 local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect) local focal = fw * 25.4 / (2 * math.tan(hfov / 2)) props = { Penum("CameraProjectionType", 0), Penum("ApertureMode", 1), P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi), P("FocalLength", "Number", "", "A", "D", focal), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh), Penum("AspectRatioMode", 0), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), } end add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, { N("Properties70", "", {}, props), N("TypeFlags", "S", { "Camera" }), N("GeometryVersion", "I", { 124 }), })) OO(aid, mid) elseif nd.light and scene.lights[nd.light] then local l = scene.lights[nd.light] local aid = id() local lt = if l.type == "directional" then 1 elseif l.type == "spot" then 2 else 0 local props = { Penum("LightType", lt), Pcolor("Color", l.color or { 1, 1, 1 }), Pnum("Intensity", (l.intensity or 1) * 100), P("CastLight", "bool", "", "", "I", 1), } if lt == 2 then table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi)) table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi)) end if l.range then table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1)) table.insert(props, Pnum("FarAttenuationEnd", l.range)) end add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, { N("Properties70", "", {}, props), N("TypeFlags", "S", { "Light" }), N("GeometryVersion", "I", { 124 }), })) OO(aid, mid) end end for i, nd in nodes do if not skip[i] then local t, r, s = trs(nd) local euler = Xform.eulerXYZ(r) local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null" -- an orientation child folded into this node gives it its attribute local folded: number? = nil for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) if host == i then folded = c end end if not nd.mesh and folded then sub = if nodes[folded].camera then "Camera" else "Light" end local mid = model(nd.name or ("Node" .. i), sub, t, euler, s) modelIds[i] = mid if sub == "LimbNode" then local aid = id() add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) })) OO(aid, mid) end if folded then attribute(nodes[folded], mid, nd.name or "") end if nd.camera or nd.light then -- a glTF-oriented camera / light: an FBX-oriented child model carries it local kind = if nd.camera then "camera" else "light" local cmid = model((nd.name or "") .. "_" .. kind, if nd.camera then "Camera" else "Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 }) OO(cmid, mid) attribute(nd, cmid, nd.name or "") end end end for i in nodes do local mid = modelIds[i] if mid then local p = parentOf[i] local pm = p and modelIds[p] OO(mid, pm or 0) end end -- ------------------------------------------------------------------------------------------ geometry local geoIds: { [number]: number } = {} local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {} local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation) local geoCount: { [number]: number } = {} local function geometry(mi: number): number? if geoIds[mi] then return geoIds[mi] end local mesh = scene.meshes[mi] if not mesh then return nil end local V, PVI, NRM, MATS = {}, {}, {}, {} local UV: { [number]: { number } } = {} local UVI: { [number]: { number } } = {} local COL: { [number]: { number } } = {} local COLI: { [number]: { number } } = {} local slots: { number } = {} local slotOf: { [number]: number } = {} local hasN = false local nuv, ncol = 0, 0 for _, prim in mesh.primitives do for k = 0, 7 do if prim.attributes["TEXCOORD_" .. k] then nuv = math.max(nuv, k + 1) end if prim.attributes["COLOR_" .. k] then ncol = math.max(ncol, k + 1) end end if prim.attributes.NORMAL then hasN = true end end for k = 1, nuv do UV[k], UVI[k] = {}, {} end for k = 1, ncol do COL[k], COLI[k] = {}, {} end local layout = {} local offset = 0 for _, prim in mesh.primitives do local fs = faces(prim) local pos = prim.attributes.POSITION local R = accessorReader(pos) if fs and R and pos then table.insert(layout, { prim = prim, offset = offset }) local n = pos.count for v = 0, n - 1 do table.insert(V, R(v, 0)) table.insert(V, R(v, 1)) table.insert(V, R(v, 2)) end local NR = accessorReader(prim.attributes.NORMAL) if hasN then for v = 0, n - 1 do if NR then table.insert(NRM, NR(v, 0)) table.insert(NRM, NR(v, 1)) table.insert(NRM, NR(v, 2)) else table.insert(NRM, 0) table.insert(NRM, 0) table.insert(NRM, 1) end end end local uvBase: { number } = {} for k = 1, nuv do uvBase[k] = #UV[k] // 2 local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)]) for v = 0, n - 1 do local u, w = 0, 0 if T then u, w = T(v, 0), T(v, 1) end table.insert(UV[k], u) table.insert(UV[k], if flipV then 1 - w else w) end end local colBase: { number } = {} for k = 1, ncol do colBase[k] = #COL[k] // 4 local acc = prim.attributes["COLOR_" .. (k - 1)] local C = accessorReader(acc) local comps = acc and acc.components or 4 for v = 0, n - 1 do table.insert(COL[k], if C then C(v, 0) else 1) table.insert(COL[k], if C then C(v, 1) else 1) table.insert(COL[k], if C then C(v, 2) else 1) table.insert(COL[k], if C and comps >= 4 then C(v, 3) else 1) end end local mat = prim.material or 0 local slot = slotOf[mat] if slot == nil then table.insert(slots, mat) slot = #slots - 1 slotOf[mat] = slot end for _, f in fs do for q, v in f do local cp = v + offset table.insert(PVI, if q == #f then -cp - 1 else cp) for k = 1, nuv do table.insert(UVI[k], uvBase[k] + v) end for k = 1, ncol do table.insert(COLI[k], colBase[k] + v) end end table.insert(MATS, slot) end offset += n end end if #PVI == 0 then return nil end local gid = id() local ch: { WNode } = { N("Properties70", "", {}, {}), N("GeometryVersion", "I", { 124 }), N("Vertices", "", { arr("d", V) }), N("PolygonVertexIndex", "", { arr("i", PVI) }), } local layer0: { WNode } = { N("Version", "I", { 100 }) } if hasN then table.insert(ch, N("LayerElementNormal", "I", { 0 }, { N("Version", "I", { 101 }), N("Name", "S", { "" }), N("MappingInformationType", "S", { "ByVertice" }), N("ReferenceInformationType", "S", { "Direct" }), N("Normals", "", { arr("d", NRM) }), })) table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) })) end local extraLayers: { WNode } = {} local uvNames = mesh.extras and (mesh.extras :: any).fbx and (mesh.extras :: any).fbx.uvSets or {} for k = 1, nuv do table.insert(ch, N("LayerElementUV", "I", { k - 1 }, { N("Version", "I", { 101 }), N("Name", "S", { if type(uvNames[k]) == "string" then uvNames[k] else (if k == 1 then "UVMap" else "UVMap" .. k) }), N("MappingInformationType", "S", { "ByPolygonVertex" }), N("ReferenceInformationType", "S", { "IndexToDirect" }), N("UV", "", { arr("d", UV[k]) }), N("UVIndex", "", { arr("i", UVI[k]) }), })) local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) }) if k == 1 then table.insert(layer0, le) else table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le })) end end for k = 1, ncol do table.insert(ch, N("LayerElementColor", "I", { k - 1 }, { N("Version", "I", { 101 }), N("Name", "S", { "Col" .. (if k > 1 then tostring(k) else "") }), N("MappingInformationType", "S", { "ByPolygonVertex" }), N("ReferenceInformationType", "S", { "IndexToDirect" }), N("Colors", "", { arr("d", COL[k]) }), N("ColorIndex", "", { arr("i", COLI[k]) }), })) if k == 1 then table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) })) end end local anyMat = false for _, m in slots do if m ~= 0 and matIds[m] then anyMat = true end end if anyMat then local allSame = #slots == 1 table.insert(ch, N("LayerElementMaterial", "I", { 0 }, { N("Version", "I", { 101 }), N("Name", "S", { "" }), N("MappingInformationType", "S", { if allSame then "AllSame" else "ByPolygon" }), N("ReferenceInformationType", "S", { "IndexToDirect" }), N("Materials", "", { arr("i", if allSame then { 0 } else MATS) }), })) table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) })) end table.insert(ch, N("Layer", "I", { 0 }, layer0)) for _, l in extraLayers do table.insert(ch, l) end add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch)) geoIds[mi] = gid geoSlots[mi] = if anyMat then slots else {} geoVerts[mi] = layout geoCount[mi] = offset -- morph targets local prims = mesh.primitives local ntargets = 0 for _, l in layout do ntargets = math.max(ntargets, if l.prim.targets then #(l.prim.targets :: any) else 0) end if ntargets > 0 then local bsid = id() add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) })) OO(bsid, gid) local names = mesh.extras and (mesh.extras :: any).targetNames or {} for t = 1, ntargets do local IDX, DV, DN = {}, {}, {} local anyN = false for _, l in layout do local tg = l.prim.targets and (l.prim.targets :: any)[t] if tg and tg.NORMAL then anyN = true end end for _, l in layout do local tg = l.prim.targets and (l.prim.targets :: any)[t] local TP = tg and accessorReader(tg.POSITION) local TN = tg and accessorReader(tg.NORMAL) if TP then for v = 0, l.prim.attributes.POSITION.count - 1 do local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2) local nx, ny, nz = 0, 0, 0 if TN then nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2) end if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then table.insert(IDX, l.offset + v) table.insert(DV, x) table.insert(DV, y) table.insert(DV, z) if anyN then table.insert(DN, nx) table.insert(DN, ny) table.insert(DN, nz) end end end end end local tname = if type(names[t]) == "string" then names[t] else ("Target" .. t) local chid, shid = id(), id() local w = mesh.weights and mesh.weights[t] or 0 add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, { N("Version", "I", { 100 }), N("DeformPercent", "D", { w * 100 }), N("FullWeights", "", { arr("d", { 100 }) }), N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }), })) local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) } if anyN then table.insert(shch, N("Normals", "", { arr("d", DN) })) end add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch)) OO(chid, bsid) OO(shid, chid) local gc: any = geoChannels gc[mi] = gc[mi] or {} gc[mi][t] = chid end end local _ = prims return gid end local poseNodes: { WNode } = {} local posed: { [number]: boolean } = {} local function pose(mid: number, m: Xform.M4) if posed[mid] then return end posed[mid] = true table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) })) end local skinned: { [string]: boolean } = {} for i, nd in nodes do local mid = modelIds[i] if nd.mesh and mid then local gid = geometry(nd.mesh) if gid then OO(gid, mid) for _, m in geoSlots[nd.mesh] do local pm = matIds[m] if pm then OO(pm, mid) end end -- skin: one Skin per (geometry, skin) local skin = nd.skin and scene.skins[nd.skin] local key = tostring(gid) .. ":" .. tostring(nd.skin) if skin and not skinned[key] then skinned[key] = true local sid = id() add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) })) OO(sid, gid) local meshWorld = world(i) pose(mid, meshWorld) local ibm = accessorReader(skin.inverseBindMatrices) -- per joint: control points and weights local perJoint: { { idx: { number }, w: { number } } } = {} for j in skin.joints do perJoint[j] = { idx = {}, w = {} } end for _, l in geoVerts[nd.mesh] do local J = accessorReader(l.prim.attributes.JOINTS_0) local W = accessorReader(l.prim.attributes.WEIGHTS_0) if J and W then for v = 0, l.prim.attributes.POSITION.count - 1 do for q = 0, 3 do local j, w = J(v, q), W(v, q) local pj = perJoint[j + 1] if w > 0 and pj then table.insert(pj.idx, l.offset + v) table.insert(pj.w, w) end end end end end for j, ji in skin.joints do local jm = modelIds[ji] if jm then local IB = Xform.identity() if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then for k = 1, 16 do IB[k] = ibm(j - 1, k - 1) end end local inv = Xform.inverse(IB) or Xform.identity() local link = Xform.mul(meshWorld, inv) local cid = id() add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, { N("Version", "I", { 100 }), N("UserData", "SS", { "", "" }), N("Indexes", "", { arr("i", perJoint[j].idx) }), N("Weights", "", { arr("d", perJoint[j].w) }), N("Transform", "", { arr("d", meshWorld) }), N("TransformLink", "", { arr("d", link) }), })) OO(cid, sid) OO(jm, cid) pose(jm, link) end end end end end end if #poseNodes > 0 then local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) } for _, pn in poseNodes do table.insert(pch, pn) end add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch)) end -- ------------------------------------------------------------------------------------------ animations local tmin, tmax = math.huge, -math.huge local function curveNode(name: string, layer: number, target: number, prop: string, comps: { { number } }, times: { number }, labels: { string }, step: boolean) local cnid = id() local p = {} for k, lab in labels do table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0)) end add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) })) OO(cnid, layer) OP(cnid, target, prop) local ticks = table.create(#times, 0) for k, t in times do ticks[k] = math.floor(t * TICKS + 0.5) end for k, lab in labels do local cid = id() local df = buffer.create(32) buffer.writeu32(df, 8, 218434821) local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) } buffer.writef64(dfa.data, 16, buffer.readf32(df, 8)) add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, { N("Default", "D", { comps[k][1] or 0 }), N("KeyVer", "I", { 4009 }), N("KeyTime", "", { arr("l", ticks) }), N("KeyValueFloat", "", { arr("f", comps[k]) }), N("KeyAttrFlags", "", { arr("i", { if step then 0x00000002 else 0x00000104 }) }), N("KeyAttrDataFloat", "", { dfa }), N("KeyAttrRefCount", "", { arr("i", { #times }) }), })) OP(cid, cnid, "d|" .. lab) end end local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } } for ai, anim in scene.animations or {} do local stid, lid = id(), id() local astart, astop = math.huge, -math.huge local layerNodes = {} for _, ch in anim.channels do local mid = modelIds[ch.node] local IN = accessorReader(ch.input) local OUT = accessorReader(ch.output) local spec = PATH[ch.path] if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then local n = ch.input.count local times = table.create(n, 0) for k = 0, n - 1 do times[k + 1] = IN(k, 0) astart, astop = math.min(astart, times[k + 1]), math.max(astop, times[k + 1]) end local cubic = ch.interpolation == "CUBICSPLINE" local step = ch.interpolation == "STEP" if spec then local comps = spec[3] local function val(k: number, c: number): number local e = if cubic then k * 3 + 1 else k if e >= ch.output.count then return 0 end return OUT(e, c) end local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0) local prev: { number }? = nil for k = 0, n - 1 do local v if comps == 4 then local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) } local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) if ql > 0 then q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else q = { 0, 0, 0, 1 } end v = Xform.eulerXYZ(q) if prev then for a = 1, 3 do while v[a] - prev[a] > 180 do v[a] -= 360 end while v[a] - prev[a] < -180 do v[a] += 360 end end end prev = v else v = { val(k, 0), val(k, 1), val(k, 2) } end X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3] end table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) else -- weights: one DeformPercent curve per blend shape channel of the node's mesh local nd = nodes[ch.node] local gc: any = geoChannels local chans = nd.mesh and gc[nd.mesh] if chans then local nt = #chans for t = 1, nt do local vals = table.create(n, 0) for k = 0, n - 1 do local e = if cubic then (k * 3 + 1) * nt + (t - 1) else k * nt + (t - 1) vals[k + 1] = if e < ch.output.count then OUT(e, 0) * 100 else 0 end table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step }) end end end end end if astart > astop then astart, astop = 0, 0 end tmin, tmax = math.min(tmin, astart), math.max(tmax, astop) add("AnimationStack", N("AnimationStack", "LSS", { stid, cls(if anim.name and anim.name ~= "" then anim.name else ("Animation" .. ai), "AnimStack"), "" }, { N("Properties70", "", {}, { Ptime("LocalStart", math.floor(astart * TICKS + 0.5)), Ptime("LocalStop", math.floor(astop * TICKS + 0.5)), Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)), Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)), }), })) add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) })) OO(lid, stid) for _, ln in layerNodes do curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8]) end end if tmin > tmax then tmin, tmax = 0, 0 end -- ------------------------------------------------------------------------------------------ document local meta = scene.meta or {} local src = type(meta.source) == "table" and meta.source or {} local up = if meta.up == "z" then 2 else 1 local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1 if up == 2 then front, frontSign = 1, -1 end if src.format == "fbx" and src.upAxis == up then upSign = src.upAxisSign or upSign front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign end local unitScale = if type(meta.unit) == "number" and meta.unit > 0 then meta.unit * 100 else 1 local creator = opts and opts.creator or "formats-luau" local defs: { WNode } = { N("Version", "I", { 100 }) } local total = 1 local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" } for _, c in CLASSES do total += counts[c] or 0 end table.insert(defs, N("Count", "I", { total })) table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) })) for _, c in CLASSES do if counts[c] then table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) })) end end local docId = id() local root: WNode = { name = "", props = {}, children = { N("FBXHeaderExtension", "", {}, { N("FBXHeaderVersion", "I", { 1003 }), N("FBXVersion", "I", { opts and opts.version or 7400 }), N("CreationTimeStamp", "", {}, { N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }), N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }), }), N("Creator", "S", { creator }), }), N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }), N("CreationTime", "S", { "1970-01-01 10:00:00:000" }), N("Creator", "S", { creator }), N("GlobalSettings", "", {}, { N("Version", "I", { 1000 }), N("Properties70", "", {}, { Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign), Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign), Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale), P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0), P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"), Penum("TimeMode", 6), Penum("TimeProtocol", 2), Penum("SnapOnFrameMode", 0), Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)), Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)), Pdouble("CustomFrameRate", -1), }), }), N("Documents", "", {}, { N("Count", "I", { 1 }), N("Document", "LSS", { docId, "Scene", "Scene" }, { N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }), N("RootNode", "L", { 0 }), }), }), N("References", "", {}, {}), N("Definitions", "", {}, defs), N("Objects", "", {}, objects), N("Connections", "", {}, conns), N("Takes", "", {}, { N("Current", "S", { "" }) }), } } local _ = Err return root, nil end return Write